text
stringlengths
54
60.6k
<commit_before>#include <tamer/tamer.hh> #include <sys/select.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> namespace tamer { namespace { class driver_tamer : public driver { public: driver_tamer(); ~driver_tamer(); virtual void at_fd(int fd, int action, const event<> &e); virtual void at_time(const timeval &expiry, const event<> &e); virtual void at_asap(const event<> &e); virtual void kill_fd(int fd); virtual bool empty(); virtual void once(); virtual void loop(); private: struct ttimer { union { int schedpos; ttimer *next; } u; timeval expiry; event<> trigger; ttimer(int schedpos_, const timeval &expiry_, const event<> &trigger_) : expiry(expiry_), trigger(trigger_) { u.schedpos = schedpos_; } }; struct ttimer_group { ttimer_group *next; ttimer t[1]; }; struct tfd { int fd : 30; unsigned action : 2; event<> e; tfd *next; }; struct tfd_group { tfd_group *next; tfd t[1]; }; ttimer **_t; int _nt; tfd *_fd; int _nfds; fd_set _fdset[2]; tamerpriv::debuffer<event<> > _asap; int _tcap; ttimer_group *_tgroup; ttimer *_tfree; int _fdcap; tfd_group *_fdgroup; tfd *_fdfree; rendezvous<> _fdcancelr; void expand_timers(); void check_timers() const; void timer_reheapify_from(int pos, ttimer *t, bool will_delete); void expand_fds(); }; driver_tamer::driver_tamer() : _t(0), _nt(0), _fd(0), _nfds(0), _tcap(0), _tgroup(0), _tfree(0), _fdcap(0), _fdgroup(0), _fdfree(0) { expand_timers(); FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); set_now(); } driver_tamer::~driver_tamer() { // destroy all active timers for (int i = 0; i < _nt; i++) _t[i]->~ttimer(); // free timer groups while (_tgroup) { ttimer_group *next = _tgroup->next; delete[] reinterpret_cast<unsigned char *>(_tgroup); _tgroup = next; } delete[] _t; // destroy all active file descriptors while (_fd) { _fd->e.~event(); _fd = _fd->next; } // free file descriptor groups while (_fdgroup) { tfd_group *next = _fdgroup->next; delete[] reinterpret_cast<unsigned char *>(_fdgroup); _fdgroup = next; } } void driver_tamer::expand_timers() { int ncap = (_tcap ? _tcap * 2 : 16); ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (ncap - 1)]); ngroup->next = _tgroup; _tgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].u.next = _tfree; _tfree = &ngroup->t[i]; } ttimer **t = new ttimer *[ncap]; memcpy(t, _t, sizeof(ttimer *) * _nt); delete[] _t; _t = t; _tcap = ncap; } void driver_tamer::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/) { int npos; while (pos > 0 && (npos = (pos-1) >> 1, timercmp(&_t[npos]->expiry, &t->expiry, >))) { _t[pos] = _t[npos]; _t[npos]->u.schedpos = pos; pos = npos; } while (1) { ttimer *smallest = t; npos = 2*pos + 1; if (npos < _nt && !timercmp(&_t[npos]->expiry, &smallest->expiry, >)) smallest = _t[npos]; if (npos + 1 < _nt && !timercmp(&_t[npos+1]->expiry, &smallest->expiry, >)) smallest = _t[npos+1], npos++; smallest->u.schedpos = pos; _t[pos] = smallest; if (smallest == t) break; pos = npos; } #if 0 if (_t + 1 < tend || !will_delete) _timer_expiry = tbegin[0]->expiry; else _timer_expiry = Timestamp(); #endif } #if 0 void driver_tamer::check_timers() const { fprintf(stderr, "---"); for (int k = 0; k < _nt; k++) fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); for (int i = 0; i < _nt / 2; i++) for (int j = 2*i + 1; j < 2*i + 3; j++) if (j < _nt && timercmp(&_t[i]->expiry, &_t[j]->expiry, >)) { fprintf(stderr, "***"); for (int k = 0; k < _nt; k++) fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); assert(0); } } #endif void driver_tamer::expand_fds() { int ncap = (_fdcap ? _fdcap * 2 : 16); tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]); ngroup->next = _fdgroup; _fdgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].next = _fdfree; _fdfree = &ngroup->t[i]; } } void driver_tamer::at_fd(int fd, int action, const event<> &trigger) { if (!_fdfree) expand_fds(); if (fd >= FD_SETSIZE) throw tamer::tamer_error("file descriptor too large"); if (trigger) { tfd *t = _fdfree; _fdfree = t->next; t->next = _fd; _fd = t; t->fd = fd; t->action = action; (void) new(static_cast<void *>(&t->e)) event<>(trigger); FD_SET(fd, &_fdset[action]); if (fd >= _nfds) _nfds = fd + 1; if (action <= fdwrite) t->e.at_cancel(make_event(_fdcancelr)); } } void driver_tamer::kill_fd(int fd) { assert(fd >= 0); if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]))) { FD_CLR(fd, &_fdset[fdread]); FD_CLR(fd, &_fdset[fdwrite]); tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->fd == fd) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } } void driver_tamer::at_time(const timeval &expiry, const event<> &e) { if (!_tfree) expand_timers(); ttimer *t = _tfree; _tfree = t->u.next; (void) new(static_cast<void *>(t)) ttimer(_nt, expiry, e); _t[_nt++] = 0; timer_reheapify_from(_nt - 1, t, false); } void driver_tamer::at_asap(const event<> &e) { _asap.push_back(e); } bool driver_tamer::empty() { if (_nt != 0 || _nfds != 0 || _asap.size() != 0 || sig_any_active || tamerpriv::abstract_rendezvous::unblocked) return false; return true; } void driver_tamer::once() { // get rid of initial cancelled timers ttimer *t; while (_nt > 0 && (t = _t[0], !t->trigger)) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->~ttimer(); t->u.next = _tfree; _tfree = t; } // determine timeout struct timeval to, *toptr; if (_asap.size() || (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >)) || sig_any_active) { timerclear(&to); toptr = &to; } else if (_nt == 0) toptr = 0; else { timersub(&_t[0]->expiry, &now, &to); toptr = &to; } // get rid of canceled descriptors, if any if (_fdcancelr.nready()) { while (_fdcancelr.join()) /* nada */; FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); _nfds = 0; tfd **pprev = &_fd, *t; while ((t = *pprev)) if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else { FD_SET(t->fd, &_fdset[t->action]); if (t->fd >= _nfds) _nfds = t->fd + 1; pprev = &t->next; } } // select! fd_set fds[2]; fds[fdread] = _fdset[fdread]; fds[fdwrite] = _fdset[fdwrite]; int nfds = _nfds; if (sig_pipe[0] >= 0) { FD_SET(sig_pipe[0], &fds[fdread]); if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; } nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr); // run signals if (sig_any_active) dispatch_signals(); // run asaps while (event<> *e = _asap.front()) { e->trigger(); _asap.pop_front(); } // run file descriptors if (nfds > 0) { tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) { FD_CLR(t->fd, &_fdset[t->action]); t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } // run the timers that worked set_now(); while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->trigger.trigger(); t->~ttimer(); t->u.next = _tfree; _tfree = t; } // run active closures while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); } #if 0 void driver_tamer::print_fds() { tfd *t = _fd; while (t) { fprintf(stderr, "%d.%d ", t->fd, t->action); t = t->next; } if (_fd) fprintf(stderr, "\n"); } #endif void driver_tamer::loop() { while (1) once(); } } driver *driver::make_tamer() { return new driver_tamer; } } <commit_msg>duh: allocate enough ttimer*s<commit_after>#include <tamer/tamer.hh> #include <sys/select.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> namespace tamer { namespace { class driver_tamer : public driver { public: driver_tamer(); ~driver_tamer(); virtual void at_fd(int fd, int action, const event<> &e); virtual void at_time(const timeval &expiry, const event<> &e); virtual void at_asap(const event<> &e); virtual void kill_fd(int fd); virtual bool empty(); virtual void once(); virtual void loop(); private: struct ttimer { union { int schedpos; ttimer *next; } u; timeval expiry; event<> trigger; ttimer(int schedpos_, const timeval &expiry_, const event<> &trigger_) : expiry(expiry_), trigger(trigger_) { u.schedpos = schedpos_; } }; struct ttimer_group { ttimer_group *next; ttimer t[1]; }; struct tfd { int fd : 30; unsigned action : 2; event<> e; tfd *next; }; struct tfd_group { tfd_group *next; tfd t[1]; }; ttimer **_t; int _nt; tfd *_fd; int _nfds; fd_set _fdset[2]; tamerpriv::debuffer<event<> > _asap; int _tcap; ttimer_group *_tgroup; ttimer *_tfree; int _fdcap; tfd_group *_fdgroup; tfd *_fdfree; rendezvous<> _fdcancelr; void expand_timers(); void check_timers() const; void timer_reheapify_from(int pos, ttimer *t, bool will_delete); void expand_fds(); }; driver_tamer::driver_tamer() : _t(0), _nt(0), _fd(0), _nfds(0), _tcap(0), _tgroup(0), _tfree(0), _fdcap(0), _fdgroup(0), _fdfree(0) { expand_timers(); FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); set_now(); } driver_tamer::~driver_tamer() { // destroy all active timers for (int i = 0; i < _nt; i++) _t[i]->~ttimer(); // free timer groups while (_tgroup) { ttimer_group *next = _tgroup->next; delete[] reinterpret_cast<unsigned char *>(_tgroup); _tgroup = next; } delete[] _t; // destroy all active file descriptors while (_fd) { _fd->e.~event(); _fd = _fd->next; } // free file descriptor groups while (_fdgroup) { tfd_group *next = _fdgroup->next; delete[] reinterpret_cast<unsigned char *>(_fdgroup); _fdgroup = next; } } void driver_tamer::expand_timers() { int ncap = (_tcap ? _tcap * 2 : 16); ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (ncap - 1)]); ngroup->next = _tgroup; _tgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].u.next = _tfree; _tfree = &ngroup->t[i]; } ttimer **t = new ttimer *[_tcap + ncap]; memcpy(t, _t, sizeof(ttimer *) * _nt); delete[] _t; _t = t; _tcap = ncap; } void driver_tamer::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/) { int npos; while (pos > 0 && (npos = (pos-1) >> 1, timercmp(&_t[npos]->expiry, &t->expiry, >))) { _t[pos] = _t[npos]; _t[npos]->u.schedpos = pos; pos = npos; } while (1) { ttimer *smallest = t; npos = 2*pos + 1; if (npos < _nt && !timercmp(&_t[npos]->expiry, &smallest->expiry, >)) smallest = _t[npos]; if (npos + 1 < _nt && !timercmp(&_t[npos+1]->expiry, &smallest->expiry, >)) smallest = _t[npos+1], npos++; smallest->u.schedpos = pos; _t[pos] = smallest; if (smallest == t) break; pos = npos; } #if 0 if (_t + 1 < tend || !will_delete) _timer_expiry = tbegin[0]->expiry; else _timer_expiry = Timestamp(); #endif } #if 0 void driver_tamer::check_timers() const { fprintf(stderr, "---"); for (int k = 0; k < _nt; k++) fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); for (int i = 0; i < _nt / 2; i++) for (int j = 2*i + 1; j < 2*i + 3; j++) if (j < _nt && timercmp(&_t[i]->expiry, &_t[j]->expiry, >)) { fprintf(stderr, "***"); for (int k = 0; k < _nt; k++) fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); assert(0); } } #endif void driver_tamer::expand_fds() { int ncap = (_fdcap ? _fdcap * 2 : 16); tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]); ngroup->next = _fdgroup; _fdgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].next = _fdfree; _fdfree = &ngroup->t[i]; } } void driver_tamer::at_fd(int fd, int action, const event<> &trigger) { if (!_fdfree) expand_fds(); if (fd >= FD_SETSIZE) throw tamer::tamer_error("file descriptor too large"); if (trigger) { tfd *t = _fdfree; _fdfree = t->next; t->next = _fd; _fd = t; t->fd = fd; t->action = action; (void) new(static_cast<void *>(&t->e)) event<>(trigger); FD_SET(fd, &_fdset[action]); if (fd >= _nfds) _nfds = fd + 1; if (action <= fdwrite) t->e.at_cancel(make_event(_fdcancelr)); } } void driver_tamer::kill_fd(int fd) { assert(fd >= 0); if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]))) { FD_CLR(fd, &_fdset[fdread]); FD_CLR(fd, &_fdset[fdwrite]); tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->fd == fd) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } } void driver_tamer::at_time(const timeval &expiry, const event<> &e) { if (!_tfree) expand_timers(); ttimer *t = _tfree; _tfree = t->u.next; (void) new(static_cast<void *>(t)) ttimer(_nt, expiry, e); _t[_nt++] = 0; timer_reheapify_from(_nt - 1, t, false); } void driver_tamer::at_asap(const event<> &e) { _asap.push_back(e); } bool driver_tamer::empty() { if (_nt != 0 || _nfds != 0 || _asap.size() != 0 || sig_any_active || tamerpriv::abstract_rendezvous::unblocked) return false; return true; } void driver_tamer::once() { // get rid of initial cancelled timers ttimer *t; while (_nt > 0 && (t = _t[0], !t->trigger)) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->~ttimer(); t->u.next = _tfree; _tfree = t; } // determine timeout struct timeval to, *toptr; if (_asap.size() || (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >)) || sig_any_active) { timerclear(&to); toptr = &to; } else if (_nt == 0) toptr = 0; else { timersub(&_t[0]->expiry, &now, &to); toptr = &to; } // get rid of canceled descriptors, if any if (_fdcancelr.nready()) { while (_fdcancelr.join()) /* nada */; FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); _nfds = 0; tfd **pprev = &_fd, *t; while ((t = *pprev)) if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else { FD_SET(t->fd, &_fdset[t->action]); if (t->fd >= _nfds) _nfds = t->fd + 1; pprev = &t->next; } } // select! fd_set fds[2]; fds[fdread] = _fdset[fdread]; fds[fdwrite] = _fdset[fdwrite]; int nfds = _nfds; if (sig_pipe[0] >= 0) { FD_SET(sig_pipe[0], &fds[fdread]); if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; } nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr); // run signals if (sig_any_active) dispatch_signals(); // run asaps while (event<> *e = _asap.front()) { e->trigger(); _asap.pop_front(); } // run file descriptors if (nfds > 0) { tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) { FD_CLR(t->fd, &_fdset[t->action]); t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } // run the timers that worked set_now(); while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->trigger.trigger(); t->~ttimer(); t->u.next = _tfree; _tfree = t; } // run active closures while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); } #if 0 void driver_tamer::print_fds() { tfd *t = _fd; while (t) { fprintf(stderr, "%d.%d ", t->fd, t->action); t = t->next; } if (_fd) fprintf(stderr, "\n"); } #endif void driver_tamer::loop() { while (1) once(); } } driver *driver::make_tamer() { return new driver_tamer; } } <|endoftext|>
<commit_before>#include "tangram.h" #include "platform_osx.h" #include "data/clientGeoJsonSource.h" #include "debug/textDisplay.h" #include <cmath> #include <memory> #include <signal.h> #include <stdlib.h> // Forward declaration void init_main_window(bool recreate); std::string sceneFile = "scene.yaml"; GLFWwindow* main_window = nullptr; Tangram::Map* map = nullptr; int width = 800; int height = 600; float density = 1.0; bool recreate_context = false; float pixel_scale = 1.0; // Input handling // ============== const double double_tap_time = 0.5; // seconds const double scroll_span_multiplier = 0.05; // scaling for zoom and rotation const double scroll_distance_multiplier = 5.0; // scaling for shove const double single_tap_time = 0.25; //seconds (to avoid a long press being considered as a tap) bool was_panning = false; double last_time_released = -double_tap_time; // First click should never trigger a double tap double last_time_pressed = 0.0; double last_time_moved = 0.0; double last_x_down = 0.0; double last_y_down = 0.0; double last_x_velocity = 0.0; double last_y_velocity = 0.0; using namespace Tangram; std::shared_ptr<ClientGeoJsonSource> data_source; LngLat last_point; template<typename T> static constexpr T clamp(T val, T min, T max) { return val > max ? max : val < min ? min : val; } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button != GLFW_MOUSE_BUTTON_1) { return; // This event is for a mouse button that we don't care about } double x, y; glfwGetCursorPos(window, &x, &y); x *= density; y *= density; double time = glfwGetTime(); if (was_panning && action == GLFW_RELEASE) { was_panning = false; auto vx = clamp(last_x_velocity, -2000.0, 2000.0); auto vy = clamp(last_y_velocity, -2000.0, 2000.0); map->handleFlingGesture(x, y, vx, vy); return; // Clicks with movement don't count as taps, so stop here } if (action == GLFW_PRESS) { map->handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f); last_x_down = x; last_y_down = y; last_time_pressed = time; return; } if ((time - last_time_released) < double_tap_time) { // Double tap recognized LngLat p; map->screenPositionToLngLat(x, y, &p.longitude, &p.latitude); map->setPositionEased(p.longitude, p.latitude, 1.f); logMsg("pick feature\n"); map->clearDataSource(*data_source, true, true); auto picks = map->pickFeaturesAt(x, y); std::string name; logMsg("picked %d features\n", picks.size()); for (const auto& it : picks) { if (it.properties->getString("name", name)) { logMsg(" - %f\t %s\n", it.distance, name.c_str()); } } } else if ((time - last_time_pressed) < single_tap_time) { // Single tap recognized LngLat p1; map->screenPositionToLngLat(x, y, &p1.longitude, &p1.latitude); if (!(last_point == LngLat{0, 0})) { LngLat p2 = last_point; logMsg("add line %f %f - %f %f\n", p1.longitude, p1.latitude, p2.longitude, p2.latitude); // data_source->addLine(Properties{{"type", "line" }}, {p1, p2}); // data_source->addPoint(Properties{{"type", "point" }}, p2); Properties prop1; prop1.set("type", "line"); data_source->addLine(prop1, {p1, p2}); Properties prop2; prop2.set("type", "point"); data_source->addPoint(prop2, p2); } last_point = p1; // Tangram::clearDataSource(*data_source, false, true); // This updates the tiles (maybe we need a recalcTiles()) requestRender(); } last_time_released = time; } void cursor_pos_callback(GLFWwindow* window, double x, double y) { x *= density; y *= density; int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1); double time = glfwGetTime(); if (action == GLFW_PRESS) { if (was_panning) { map->handlePanGesture(last_x_down, last_y_down, x, y); } was_panning = true; last_x_velocity = (x - last_x_down) / (time - last_time_moved); last_y_velocity = (y - last_y_down) / (time - last_time_moved); last_x_down = x; last_y_down = y; } last_time_moved = time; } void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) { double x, y; glfwGetCursorPos(window, &x, &y); x *= density; y *= density; bool rotating = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS; bool shoving = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS; if (shoving) { map->handleShoveGesture(scroll_distance_multiplier * scrolly); } else if (rotating) { map->handleRotateGesture(x, y, scroll_span_multiplier * scrolly); } else { map->handlePinchGesture(x, y, 1.0 + scroll_span_multiplier * scrolly, 0.f); } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_1: Tangram::toggleDebugFlag(Tangram::DebugFlags::freeze_tiles); break; case GLFW_KEY_2: Tangram::toggleDebugFlag(Tangram::DebugFlags::proxy_colors); break; case GLFW_KEY_3: Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_bounds); break; case GLFW_KEY_4: Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_infos); break; case GLFW_KEY_5: Tangram::toggleDebugFlag(Tangram::DebugFlags::labels); break; case GLFW_KEY_6: Tangram::toggleDebugFlag(Tangram::DebugFlags::draw_all_labels); break; case GLFW_KEY_7: Tangram::toggleDebugFlag(Tangram::DebugFlags::tangram_infos); break; case GLFW_KEY_8: Tangram::toggleDebugFlag(Tangram::DebugFlags::tangram_stats); break; case GLFW_KEY_BACKSPACE: recreate_context = true; break; case GLFW_KEY_R: map->loadSceneAsync(sceneFile.c_str()); break; case GLFW_KEY_Z: map->setZoomEased(map->getZoom() + 1.f, 1.5f); break; case GLFW_KEY_N: map->setRotationEased(0.f, 1.f); break; case GLFW_KEY_S: if (pixel_scale == 1.0) { pixel_scale = 2.0; } else if (pixel_scale == 2.0) { pixel_scale = 0.75; } else { pixel_scale = 1.0; } map->loadSceneAsync(sceneFile.c_str()); map->setPixelScale(pixel_scale); break; case GLFW_KEY_P: map->queueSceneUpdate("cameras", "{ main_camera: { type: perspective } }"); map->applySceneUpdates(); break; case GLFW_KEY_I: map->queueSceneUpdate("cameras", "{ main_camera: { type: isometric } }"); map->applySceneUpdates(); break; case GLFW_KEY_G: static bool geoJSON = false; if (!geoJSON) { LOGS("Switching to GeoJSON data source"); map->queueSceneUpdate("sources.osm.type", "GeoJSON"); map->queueSceneUpdate("sources.osm.url", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.json"); } else { LOGS("Switching to MVT data source"); map->queueSceneUpdate("sources.osm.type", "MVT"); map->queueSceneUpdate("sources.osm.url", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt"); } geoJSON = !geoJSON; map->applySceneUpdates(); break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(main_window, true); break; case GLFW_KEY_F1: map->setPosition(-74.00976419448854, 40.70532700869127); map->setZoom(16); break; case GLFW_KEY_F2: map->setPosition(8.82, 53.08); map->setZoom(14); break; default: break; } } } void drop_callback(GLFWwindow* window, int count, const char** paths) { sceneFile = std::string(paths[0]); map->loadSceneAsync(sceneFile.c_str()); } // Window handling // =============== void framebuffer_size_callback(GLFWwindow* window, int fWidth, int fHeight) { int wWidth = 0, wHeight = 0; glfwGetWindowSize(main_window, &wWidth, &wHeight); float new_density = (float)fWidth / (float)wWidth; if (new_density != density) { recreate_context = true; density = new_density; } map->setPixelScale(density); map->resize(fWidth, fHeight); } void init_main_window(bool recreate) { // Setup tangram if (!map) { map = new Tangram::Map(); map->loadSceneAsync(sceneFile.c_str(), true); } if (!recreate) { // Destroy old window if (main_window != nullptr) { glfwDestroyWindow(main_window); } // Create a windowed mode window and its OpenGL context glfwWindowHint(GLFW_SAMPLES, 2); main_window = glfwCreateWindow(width, height, "Tangram ES", NULL, NULL); if (!main_window) { glfwTerminate(); } // Make the main_window's context current glfwMakeContextCurrent(main_window); // Set input callbacks glfwSetFramebufferSizeCallback(main_window, framebuffer_size_callback); glfwSetMouseButtonCallback(main_window, mouse_button_callback); glfwSetCursorPosCallback(main_window, cursor_pos_callback); glfwSetScrollCallback(main_window, scroll_callback); glfwSetKeyCallback(main_window, key_callback); glfwSetDropCallback(main_window, drop_callback); } // Setup graphics map->setupGL(); int fWidth = 0, fHeight = 0; glfwGetFramebufferSize(main_window, &fWidth, &fHeight); framebuffer_size_callback(main_window, fWidth, fHeight); data_source = std::make_shared<ClientGeoJsonSource>("touch", ""); map->addDataSource(data_source); } // Main program // ============ int main(int argc, char* argv[]) { static bool keepRunning = true; // Give it a chance to shutdown cleanly on CTRL-C signal(SIGINT, [](int) { if (keepRunning) { logMsg("shutdown\n"); keepRunning = false; glfwPostEmptyEvent(); } else { logMsg("killed!\n"); exit(1); }}); int argi = 0; while (++argi < argc) { if (strcmp(argv[argi - 1], "-f") == 0) { sceneFile = std::string(argv[argi]); logMsg("File from command line: %s\n", argv[argi]); break; } } // Initialize networking NSurlInit(); // Initialize the windowing library if (!glfwInit()) { return -1; } init_main_window(false); double lastTime = glfwGetTime(); // Loop until the user closes the window while (keepRunning && !glfwWindowShouldClose(main_window)) { double currentTime = glfwGetTime(); double delta = currentTime - lastTime; lastTime = currentTime; // Render map->update(delta); map->render(); // Swap front and back buffers glfwSwapBuffers(main_window); // Poll for and process events if (isContinuousRendering()) { glfwPollEvents(); } else { glfwWaitEvents(); } if (recreate_context) { logMsg("recreate context\n"); // Simulate GL context loss init_main_window(true); recreate_context = false; } } finishUrlRequests(); if (map) { delete map; map = nullptr; } glfwTerminate(); return 0; } <commit_msg>Marker testing<commit_after>#include "tangram.h" #include "platform_osx.h" #include "data/clientGeoJsonSource.h" #include "debug/textDisplay.h" #include <cmath> #include <memory> #include <signal.h> #include <stdlib.h> // Forward declaration void init_main_window(bool recreate); std::string sceneFile = "scene.yaml"; std::string markerStyling = "{ style: 'lines', color: 'purple', width: 10px, order: 100 }"; GLFWwindow* main_window = nullptr; Tangram::Map* map = nullptr; int width = 800; int height = 600; float density = 1.0; bool recreate_context = false; float pixel_scale = 1.0; // Input handling // ============== const double double_tap_time = 0.5; // seconds const double scroll_span_multiplier = 0.05; // scaling for zoom and rotation const double scroll_distance_multiplier = 5.0; // scaling for shove const double single_tap_time = 0.25; //seconds (to avoid a long press being considered as a tap) bool was_panning = false; double last_time_released = -double_tap_time; // First click should never trigger a double tap double last_time_pressed = 0.0; double last_time_moved = 0.0; double last_x_down = 0.0; double last_y_down = 0.0; double last_x_velocity = 0.0; double last_y_velocity = 0.0; using namespace Tangram; std::shared_ptr<ClientGeoJsonSource> data_source; LngLat last_point; std::vector<LngLat> taps; Marker* marker = nullptr; template<typename T> static constexpr T clamp(T val, T min, T max) { return val > max ? max : val < min ? min : val; } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button != GLFW_MOUSE_BUTTON_1) { return; // This event is for a mouse button that we don't care about } double x, y; glfwGetCursorPos(window, &x, &y); x *= density; y *= density; double time = glfwGetTime(); if (was_panning && action == GLFW_RELEASE) { was_panning = false; auto vx = clamp(last_x_velocity, -2000.0, 2000.0); auto vy = clamp(last_y_velocity, -2000.0, 2000.0); map->handleFlingGesture(x, y, vx, vy); return; // Clicks with movement don't count as taps, so stop here } if (action == GLFW_PRESS) { map->handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f); last_x_down = x; last_y_down = y; last_time_pressed = time; return; } if ((time - last_time_released) < double_tap_time) { // Double tap recognized LngLat p; map->screenPositionToLngLat(x, y, &p.longitude, &p.latitude); map->setPositionEased(p.longitude, p.latitude, 1.f); logMsg("pick feature\n"); map->clearDataSource(*data_source, true, true); auto picks = map->pickFeaturesAt(x, y); std::string name; logMsg("picked %d features\n", picks.size()); for (const auto& it : picks) { if (it.properties->getString("name", name)) { logMsg(" - %f\t %s\n", it.distance, name.c_str()); } } } else if ((time - last_time_pressed) < single_tap_time) { // Single tap recognized LngLat p1; map->screenPositionToLngLat(x, y, &p1.longitude, &p1.latitude); taps.push_back(p1); if (!(last_point == LngLat{0, 0})) { LngLat p2 = last_point; logMsg("add line (%f, %f) (%f, %f)\n", p1.longitude, p1.latitude, p2.longitude, p2.latitude); if (!marker) { marker = map->markerAdd(markerStyling.c_str()); } map->markerSetPolyline(marker, taps.data(), taps.size()); } last_point = p1; // Tangram::clearDataSource(*data_source, false, true); // This updates the tiles (maybe we need a recalcTiles()) requestRender(); } last_time_released = time; } void cursor_pos_callback(GLFWwindow* window, double x, double y) { x *= density; y *= density; int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1); double time = glfwGetTime(); if (action == GLFW_PRESS) { if (was_panning) { map->handlePanGesture(last_x_down, last_y_down, x, y); } was_panning = true; last_x_velocity = (x - last_x_down) / (time - last_time_moved); last_y_velocity = (y - last_y_down) / (time - last_time_moved); last_x_down = x; last_y_down = y; } last_time_moved = time; } void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) { double x, y; glfwGetCursorPos(window, &x, &y); x *= density; y *= density; bool rotating = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS; bool shoving = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS; if (shoving) { map->handleShoveGesture(scroll_distance_multiplier * scrolly); } else if (rotating) { map->handleRotateGesture(x, y, scroll_span_multiplier * scrolly); } else { map->handlePinchGesture(x, y, 1.0 + scroll_span_multiplier * scrolly, 0.f); } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_1: Tangram::toggleDebugFlag(Tangram::DebugFlags::freeze_tiles); break; case GLFW_KEY_2: Tangram::toggleDebugFlag(Tangram::DebugFlags::proxy_colors); break; case GLFW_KEY_3: Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_bounds); break; case GLFW_KEY_4: Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_infos); break; case GLFW_KEY_5: Tangram::toggleDebugFlag(Tangram::DebugFlags::labels); break; case GLFW_KEY_6: Tangram::toggleDebugFlag(Tangram::DebugFlags::draw_all_labels); break; case GLFW_KEY_7: Tangram::toggleDebugFlag(Tangram::DebugFlags::tangram_infos); break; case GLFW_KEY_8: Tangram::toggleDebugFlag(Tangram::DebugFlags::tangram_stats); break; case GLFW_KEY_BACKSPACE: recreate_context = true; break; case GLFW_KEY_R: map->loadSceneAsync(sceneFile.c_str()); break; case GLFW_KEY_Z: map->setZoomEased(map->getZoom() + 1.f, 1.5f); break; case GLFW_KEY_N: map->setRotationEased(0.f, 1.f); break; case GLFW_KEY_S: if (pixel_scale == 1.0) { pixel_scale = 2.0; } else if (pixel_scale == 2.0) { pixel_scale = 0.75; } else { pixel_scale = 1.0; } map->loadSceneAsync(sceneFile.c_str()); map->setPixelScale(pixel_scale); break; case GLFW_KEY_P: map->queueSceneUpdate("cameras", "{ main_camera: { type: perspective } }"); map->applySceneUpdates(); break; case GLFW_KEY_I: map->queueSceneUpdate("cameras", "{ main_camera: { type: isometric } }"); map->applySceneUpdates(); break; case GLFW_KEY_G: static bool geoJSON = false; if (!geoJSON) { LOGS("Switching to GeoJSON data source"); map->queueSceneUpdate("sources.osm.type", "GeoJSON"); map->queueSceneUpdate("sources.osm.url", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.json"); } else { LOGS("Switching to MVT data source"); map->queueSceneUpdate("sources.osm.type", "MVT"); map->queueSceneUpdate("sources.osm.url", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt"); } geoJSON = !geoJSON; map->applySceneUpdates(); break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(main_window, true); break; case GLFW_KEY_F1: map->setPosition(-74.00976419448854, 40.70532700869127); map->setZoom(16); break; case GLFW_KEY_F2: map->setPosition(8.82, 53.08); map->setZoom(14); break; default: break; } } } void drop_callback(GLFWwindow* window, int count, const char** paths) { sceneFile = std::string(paths[0]); map->loadSceneAsync(sceneFile.c_str()); } // Window handling // =============== void framebuffer_size_callback(GLFWwindow* window, int fWidth, int fHeight) { int wWidth = 0, wHeight = 0; glfwGetWindowSize(main_window, &wWidth, &wHeight); float new_density = (float)fWidth / (float)wWidth; if (new_density != density) { recreate_context = true; density = new_density; } map->setPixelScale(density); map->resize(fWidth, fHeight); } void init_main_window(bool recreate) { // Setup tangram if (!map) { map = new Tangram::Map(); map->loadSceneAsync(sceneFile.c_str(), true); } if (!recreate) { // Destroy old window if (main_window != nullptr) { glfwDestroyWindow(main_window); } // Create a windowed mode window and its OpenGL context glfwWindowHint(GLFW_SAMPLES, 2); main_window = glfwCreateWindow(width, height, "Tangram ES", NULL, NULL); if (!main_window) { glfwTerminate(); } // Make the main_window's context current glfwMakeContextCurrent(main_window); // Set input callbacks glfwSetFramebufferSizeCallback(main_window, framebuffer_size_callback); glfwSetMouseButtonCallback(main_window, mouse_button_callback); glfwSetCursorPosCallback(main_window, cursor_pos_callback); glfwSetScrollCallback(main_window, scroll_callback); glfwSetKeyCallback(main_window, key_callback); glfwSetDropCallback(main_window, drop_callback); } // Setup graphics map->setupGL(); int fWidth = 0, fHeight = 0; glfwGetFramebufferSize(main_window, &fWidth, &fHeight); framebuffer_size_callback(main_window, fWidth, fHeight); data_source = std::make_shared<ClientGeoJsonSource>("touch", ""); map->addDataSource(data_source); } // Main program // ============ int main(int argc, char* argv[]) { static bool keepRunning = true; // Give it a chance to shutdown cleanly on CTRL-C signal(SIGINT, [](int) { if (keepRunning) { logMsg("shutdown\n"); keepRunning = false; glfwPostEmptyEvent(); } else { logMsg("killed!\n"); exit(1); }}); int argi = 0; while (++argi < argc) { if (strcmp(argv[argi - 1], "-f") == 0) { sceneFile = std::string(argv[argi]); logMsg("File from command line: %s\n", argv[argi]); break; } } // Initialize networking NSurlInit(); // Initialize the windowing library if (!glfwInit()) { return -1; } init_main_window(false); double lastTime = glfwGetTime(); // Loop until the user closes the window while (keepRunning && !glfwWindowShouldClose(main_window)) { double currentTime = glfwGetTime(); double delta = currentTime - lastTime; lastTime = currentTime; // Render map->update(delta); map->render(); // Swap front and back buffers glfwSwapBuffers(main_window); // Poll for and process events if (isContinuousRendering()) { glfwPollEvents(); } else { glfwWaitEvents(); } if (recreate_context) { logMsg("recreate context\n"); // Simulate GL context loss init_main_window(true); recreate_context = false; } } finishUrlRequests(); if (map) { delete map; map = nullptr; } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2011-2016 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * 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 <Core/Controller.h> /************************************************************************* * * Implements Core::Controller methods pertaining selecting an application * process to handle the current request. * *************************************************************************/ namespace Passenger { namespace Core { using namespace std; using namespace boost; /**************************** * * Private methods * ****************************/ void Controller::checkoutSession(Client *client, Request *req) { GetCallback callback; Options &options = req->options; CC_BENCHMARK_POINT(client, req, BM_BEFORE_CHECKOUT); SKC_TRACE(client, 2, "Checking out session: appRoot=" << options.appRoot); req->state = Request::CHECKING_OUT_SESSION; if (req->requestBodyBuffering) { assert(!req->bodyBuffer.isStarted()); } else { assert(!req->bodyChannel.isStarted()); } callback.func = sessionCheckedOut; callback.userData = req; options.currentTime = SystemTime::getUsec(); refRequest(req, __FILE__, __LINE__); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING req->timeBeforeAccessingApplicationPool = ev_now(getLoop()); #endif asyncGetFromApplicationPool(req, callback); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING if (!req->timedAppPoolGet) { req->timedAppPoolGet = true; ev_now_update(getLoop()); reportLargeTimeDiff(client, "ApplicationPool get until return", req->timeBeforeAccessingApplicationPool, ev_now(getLoop())); } #endif } void Controller::asyncGetFromApplicationPool(Request *req, ApplicationPool2::GetCallback callback) { appPool->asyncGet(req->options, callback, true, req->useUnionStation() ? &req->stopwatchLogs.getFromPool : NULL); } void Controller::sessionCheckedOut(const AbstractSessionPtr &session, const ExceptionPtr &e, void *userData) { Request *req = static_cast<Request *>(userData); Client *client = static_cast<Client *>(req->client); Controller *self = static_cast<Controller *>(getServerFromClient(client)); if (self->getContext()->libev->onEventLoopThread()) { self->sessionCheckedOutFromEventLoopThread(client, req, session, e); self->unrefRequest(req, __FILE__, __LINE__); } else { self->getContext()->libev->runLater( boost::bind(&Controller::sessionCheckedOutFromAnotherThread, self, client, req, session, e)); } } void Controller::sessionCheckedOutFromAnotherThread(Client *client, Request *req, AbstractSessionPtr session, ExceptionPtr e) { SKC_LOG_EVENT(Controller, client, "sessionCheckedOutFromAnotherThread"); sessionCheckedOutFromEventLoopThread(client, req, session, e); unrefRequest(req, __FILE__, __LINE__); } void Controller::sessionCheckedOutFromEventLoopThread(Client *client, Request *req, const AbstractSessionPtr &session, const ExceptionPtr &e) { if (req->ended()) { return; } TRACE_POINT(); CC_BENCHMARK_POINT(client, req, BM_AFTER_CHECKOUT); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING if (!req->timedAppPoolGet) { req->timedAppPoolGet = true; ev_now_update(getLoop()); reportLargeTimeDiff(client, "ApplicationPool get until return", req->timeBeforeAccessingApplicationPool, ev_now(getLoop())); } #endif if (e == NULL) { SKC_DEBUG(client, "Session checked out: pid=" << session->getPid() << ", gupid=" << session->getGupid()); req->session = session; UPDATE_TRACE_POINT(); maybeSend100Continue(client, req); UPDATE_TRACE_POINT(); initiateSession(client, req); } else { UPDATE_TRACE_POINT(); req->endStopwatchLog(&req->stopwatchLogs.getFromPool, false); reportSessionCheckoutError(client, req, e); } } void Controller::maybeSend100Continue(Client *client, Request *req) { int httpVersion = req->httpMajor * 1000 + req->httpMinor * 10; if (httpVersion >= 1010 && req->hasBody() && !req->strip100ContinueHeader) { // Apps with the "session" protocol don't respond with 100-Continue, // so we do it for them. const LString *value = req->headers.lookup(HTTP_EXPECT); if (value != NULL && psg_lstr_cmp(value, P_STATIC_STRING("100-continue")) && req->session->getProtocol() == P_STATIC_STRING("session")) { const unsigned int BUFSIZE = 32; char *buf = (char *) psg_pnalloc(req->pool, BUFSIZE); int size = snprintf(buf, BUFSIZE, "HTTP/%d.%d 100 Continue\r\n", (int) req->httpMajor, (int) req->httpMinor); writeResponse(client, buf, size); if (!req->ended()) { // Allow sending more response headers. req->responseBegun = false; } } } } void Controller::initiateSession(Client *client, Request *req) { TRACE_POINT(); req->sessionCheckoutTry++; try { req->session->initiate(false); } catch (const SystemException &e2) { if (req->sessionCheckoutTry < MAX_SESSION_CHECKOUT_TRY) { SKC_DEBUG(client, "Error checking out session (" << e2.what() << "); retrying (attempt " << req->sessionCheckoutTry << ")"); refRequest(req, __FILE__, __LINE__); getContext()->libev->runLater(boost::bind(checkoutSessionLater, req)); } else { string message = "could not initiate a session ("; message.append(e2.what()); message.append(")"); disconnectWithError(&client, message); } return; } UPDATE_TRACE_POINT(); if (req->useUnionStation()) { req->endStopwatchLog(&req->stopwatchLogs.getFromPool); req->logMessage("Application PID: " + toString(req->session->getPid()) + " (GUPID: " + req->session->getGupid() + ")"); req->beginStopwatchLog(&req->stopwatchLogs.requestProxying, "request proxying"); } UPDATE_TRACE_POINT(); SKC_DEBUG(client, "Session initiated: fd=" << req->session->fd()); req->appSink.reinitialize(req->session->fd()); req->appSource.reinitialize(req->session->fd()); /***************/ /***************/ reinitializeAppResponse(client, req); sendHeaderToApp(client, req); } void Controller::checkoutSessionLater(Request *req) { Client *client = static_cast<Client *>(req->client); Controller *self = static_cast<Controller *>( Controller::getServerFromClient(client)); SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "checkoutSessionLater"); if (!req->ended()) { self->checkoutSession(client, req); } self->unrefRequest(req, __FILE__, __LINE__); } void Controller::reportSessionCheckoutError(Client *client, Request *req, const ExceptionPtr &e) { TRACE_POINT(); { boost::shared_ptr<RequestQueueFullException> e2 = dynamic_pointer_cast<RequestQueueFullException>(e); if (e2 != NULL) { writeRequestQueueFullExceptionErrorResponse(client, req, e2); return; } } { boost::shared_ptr<SpawnException> e2 = dynamic_pointer_cast<SpawnException>(e); if (e2 != NULL) { writeSpawnExceptionErrorResponse(client, req, e2); return; } } writeOtherExceptionErrorResponse(client, req, e); } void Controller::writeRequestQueueFullExceptionErrorResponse(Client *client, Request *req, const boost::shared_ptr<RequestQueueFullException> &e) { TRACE_POINT(); const LString *value = req->secureHeaders.lookup( "!~PASSENGER_REQUEST_QUEUE_OVERFLOW_STATUS_CODE"); int requestQueueOverflowStatusCode = 503; if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); requestQueueOverflowStatusCode = stringToInt( StaticString(value->start->data, value->size)); } SKC_WARN(client, "Returning HTTP " << requestQueueOverflowStatusCode << " due to: " << e->what()); endRequestWithSimpleResponse(&client, &req, "<h2>This website is under heavy load (queue full)</h2>" "<p>We're sorry, too many people are accessing this website at the same " "time. We're working on this problem. Please try again later.</p>", requestQueueOverflowStatusCode); } void Controller::writeSpawnExceptionErrorResponse(Client *client, Request *req, const boost::shared_ptr<SpawnException> &e) { TRACE_POINT(); SKC_ERROR(client, "Cannot checkout session because a spawning error occurred. " << "The identifier of the error is " << e->get("error_id") << ". Please see earlier logs for " << "details about the error."); endRequestWithErrorResponse(&client, &req, e->getErrorPage(), e.get()); } void Controller::writeOtherExceptionErrorResponse(Client *client, Request *req, const ExceptionPtr &e) { TRACE_POINT(); string typeName; #ifdef CXX_ABI_API_AVAILABLE int status; char *tmp = abi::__cxa_demangle(typeid(*e).name(), 0, 0, &status); if (tmp != NULL) { typeName = tmp; free(tmp); } else { typeName = typeid(*e).name(); } #else typeName = typeid(*e).name(); #endif const unsigned int exceptionMessageLen = strlen(e->what()); string backtrace; boost::shared_ptr<tracable_exception> e3 = dynamic_pointer_cast<tracable_exception>(e); if (e3 != NULL) { backtrace = e3->backtrace(); } SKC_WARN(client, "Cannot checkout session due to " << typeName << ": " << e->what() << (!backtrace.empty() ? "\n" + backtrace : "")); if (friendlyErrorPagesEnabled(req)) { const unsigned int BUFFER_SIZE = 512 + typeName.size() + exceptionMessageLen + backtrace.size(); char *buf = (char *) psg_pnalloc(req->pool, BUFFER_SIZE); char *pos = buf; const char *end = buf + BUFFER_SIZE; pos = appendData(pos, end, "<h2>Internal server error</h2>"); pos = appendData(pos, end, "<p>Application could not be started.</p>"); pos = appendData(pos, end, "<p>Exception type: "); pos = appendData(pos, end, typeName); pos = appendData(pos, end, "<br>Error message: "); pos = appendData(pos, end, e->what(), exceptionMessageLen); if (!backtrace.empty()) { pos = appendData(pos, end, "<br>Backtrace:<br>"); pos = appendData(pos, end, backtrace); } pos = appendData(pos, end, "</p>"); endRequestWithSimpleResponse(&client, &req, StaticString(buf, pos - buf), 500); } else { endRequestWithSimpleResponse(&client, &req, "<h2>Internal server error</h2>" "Application could not be started. Please try again later.", 500); } } /** * `message` will be copied and doesn't need to outlive the request. */ void Controller::endRequestWithErrorResponse(Client **c, Request **r, const StaticString &message, const SpawnException *e) { TRACE_POINT(); Client *client = *c; Request *req = *r; ErrorRenderer renderer(*resourceLocator); string data; if (friendlyErrorPagesEnabled(req)) { try { data = renderer.renderWithDetails(message, req->options, e); } catch (const SystemException &e2) { SKC_ERROR(client, "Cannot render an error page: " << e2.what() << "\n" << e2.backtrace()); data = message; } } else { try { data = renderer.renderWithoutDetails(e); } catch (const SystemException &e2) { SKC_ERROR(client, "Cannot render an error page: " << e2.what() << "\n" << e2.backtrace()); data = "<h2>Internal server error</h2>"; } } endRequestWithSimpleResponse(c, r, psg_pstrdup(req->pool, data), 500); } bool Controller::friendlyErrorPagesEnabled(Request *req) { bool defaultValue; string defaultStr = agentsOptions->get("friendly_error_pages"); if (defaultStr == "auto") { defaultValue = (req->options.environment == "development"); } else { defaultValue = defaultStr == "true"; } return getBoolOption(req, "!~PASSENGER_FRIENDLY_ERROR_PAGES", defaultValue); } /***************/ /***************/ } // namespace Core } // namespace Passenger <commit_msg>Fix compilation warning on Clang<commit_after>/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2011-2016 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * 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 <Core/Controller.h> /************************************************************************* * * Implements Core::Controller methods pertaining selecting an application * process to handle the current request. * *************************************************************************/ namespace Passenger { namespace Core { using namespace std; using namespace boost; /**************************** * * Private methods * ****************************/ void Controller::checkoutSession(Client *client, Request *req) { GetCallback callback; Options &options = req->options; CC_BENCHMARK_POINT(client, req, BM_BEFORE_CHECKOUT); SKC_TRACE(client, 2, "Checking out session: appRoot=" << options.appRoot); req->state = Request::CHECKING_OUT_SESSION; if (req->requestBodyBuffering) { assert(!req->bodyBuffer.isStarted()); } else { assert(!req->bodyChannel.isStarted()); } callback.func = sessionCheckedOut; callback.userData = req; options.currentTime = SystemTime::getUsec(); refRequest(req, __FILE__, __LINE__); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING req->timeBeforeAccessingApplicationPool = ev_now(getLoop()); #endif asyncGetFromApplicationPool(req, callback); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING if (!req->timedAppPoolGet) { req->timedAppPoolGet = true; ev_now_update(getLoop()); reportLargeTimeDiff(client, "ApplicationPool get until return", req->timeBeforeAccessingApplicationPool, ev_now(getLoop())); } #endif } void Controller::asyncGetFromApplicationPool(Request *req, ApplicationPool2::GetCallback callback) { appPool->asyncGet(req->options, callback, true, req->useUnionStation() ? &req->stopwatchLogs.getFromPool : NULL); } void Controller::sessionCheckedOut(const AbstractSessionPtr &session, const ExceptionPtr &e, void *userData) { Request *req = static_cast<Request *>(userData); Client *client = static_cast<Client *>(req->client); Controller *self = static_cast<Controller *>(getServerFromClient(client)); if (self->getContext()->libev->onEventLoopThread()) { self->sessionCheckedOutFromEventLoopThread(client, req, session, e); self->unrefRequest(req, __FILE__, __LINE__); } else { self->getContext()->libev->runLater( boost::bind(&Controller::sessionCheckedOutFromAnotherThread, self, client, req, session, e)); } } void Controller::sessionCheckedOutFromAnotherThread(Client *client, Request *req, AbstractSessionPtr session, ExceptionPtr e) { SKC_LOG_EVENT(Controller, client, "sessionCheckedOutFromAnotherThread"); sessionCheckedOutFromEventLoopThread(client, req, session, e); unrefRequest(req, __FILE__, __LINE__); } void Controller::sessionCheckedOutFromEventLoopThread(Client *client, Request *req, const AbstractSessionPtr &session, const ExceptionPtr &e) { if (req->ended()) { return; } TRACE_POINT(); CC_BENCHMARK_POINT(client, req, BM_AFTER_CHECKOUT); #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING if (!req->timedAppPoolGet) { req->timedAppPoolGet = true; ev_now_update(getLoop()); reportLargeTimeDiff(client, "ApplicationPool get until return", req->timeBeforeAccessingApplicationPool, ev_now(getLoop())); } #endif if (e == NULL) { SKC_DEBUG(client, "Session checked out: pid=" << session->getPid() << ", gupid=" << session->getGupid()); req->session = session; UPDATE_TRACE_POINT(); maybeSend100Continue(client, req); UPDATE_TRACE_POINT(); initiateSession(client, req); } else { UPDATE_TRACE_POINT(); req->endStopwatchLog(&req->stopwatchLogs.getFromPool, false); reportSessionCheckoutError(client, req, e); } } void Controller::maybeSend100Continue(Client *client, Request *req) { int httpVersion = req->httpMajor * 1000 + req->httpMinor * 10; if (httpVersion >= 1010 && req->hasBody() && !req->strip100ContinueHeader) { // Apps with the "session" protocol don't respond with 100-Continue, // so we do it for them. const LString *value = req->headers.lookup(HTTP_EXPECT); if (value != NULL && psg_lstr_cmp(value, P_STATIC_STRING("100-continue")) && req->session->getProtocol() == P_STATIC_STRING("session")) { const unsigned int BUFSIZE = 32; char *buf = (char *) psg_pnalloc(req->pool, BUFSIZE); int size = snprintf(buf, BUFSIZE, "HTTP/%d.%d 100 Continue\r\n", (int) req->httpMajor, (int) req->httpMinor); writeResponse(client, buf, size); if (!req->ended()) { // Allow sending more response headers. req->responseBegun = false; } } } } void Controller::initiateSession(Client *client, Request *req) { TRACE_POINT(); req->sessionCheckoutTry++; try { req->session->initiate(false); } catch (const SystemException &e2) { if (req->sessionCheckoutTry < MAX_SESSION_CHECKOUT_TRY) { SKC_DEBUG(client, "Error checking out session (" << e2.what() << "); retrying (attempt " << req->sessionCheckoutTry << ")"); refRequest(req, __FILE__, __LINE__); getContext()->libev->runLater(boost::bind(checkoutSessionLater, req)); } else { string message = "could not initiate a session ("; message.append(e2.what()); message.append(")"); disconnectWithError(&client, message); } return; } UPDATE_TRACE_POINT(); if (req->useUnionStation()) { req->endStopwatchLog(&req->stopwatchLogs.getFromPool); req->logMessage("Application PID: " + toString(req->session->getPid()) + " (GUPID: " + req->session->getGupid() + ")"); req->beginStopwatchLog(&req->stopwatchLogs.requestProxying, "request proxying"); } UPDATE_TRACE_POINT(); SKC_DEBUG(client, "Session initiated: fd=" << req->session->fd()); req->appSink.reinitialize(req->session->fd()); req->appSource.reinitialize(req->session->fd()); /***************/ /***************/ reinitializeAppResponse(client, req); sendHeaderToApp(client, req); } void Controller::checkoutSessionLater(Request *req) { Client *client = static_cast<Client *>(req->client); Controller *self = static_cast<Controller *>( Controller::getServerFromClient(client)); SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "checkoutSessionLater"); if (!req->ended()) { self->checkoutSession(client, req); } self->unrefRequest(req, __FILE__, __LINE__); } void Controller::reportSessionCheckoutError(Client *client, Request *req, const ExceptionPtr &e) { TRACE_POINT(); { boost::shared_ptr<RequestQueueFullException> e2 = dynamic_pointer_cast<RequestQueueFullException>(e); if (e2 != NULL) { writeRequestQueueFullExceptionErrorResponse(client, req, e2); return; } } { boost::shared_ptr<SpawnException> e2 = dynamic_pointer_cast<SpawnException>(e); if (e2 != NULL) { writeSpawnExceptionErrorResponse(client, req, e2); return; } } writeOtherExceptionErrorResponse(client, req, e); } void Controller::writeRequestQueueFullExceptionErrorResponse(Client *client, Request *req, const boost::shared_ptr<RequestQueueFullException> &e) { TRACE_POINT(); const LString *value = req->secureHeaders.lookup( "!~PASSENGER_REQUEST_QUEUE_OVERFLOW_STATUS_CODE"); int requestQueueOverflowStatusCode = 503; if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); requestQueueOverflowStatusCode = stringToInt( StaticString(value->start->data, value->size)); } SKC_WARN(client, "Returning HTTP " << requestQueueOverflowStatusCode << " due to: " << e->what()); endRequestWithSimpleResponse(&client, &req, "<h2>This website is under heavy load (queue full)</h2>" "<p>We're sorry, too many people are accessing this website at the same " "time. We're working on this problem. Please try again later.</p>", requestQueueOverflowStatusCode); } void Controller::writeSpawnExceptionErrorResponse(Client *client, Request *req, const boost::shared_ptr<SpawnException> &e) { TRACE_POINT(); SKC_ERROR(client, "Cannot checkout session because a spawning error occurred. " << "The identifier of the error is " << e->get("error_id") << ". Please see earlier logs for " << "details about the error."); endRequestWithErrorResponse(&client, &req, e->getErrorPage(), e.get()); } void Controller::writeOtherExceptionErrorResponse(Client *client, Request *req, const ExceptionPtr &e) { TRACE_POINT(); string typeName; const oxt::tracable_exception &eptr = *e; #ifdef CXX_ABI_API_AVAILABLE int status; char *tmp = abi::__cxa_demangle(typeid(eptr).name(), 0, 0, &status); if (tmp != NULL) { typeName = tmp; free(tmp); } else { typeName = typeid(eptr).name(); } #else typeName = typeid(eptr).name(); #endif const unsigned int exceptionMessageLen = strlen(e->what()); string backtrace; boost::shared_ptr<tracable_exception> e3 = dynamic_pointer_cast<tracable_exception>(e); if (e3 != NULL) { backtrace = e3->backtrace(); } SKC_WARN(client, "Cannot checkout session due to " << typeName << ": " << e->what() << (!backtrace.empty() ? "\n" + backtrace : "")); if (friendlyErrorPagesEnabled(req)) { const unsigned int BUFFER_SIZE = 512 + typeName.size() + exceptionMessageLen + backtrace.size(); char *buf = (char *) psg_pnalloc(req->pool, BUFFER_SIZE); char *pos = buf; const char *end = buf + BUFFER_SIZE; pos = appendData(pos, end, "<h2>Internal server error</h2>"); pos = appendData(pos, end, "<p>Application could not be started.</p>"); pos = appendData(pos, end, "<p>Exception type: "); pos = appendData(pos, end, typeName); pos = appendData(pos, end, "<br>Error message: "); pos = appendData(pos, end, e->what(), exceptionMessageLen); if (!backtrace.empty()) { pos = appendData(pos, end, "<br>Backtrace:<br>"); pos = appendData(pos, end, backtrace); } pos = appendData(pos, end, "</p>"); endRequestWithSimpleResponse(&client, &req, StaticString(buf, pos - buf), 500); } else { endRequestWithSimpleResponse(&client, &req, "<h2>Internal server error</h2>" "Application could not be started. Please try again later.", 500); } } /** * `message` will be copied and doesn't need to outlive the request. */ void Controller::endRequestWithErrorResponse(Client **c, Request **r, const StaticString &message, const SpawnException *e) { TRACE_POINT(); Client *client = *c; Request *req = *r; ErrorRenderer renderer(*resourceLocator); string data; if (friendlyErrorPagesEnabled(req)) { try { data = renderer.renderWithDetails(message, req->options, e); } catch (const SystemException &e2) { SKC_ERROR(client, "Cannot render an error page: " << e2.what() << "\n" << e2.backtrace()); data = message; } } else { try { data = renderer.renderWithoutDetails(e); } catch (const SystemException &e2) { SKC_ERROR(client, "Cannot render an error page: " << e2.what() << "\n" << e2.backtrace()); data = "<h2>Internal server error</h2>"; } } endRequestWithSimpleResponse(c, r, psg_pstrdup(req->pool, data), 500); } bool Controller::friendlyErrorPagesEnabled(Request *req) { bool defaultValue; string defaultStr = agentsOptions->get("friendly_error_pages"); if (defaultStr == "auto") { defaultValue = (req->options.environment == "development"); } else { defaultValue = defaultStr == "true"; } return getBoolOption(req, "!~PASSENGER_FRIENDLY_ERROR_PAGES", defaultValue); } /***************/ /***************/ } // namespace Core } // namespace Passenger <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include "downsampled.h" #include <algorithm> namespace himg { Downsampled::Downsampled() : m_rows(0), m_columns(0) { } void Downsampled::SampleImage(const uint8_t *pixels, int stride, int width, int height) { // Divide by 8x8, rounding up. m_rows = (height + 7) >> 3; m_columns = (width + 7) >> 3; // Calculate average color for each 8x8 block. std::vector<uint8_t> average; average.reserve(m_rows * m_columns); for (int v = 0; v < m_rows; ++v) { int y_min = std::max(0, v * 8 - 3); int y_max = std::min(height - 1, v * 8 + 4); for (int u = 0; u < m_columns; ++u) { int x_min = std::max(0, u * 8 - 3); int x_max = std::min(width - 1, u * 8 + 4); uint16_t sum = 0; for (int y = y_min; y <= y_max; ++y) { for (int x = x_min; x <= x_max; ++x) { sum += pixels[(y * width + x) * stride]; } } int total_count = (x_max - x_min + 1) * (y_max - y_min + 1); average.push_back( static_cast<uint8_t>((sum + (total_count >> 1)) / total_count)); } } // Compensate blocks for lienear interpolation (phase shift 1/16 pixels up & // to the left). m_data.reserve(m_columns * m_rows); for (int v = 0; v < m_rows; ++v) { int row1 = std::max(0, v - 1); int row2 = v; for (int u = 0; u < m_columns; ++u) { int col1 = std::max(0, u - 1); int col2 = u; uint16_t x11 = static_cast<uint16_t>(average[row1 * m_columns + col1]); uint16_t x12 = static_cast<uint16_t>(average[row1 * m_columns + col2]); uint16_t x21 = static_cast<uint16_t>(average[row2 * m_columns + col1]); uint16_t x22 = static_cast<uint16_t>(average[row2 * m_columns + col2]); uint16_t a1 = (1 * x11 + 15 * x12 + 8) >> 4; uint16_t a2 = (1 * x21 + 15 * x22 + 8) >> 4; m_data.push_back(static_cast<uint8_t>((1 * a1 + 15 * a2 + 8) >> 4)); } } } void Downsampled::GetLowresBlock(int16_t *out, int u, int v) { // Pick out the four values in the corners of the block. int row1 = v; int row2 = std::min(m_rows - 1, v + 1); int col1 = u; int col2 = std::min(m_columns - 1, u + 1); int16_t x11 = static_cast<int16_t>(m_data[row1 * m_columns + col1]); int16_t x12 = static_cast<int16_t>(m_data[row1 * m_columns + col2]); int16_t x21 = static_cast<int16_t>(m_data[row2 * m_columns + col1]); int16_t x22 = static_cast<int16_t>(m_data[row2 * m_columns + col2]); // Liner interpolation to produce the left and right columns of the block. int16_t left[9], right[9]; left[0] = x11; left[8] = x21; left[4] = (left[0] + left[8]) >> 1; left[2] = (left[0] + left[4]) >> 1; left[6] = (left[4] + left[8]) >> 1; left[1] = (left[0] + left[2]) >> 1; left[3] = (left[2] + left[4]) >> 1; left[5] = (left[4] + left[6]) >> 1; left[7] = (left[6] + left[8]) >> 1; right[0] = x12; right[8] = x22; right[4] = (right[0] + right[8]) >> 1; right[2] = (right[0] + right[4]) >> 1; right[6] = (right[4] + right[8]) >> 1; right[1] = (right[0] + right[2]) >> 1; right[3] = (right[2] + right[4]) >> 1; right[5] = (right[4] + right[6]) >> 1; right[7] = (right[6] + right[8]) >> 1; // Liner interpolation to produce the eight rows of the block. for (int y = 0; y < 8; ++y) { int16_t a0 = left[y]; int16_t a8 = right[y]; int16_t a4 = (a0 + a8) >> 1; int16_t a2 = (a0 + a4) >> 1; int16_t a6 = (a4 + a8) >> 1; int16_t a1 = (a0 + a2) >> 1; int16_t a3 = (a2 + a4) >> 1; int16_t a5 = (a4 + a6) >> 1; int16_t a7 = (a6 + a8) >> 1; out[0] = a0; out[1] = a1; out[2] = a2; out[3] = a3; out[4] = a4; out[5] = a5; out[6] = a6; out[7] = a7; out += 8; } } void Downsampled::GetBlockData(uint8_t *out) const { for (int v = 0; v < m_rows; ++v) { for (int u = 0; u < m_columns; ++u) { uint8_t predicted; if (u > 0 && v > 0) { predicted = m_data[v * m_columns + u - 1] + m_data[(v - 1) * m_columns + u] - m_data[(v - 1) * m_columns + u - 1]; } else if (u > 0) { predicted = m_data[v * m_columns + u - 1]; } else if (v > 0) { predicted = m_data[(v - 1) * m_columns + u]; } else { predicted = 0; } *out++ = m_data[v * m_columns + u] - predicted; } } } void Downsampled::SetBlockData(const uint8_t *in, int rows, int columns) { m_rows = rows; m_columns = columns; m_data.resize(m_rows * m_columns); for (int v = 0; v < m_rows; ++v) { for (int u = 0; u < m_columns; ++u) { uint8_t predicted; if (u > 0 && v > 0) { predicted = m_data[v * m_columns + u - 1] + m_data[(v - 1) * m_columns + u] - m_data[(v - 1) * m_columns + u - 1]; } else if (u > 0) { predicted = m_data[v * m_columns + u - 1]; } else if (v > 0) { predicted = m_data[(v - 1) * m_columns + u]; } else { predicted = 0; } m_data[v * m_columns + u] = *in++ + predicted; } } } } // namespace himg <commit_msg>Proper rounding in the linear interpolation<commit_after>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include "downsampled.h" #include <algorithm> namespace himg { Downsampled::Downsampled() : m_rows(0), m_columns(0) { } void Downsampled::SampleImage(const uint8_t *pixels, int stride, int width, int height) { // Divide by 8x8, rounding up. m_rows = (height + 7) >> 3; m_columns = (width + 7) >> 3; // Calculate average color for each 8x8 block. std::vector<uint8_t> average; average.reserve(m_rows * m_columns); for (int v = 0; v < m_rows; ++v) { int y_min = std::max(0, v * 8 - 3); int y_max = std::min(height - 1, v * 8 + 4); for (int u = 0; u < m_columns; ++u) { int x_min = std::max(0, u * 8 - 3); int x_max = std::min(width - 1, u * 8 + 4); uint16_t sum = 0; for (int y = y_min; y <= y_max; ++y) { for (int x = x_min; x <= x_max; ++x) { sum += pixels[(y * width + x) * stride]; } } int total_count = (x_max - x_min + 1) * (y_max - y_min + 1); average.push_back( static_cast<uint8_t>((sum + (total_count >> 1)) / total_count)); } } // Compensate blocks for lienear interpolation (phase shift 1/16 pixels up & // to the left). m_data.reserve(m_columns * m_rows); for (int v = 0; v < m_rows; ++v) { int row1 = std::max(0, v - 1); int row2 = v; for (int u = 0; u < m_columns; ++u) { int col1 = std::max(0, u - 1); int col2 = u; uint16_t x11 = static_cast<uint16_t>(average[row1 * m_columns + col1]); uint16_t x12 = static_cast<uint16_t>(average[row1 * m_columns + col2]); uint16_t x21 = static_cast<uint16_t>(average[row2 * m_columns + col1]); uint16_t x22 = static_cast<uint16_t>(average[row2 * m_columns + col2]); uint16_t a1 = (1 * x11 + 15 * x12 + 8) >> 4; uint16_t a2 = (1 * x21 + 15 * x22 + 8) >> 4; m_data.push_back(static_cast<uint8_t>((1 * a1 + 15 * a2 + 8) >> 4)); } } } void Downsampled::GetLowresBlock(int16_t *out, int u, int v) { // Pick out the four values in the corners of the block. int row1 = v; int row2 = std::min(m_rows - 1, v + 1); int col1 = u; int col2 = std::min(m_columns - 1, u + 1); int16_t x11 = static_cast<int16_t>(m_data[row1 * m_columns + col1]); int16_t x12 = static_cast<int16_t>(m_data[row1 * m_columns + col2]); int16_t x21 = static_cast<int16_t>(m_data[row2 * m_columns + col1]); int16_t x22 = static_cast<int16_t>(m_data[row2 * m_columns + col2]); // Liner interpolation to produce the left and right columns of the block. int16_t left[9], right[9]; left[0] = x11; left[8] = x21; left[4] = (left[0] + left[8] + 1) >> 1; left[2] = (left[0] + left[4] + 1) >> 1; left[6] = (left[4] + left[8] + 1) >> 1; left[1] = (left[0] + left[2] + 1) >> 1; left[3] = (left[2] + left[4] + 1) >> 1; left[5] = (left[4] + left[6] + 1) >> 1; left[7] = (left[6] + left[8] + 1) >> 1; right[0] = x12; right[8] = x22; right[4] = (right[0] + right[8] + 1) >> 1; right[2] = (right[0] + right[4] + 1) >> 1; right[6] = (right[4] + right[8] + 1) >> 1; right[1] = (right[0] + right[2] + 1) >> 1; right[3] = (right[2] + right[4] + 1) >> 1; right[5] = (right[4] + right[6] + 1) >> 1; right[7] = (right[6] + right[8] + 1) >> 1; // Liner interpolation to produce the eight rows of the block. for (int y = 0; y < 8; ++y) { int16_t a0 = left[y]; int16_t a8 = right[y]; int16_t a4 = (a0 + a8 + 1) >> 1; int16_t a2 = (a0 + a4 + 1) >> 1; int16_t a6 = (a4 + a8 + 1) >> 1; int16_t a1 = (a0 + a2 + 1) >> 1; int16_t a3 = (a2 + a4 + 1) >> 1; int16_t a5 = (a4 + a6 + 1) >> 1; int16_t a7 = (a6 + a8 + 1) >> 1; out[0] = a0; out[1] = a1; out[2] = a2; out[3] = a3; out[4] = a4; out[5] = a5; out[6] = a6; out[7] = a7; out += 8; } } void Downsampled::GetBlockData(uint8_t *out) const { for (int v = 0; v < m_rows; ++v) { for (int u = 0; u < m_columns; ++u) { uint8_t predicted; if (u > 0 && v > 0) { predicted = m_data[v * m_columns + u - 1] + m_data[(v - 1) * m_columns + u] - m_data[(v - 1) * m_columns + u - 1]; } else if (u > 0) { predicted = m_data[v * m_columns + u - 1]; } else if (v > 0) { predicted = m_data[(v - 1) * m_columns + u]; } else { predicted = 0; } *out++ = m_data[v * m_columns + u] - predicted; } } } void Downsampled::SetBlockData(const uint8_t *in, int rows, int columns) { m_rows = rows; m_columns = columns; m_data.resize(m_rows * m_columns); for (int v = 0; v < m_rows; ++v) { for (int u = 0; u < m_columns; ++u) { uint8_t predicted; if (u > 0 && v > 0) { predicted = m_data[v * m_columns + u - 1] + m_data[(v - 1) * m_columns + u] - m_data[(v - 1) * m_columns + u - 1]; } else if (u > 0) { predicted = m_data[v * m_columns + u - 1]; } else if (v > 0) { predicted = m_data[(v - 1) * m_columns + u]; } else { predicted = 0; } m_data[v * m_columns + u] = *in++ + predicted; } } } } // namespace himg <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <wordexp.h> #include <ros/ros.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <spencer_tracking_msgs/TrackedPersons2d.h> extern "C" int mkpath(const char *path); void subtractbg(cv::Mat &rgb, const cv::Mat &d, float thresh=1.0f, float bgcoeff=0.5f); using namespace spencer_tracking_msgs; // These are set by params to the node. std::string g_dir; double g_hfactor; double g_wfactor; bool g_subbg; double g_bgcoeff; // For filename and stats. size_t g_counter = 0; template<typename T> std::string to_s(const T& v) { std::ostringstream oss; oss << v; return oss.str(); } void dump_32FC1(std::string fname, cv::Mat img) { if(img.type() != CV_32FC1) { ROS_ERROR("Image not of 32FC1 type, but %d", img.type()); return; } std::ofstream of(fname); if(!of) { ROS_ERROR("Error writing depth image %s", (fname + "_d.csv").c_str()); return; } for(size_t iy = 0 ; iy < img.rows ; ++iy) { float *py = img.ptr<float>(iy); for(size_t ix = 0 ; ix < img.cols ; ++ix, ++py) { of << *py; if(ix + 1 < img.cols) of << " "; } of << std::endl; } } void cb(const TrackedPersons2d::ConstPtr& t2d, const sensor_msgs::ImageConstPtr& rgb, const sensor_msgs::ImageConstPtr& d) { size_t ndet = t2d->boxes.size(); if(ndet == 0) return; cv_bridge::CvImageConstPtr cv_rgb; cv_bridge::CvImageConstPtr cv_d; try { // TODO: Careful, the above is RGB but opencv "thinks" in BGR! //cv_rgb = cv_bridge::toCvShare(rgb); cv_rgb = cv_bridge::toCvCopy(rgb, sensor_msgs::image_encodings::BGR8); cv_d = cv_bridge::toCvShare(d); } catch(const cv_bridge::Exception& e) { ROS_ERROR("Couldn't convert image: %s", e.what()); return; } for(size_t idet = 0 ; idet < ndet ; ++idet) { const TrackedPerson2d& p2d = t2d->boxes[idet]; // Compute this detection's cut-out boxes. uint32_t h = g_hfactor > 0 ? std::min(uint32_t(g_hfactor * p2d.w), p2d.h) : p2d.h; uint32_t w = uint32_t(g_wfactor * p2d.w); int32_t x = p2d.x + int32_t(.5*(1. - g_wfactor)*p2d.w); cv::Rect bbox(x, p2d.y, w, h); cv::Rect bbox_rgb = bbox & cv::Rect(0, 0, cv_rgb->image.cols, cv_rgb->image.rows); cv::Rect bbox_d = bbox & cv::Rect(0, 0, cv_d->image.cols, cv_d->image.rows); // Cut-out and optionally subtract background. cv::Mat rgbimg(cv_rgb->image, bbox_rgb); cv::Mat dimg(cv_d->image, bbox_d); if(g_subbg) subtractbg(rgbimg, dimg, 1.0, g_bgcoeff); // Save. // TODO: setw std::string fname = g_dir + "/" + to_s(p2d.track_id) + "_" + to_s(rgb->header.seq); if(!cv::imwrite(fname + "_rgb.png", rgbimg)) { ROS_ERROR("Error writing image %s", (fname + "_rgb.png").c_str()); } dump_32FC1(fname + "_d.csv", dimg); std::cout << "\rDumping: " << rgb->header.seq << std::flush; g_counter++; } } int main(int argc, char* argv[]) { ros::init(argc, argv, "dump_tracks"); ros::NodeHandle nh; ros::NodeHandle nh_("~"); nh_.param("dir", g_dir, std::string(".")); nh_.param("hfactor", g_hfactor, -1.0); nh_.param("wfactor", g_wfactor, 1.0); nh_.param("bgcoeff", g_bgcoeff, 0.5); g_wfactor = g_wfactor <= 0 ? 1.0 : g_wfactor; nh_.param("subbg", g_subbg, false); // equivalend to Python's expanduser(dir) wordexp_t exp_result; if(0 !=wordexp(g_dir.c_str(), &exp_result, WRDE_NOCMD | WRDE_SHOWERR)) return 1; g_dir = exp_result.we_wordv[0]; wordfree(&exp_result); if(mkpath(g_dir.c_str()) != 0) { perror("Couldn't create output directory"); return 2; } // TODO: warn if non-emtpy? ROS_INFO("Dumping %s%s-bodies into %s", g_subbg ? "bg-subtracted, " : " ", g_hfactor > 0 ? to_s(g_hfactor).c_str() : "full", g_dir.c_str()); std::string topic_t2d, topic_rgb, topic_d; nh_.param("track2d", topic_t2d, std::string("/upper_body_detector/detections")); nh_.param("rgb", topic_rgb, std::string("/head_xtion/rgb/image_rect_color")); nh_.param("d", topic_d, std::string("/head_xtion/depth/image_rect_meters")); message_filters::Subscriber<TrackedPersons2d> sub_t2d(nh_, topic_t2d.c_str(), 1); image_transport::ImageTransport it(nh_); image_transport::SubscriberFilter sub_rgb(it, topic_rgb.c_str(), 1); image_transport::SubscriberFilter sub_d(it, topic_d.c_str(), 1); typedef message_filters::sync_policies::ApproximateTime<TrackedPersons2d, sensor_msgs::Image, sensor_msgs::Image> SyncType; const SyncType sync_policy(20); message_filters::Synchronizer<SyncType> sync(sync_policy, sub_t2d, sub_rgb, sub_d); sync.registerCallback(boost::bind(&cb, _1, _2, _3)); ros::spin(); // TODO: ROS_INFO isn't being output after the spin is done? //ROS_INFO("Dumped a total of %d track frames.", g_counter); std::cout << "Dumped a total of " << g_counter << " track frames." << std::endl; return 0; } <commit_msg>Nicer dumper output.<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <wordexp.h> #include <ros/ros.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <spencer_tracking_msgs/TrackedPersons2d.h> extern "C" int mkpath(const char *path); void subtractbg(cv::Mat &rgb, const cv::Mat &d, float thresh=1.0f, float bgcoeff=0.5f); using namespace spencer_tracking_msgs; // These are set by params to the node. std::string g_dir; double g_hfactor; double g_wfactor; bool g_subbg; double g_bgcoeff; // For filename and stats. size_t g_counter = 0; template<typename T> std::string to_s(const T& v) { std::ostringstream oss; oss << v; return oss.str(); } void dump_32FC1(std::string fname, cv::Mat img) { if(img.type() != CV_32FC1) { ROS_ERROR("Image not of 32FC1 type, but %d", img.type()); return; } std::ofstream of(fname); if(!of) { ROS_ERROR("Error writing depth image %s", (fname + "_d.csv").c_str()); return; } for(size_t iy = 0 ; iy < img.rows ; ++iy) { float *py = img.ptr<float>(iy); for(size_t ix = 0 ; ix < img.cols ; ++ix, ++py) { of << *py; if(ix + 1 < img.cols) of << " "; } of << std::endl; } } void cb(const TrackedPersons2d::ConstPtr& t2d, const sensor_msgs::ImageConstPtr& rgb, const sensor_msgs::ImageConstPtr& d) { size_t ndet = t2d->boxes.size(); if(ndet == 0) return; cv_bridge::CvImageConstPtr cv_rgb; cv_bridge::CvImageConstPtr cv_d; try { // TODO: Careful, the above is RGB but opencv "thinks" in BGR! //cv_rgb = cv_bridge::toCvShare(rgb); cv_rgb = cv_bridge::toCvCopy(rgb, sensor_msgs::image_encodings::BGR8); cv_d = cv_bridge::toCvShare(d); } catch(const cv_bridge::Exception& e) { ROS_ERROR("Couldn't convert image: %s", e.what()); return; } for(size_t idet = 0 ; idet < ndet ; ++idet) { const TrackedPerson2d& p2d = t2d->boxes[idet]; // Compute this detection's cut-out boxes. uint32_t h = g_hfactor > 0 ? std::min(uint32_t(g_hfactor * p2d.w), p2d.h) : p2d.h; uint32_t w = uint32_t(g_wfactor * p2d.w); int32_t x = p2d.x + int32_t(.5*(1. - g_wfactor)*p2d.w); cv::Rect bbox(x, p2d.y, w, h); cv::Rect bbox_rgb = bbox & cv::Rect(0, 0, cv_rgb->image.cols, cv_rgb->image.rows); cv::Rect bbox_d = bbox & cv::Rect(0, 0, cv_d->image.cols, cv_d->image.rows); // Cut-out and optionally subtract background. cv::Mat rgbimg(cv_rgb->image, bbox_rgb); cv::Mat dimg(cv_d->image, bbox_d); if(g_subbg) subtractbg(rgbimg, dimg, 1.0, g_bgcoeff); // Save. // TODO: setw std::string fname = g_dir + "/" + to_s(p2d.track_id) + "_" + to_s(rgb->header.seq); if(!cv::imwrite(fname + "_rgb.png", rgbimg)) { ROS_ERROR("Error writing image %s", (fname + "_rgb.png").c_str()); } dump_32FC1(fname + "_d.csv", dimg); std::cout << "\rDump #" << g_counter << ": track " << p2d.track_id << "@seq" << rgb->header.seq << std::flush; g_counter++; } } int main(int argc, char* argv[]) { ros::init(argc, argv, "dump_tracks"); ros::NodeHandle nh; ros::NodeHandle nh_("~"); nh_.param("dir", g_dir, std::string(".")); nh_.param("hfactor", g_hfactor, -1.0); nh_.param("wfactor", g_wfactor, 1.0); nh_.param("bgcoeff", g_bgcoeff, 0.5); g_wfactor = g_wfactor <= 0 ? 1.0 : g_wfactor; nh_.param("subbg", g_subbg, false); // equivalend to Python's expanduser(dir) wordexp_t exp_result; if(0 !=wordexp(g_dir.c_str(), &exp_result, WRDE_NOCMD | WRDE_SHOWERR)) return 1; g_dir = exp_result.we_wordv[0]; wordfree(&exp_result); if(mkpath(g_dir.c_str()) != 0) { perror("Couldn't create output directory"); return 2; } // TODO: warn if non-emtpy? ROS_INFO("Dumping %s%s-bodies into %s", g_subbg ? "bg-subtracted, " : " ", g_hfactor > 0 ? to_s(g_hfactor).c_str() : "full", g_dir.c_str()); std::string topic_t2d, topic_rgb, topic_d; nh_.param("track2d", topic_t2d, std::string("/upper_body_detector/detections")); nh_.param("rgb", topic_rgb, std::string("/head_xtion/rgb/image_rect_color")); nh_.param("d", topic_d, std::string("/head_xtion/depth/image_rect_meters")); message_filters::Subscriber<TrackedPersons2d> sub_t2d(nh_, topic_t2d.c_str(), 1); image_transport::ImageTransport it(nh_); image_transport::SubscriberFilter sub_rgb(it, topic_rgb.c_str(), 1); image_transport::SubscriberFilter sub_d(it, topic_d.c_str(), 1); typedef message_filters::sync_policies::ApproximateTime<TrackedPersons2d, sensor_msgs::Image, sensor_msgs::Image> SyncType; const SyncType sync_policy(20); message_filters::Synchronizer<SyncType> sync(sync_policy, sub_t2d, sub_rgb, sub_d); sync.registerCallback(boost::bind(&cb, _1, _2, _3)); ros::spin(); // TODO: ROS_INFO isn't being output after the spin is done? //ROS_INFO("Dumped a total of %d track frames.", g_counter); std::cout << "Dumped a total of " << g_counter << " track frames." << std::endl; return 0; } <|endoftext|>
<commit_before>#include "system/state.hh" #include <iostream> #include <fstream> #include "common/array.hh" using namespace divine; namespace divine { class succ_container_t: public divine::array_t<state_t> { public: //!A constructor (only calls a constructor of array_t<state_t> with //! parameters 4096 (preallocation) and 16 (allocation step). succ_container_t(): array_t<state_t>(4096, 16) {} //!A destructor. ~succ_container_t() {} }; }; // added interface functions size_t (*lib_get_state_variable_count)(); const char* (*lib_get_state_variable_name)(int var); size_t (*lib_get_state_variable_type_count)(); const char* (*lib_get_state_variable_type_name)(int type); const int (*lib_get_state_variable_type)(int var); size_t (*lib_get_state_variable_type_value_count)(int type); const char* (*lib_get_state_variable_type_value)(int type, int value); void (*lib_project_state_to_int_array)(state_t state, int* proj); void (*lib_project_int_array_to_state)(int* proj, state_t state); int* (*lib_get_transition_proj)(int trans); int (*lib_get_transition_succ)(size_int_t transition, state_t state, succ_container_t & succ_container); int (*lib_get_transition_count)(); divine::state_t (*lib_new_state)(); // original interface functions int (*lib_get_succ)(state_t, succ_container_t &); bool (*lib_is_accepting)(state_t); divine::state_t (*lib_get_initial_state)(); void (*lib_print_state)(state_t, std::ostream & ); bool (*lib_is_in_accepting_component)(state_t state); extern "C" { #include "runtime.h" #include "dve-greybox.h" #include "dm/dm.h" #include "chunk_support.h" #include <dlfcn.h> static void dve_popt(poptContext con, enum poptCallbackReason reason, const struct poptOption * opt, const char * arg, void * data){ (void)con;(void)opt;(void)arg;(void)data; switch(reason){ case POPT_CALLBACK_REASON_PRE: break; case POPT_CALLBACK_REASON_POST: // TODO: add uncompiled extension, use divine to create dveC //GBregisterLoader("dve", DVEloadGreyboxModel); GBregisterLoader("dveC",DVEloadGreyboxModel); Warning(info,"Precompiled divine module initialized"); return; case POPT_CALLBACK_REASON_OPTION: break; } Fatal(1,error,"unexpected call to dve_popt"); } struct poptOption dve_options[]= { { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)&dve_popt, 0 , NULL , NULL }, POPT_TABLEEND }; typedef struct grey_box_context { int todo; } *gb_context_t; static void divine_get_initial_state(int* state) { divine::state_t s = lib_get_initial_state(); lib_project_state_to_int_array(s, state); } static lts_type_t ltstype; static matrix_t dm_info; static matrix_t sl_info; static divine::succ_container_t cb_cont; static int succ_callback(TransitionCB cb, void* context) { int result = cb_cont.size(); for(size_t i=0; i < (size_t)result;++i) { int dst[lib_get_state_variable_count()]; lib_project_state_to_int_array(cb_cont[i], dst); cb(context, NULL, dst); } cb_cont.clear(); return result; } static int divine_get_transitions_all(model_t self, int*src, TransitionCB cb, void*context) { (void)self; divine::state_t s = lib_new_state(); lib_project_int_array_to_state(src, s); lib_get_succ(s, cb_cont); return succ_callback(cb, context); } static int divine_get_transitions_long(model_t self, int group, int*src, TransitionCB cb, void*context) { (void)self; divine::state_t s = lib_new_state(); lib_project_int_array_to_state(src, s); lib_get_transition_succ(group, s, cb_cont); return succ_callback(cb, context); } void DVEloadGreyboxModel(model_t model, const char *filename){ gb_context_t ctx=(gb_context_t)RTmalloc(sizeof(struct grey_box_context)); GBsetContext(model,ctx); // Open dveC file // TODO: call dlclose() somewhere? void *dlHandle = NULL; char* abs_filename = realpath(filename, NULL); if (abs_filename) { dlHandle = dlopen(abs_filename, RTLD_LAZY); free(abs_filename); if (dlHandle == NULL) { FatalCall (1, error, "%s, Library \"%s\" is not reachable", dlerror(), filename); return; } } else { FatalCall (1, error, "%s, Library \"%s\" is not found", dlerror(), filename); } // get functions lib_get_succ = (int(*)(divine::state_t, divine::succ_container_t &)) dlsym( dlHandle, "lib_get_succ"); lib_is_accepting = (bool(*)(divine::state_t)) dlsym( dlHandle, "lib_is_accepting"); lib_is_in_accepting_component = (bool(*)(divine::state_t)) dlsym( dlHandle, "lib_is_in_accepting_component"); lib_get_initial_state = (divine::state_t(*)()) dlsym( dlHandle, "lib_get_initial_state"); lib_print_state = (void(*)(divine::state_t, std::ostream &)) dlsym( dlHandle, "lib_print_state"); if (lib_get_succ == NULL || lib_is_accepting == NULL || lib_is_in_accepting_component == NULL || lib_get_initial_state == NULL || lib_print_state == NULL) { FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename); } // added interface functions lib_get_state_variable_count = (size_t (*)()) dlsym( dlHandle, "lib_get_state_variable_count"); lib_get_state_variable_name = (const char* (*)(int var)) dlsym( dlHandle, "lib_get_state_variable_name" ); lib_get_state_variable_type_count = (size_t (*)()) dlsym( dlHandle, "lib_get_state_variable_type_count"); lib_get_state_variable_type_name = (const char* (*)(int type)) dlsym( dlHandle, "lib_get_state_variable_type_name"); lib_get_state_variable_type = (const int (*)(int var)) dlsym( dlHandle, "lib_get_state_variable_type"); lib_get_state_variable_type_value_count = (size_t (*)(int)) dlsym( dlHandle, "lib_get_state_variable_type_value_count"); lib_get_state_variable_type_value = (const char* (*)(int type, int value)) dlsym( dlHandle, "lib_get_state_variable_type_value"); lib_project_state_to_int_array = (void (*)(state_t state, int* proj)) dlsym( dlHandle, "lib_project_state_to_int_array"); lib_project_int_array_to_state = (void (*)(int* proj, state_t state)) dlsym( dlHandle, "lib_project_int_array_to_state"); lib_get_transition_proj = (int* (*)(int trans)) dlsym( dlHandle, "lib_get_transition_proj"); lib_get_transition_succ = (int (*)(size_int_t transition, state_t state, succ_container_t & succ_container)) dlsym( dlHandle, "lib_get_transition_succ"); lib_get_transition_count = (int (*)()) dlsym( dlHandle, "lib_get_transition_count"); lib_new_state = (divine::state_t (*)()) dlsym( dlHandle, "lib_new_state"); // test dveC file if (lib_get_state_variable_count == NULL || lib_get_state_variable_name == NULL || lib_get_state_variable_type_count == NULL || lib_get_state_variable_type_name == NULL || lib_get_state_variable_type == NULL || lib_get_state_variable_type_value_count == NULL || lib_get_state_variable_type_value == NULL || lib_project_state_to_int_array == NULL || lib_project_int_array_to_state == NULL || lib_get_transition_proj == NULL || lib_get_transition_succ == NULL || lib_get_transition_count == NULL || lib_new_state == NULL) { FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename); } // get ltstypes int state_length = lib_get_state_variable_count(); ltstype=lts_type_create(); // adding types int ntypes = lib_get_state_variable_type_count(); for(int i=0; i < ntypes; i++) { const char* type_name = lib_get_state_variable_type_name(i); if (lts_type_add_type(ltstype,type_name,NULL) != i) { Fatal(1,error,"wrong type number"); } } lts_type_set_state_length(ltstype, state_length); // set state name & type for(int i=0; i < state_length; ++i) { const char* name = lib_get_state_variable_name(i); const int type = lib_get_state_variable_type(i); lts_type_set_state_name(ltstype,i,name); lts_type_set_state_typeno(ltstype,i,type); } GBsetLTStype(model, ltstype); // setting values for types // chunk_str doesn't work for(int i=0; i < ntypes; i++) { int type_value_count = lib_get_state_variable_type_value_count(i); if (type_value_count > 0) { for(int j=0; j < type_value_count; ++j) { const char* type_value = lib_get_state_variable_type_value(i, j); GBchunkPut(model, i, (chunk){strlen(type_value),(char*)type_value}); } } } lts_type_validate(ltstype); int ngroups = lib_get_transition_count(); dm_create(&dm_info, ngroups, state_length); for(int i=0; i < dm_nrows(&dm_info); i++) { int* proj = lib_get_transition_proj(i); for(int j=0; j<state_length; j++) { if (proj[j]) dm_set(&dm_info, i, j); } } GBsetDMInfo(model, &dm_info); // there are no state labels dm_create(&sl_info, 0, state_length); GBsetStateLabelInfo(model, &sl_info); // get initial state int state[state_length]; divine_get_initial_state(state); GBsetInitialState(model,state); GBsetNextStateAll (model, divine_get_transitions_all); GBsetNextStateLong (model, divine_get_transitions_long); } } // extern "C" <commit_msg>Added dummy label to make --cache work<commit_after>#include "system/state.hh" #include <iostream> #include <fstream> #include "common/array.hh" using namespace divine; namespace divine { class succ_container_t: public divine::array_t<state_t> { public: //!A constructor (only calls a constructor of array_t<state_t> with //! parameters 4096 (preallocation) and 16 (allocation step). succ_container_t(): array_t<state_t>(4096, 16) {} //!A destructor. ~succ_container_t() {} }; }; // added interface functions size_t (*lib_get_state_variable_count)(); const char* (*lib_get_state_variable_name)(int var); size_t (*lib_get_state_variable_type_count)(); const char* (*lib_get_state_variable_type_name)(int type); const int (*lib_get_state_variable_type)(int var); size_t (*lib_get_state_variable_type_value_count)(int type); const char* (*lib_get_state_variable_type_value)(int type, int value); void (*lib_project_state_to_int_array)(state_t state, int* proj); void (*lib_project_int_array_to_state)(int* proj, state_t state); int* (*lib_get_transition_proj)(int trans); int (*lib_get_transition_succ)(size_int_t transition, state_t state, succ_container_t & succ_container); int (*lib_get_transition_count)(); divine::state_t (*lib_new_state)(); // original interface functions int (*lib_get_succ)(state_t, succ_container_t &); bool (*lib_is_accepting)(state_t); divine::state_t (*lib_get_initial_state)(); void (*lib_print_state)(state_t, std::ostream & ); bool (*lib_is_in_accepting_component)(state_t state); extern "C" { #include "runtime.h" #include "dve-greybox.h" #include "dm/dm.h" #include "chunk_support.h" #include <dlfcn.h> static void dve_popt(poptContext con, enum poptCallbackReason reason, const struct poptOption * opt, const char * arg, void * data){ (void)con;(void)opt;(void)arg;(void)data; switch(reason){ case POPT_CALLBACK_REASON_PRE: break; case POPT_CALLBACK_REASON_POST: // TODO: add uncompiled extension, use divine to create dveC //GBregisterLoader("dve", DVEloadGreyboxModel); GBregisterLoader("dveC",DVEloadGreyboxModel); Warning(info,"Precompiled divine module initialized"); return; case POPT_CALLBACK_REASON_OPTION: break; } Fatal(1,error,"unexpected call to dve_popt"); } struct poptOption dve_options[]= { { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)&dve_popt, 0 , NULL , NULL }, POPT_TABLEEND }; typedef struct grey_box_context { int todo; } *gb_context_t; static void divine_get_initial_state(int* state) { divine::state_t s = lib_get_initial_state(); lib_project_state_to_int_array(s, state); } static lts_type_t ltstype; static matrix_t dm_info; static matrix_t sl_info; static divine::succ_container_t cb_cont; static int succ_callback(TransitionCB cb, void* context) { int dummy = 42; // dummy to work with --cache int result = cb_cont.size(); for(size_t i=0; i < (size_t)result;++i) { int dst[lib_get_state_variable_count()]; lib_project_state_to_int_array(cb_cont[i], dst); cb(context, &dummy, dst); } cb_cont.clear(); return result; } static int divine_get_transitions_all(model_t self, int*src, TransitionCB cb, void*context) { (void)self; divine::state_t s = lib_new_state(); lib_project_int_array_to_state(src, s); lib_get_succ(s, cb_cont); return succ_callback(cb, context); } static int divine_get_transitions_long(model_t self, int group, int*src, TransitionCB cb, void*context) { (void)self; divine::state_t s = lib_new_state(); lib_project_int_array_to_state(src, s); lib_get_transition_succ(group, s, cb_cont); return succ_callback(cb, context); } void DVEloadGreyboxModel(model_t model, const char *filename){ gb_context_t ctx=(gb_context_t)RTmalloc(sizeof(struct grey_box_context)); GBsetContext(model,ctx); // Open dveC file // TODO: call dlclose() somewhere? void *dlHandle = NULL; char* abs_filename = realpath(filename, NULL); if (abs_filename) { dlHandle = dlopen(abs_filename, RTLD_LAZY); free(abs_filename); if (dlHandle == NULL) { FatalCall (1, error, "%s, Library \"%s\" is not reachable", dlerror(), filename); return; } } else { FatalCall (1, error, "%s, Library \"%s\" is not found", dlerror(), filename); } // get functions lib_get_succ = (int(*)(divine::state_t, divine::succ_container_t &)) dlsym( dlHandle, "lib_get_succ"); lib_is_accepting = (bool(*)(divine::state_t)) dlsym( dlHandle, "lib_is_accepting"); lib_is_in_accepting_component = (bool(*)(divine::state_t)) dlsym( dlHandle, "lib_is_in_accepting_component"); lib_get_initial_state = (divine::state_t(*)()) dlsym( dlHandle, "lib_get_initial_state"); lib_print_state = (void(*)(divine::state_t, std::ostream &)) dlsym( dlHandle, "lib_print_state"); if (lib_get_succ == NULL || lib_is_accepting == NULL || lib_is_in_accepting_component == NULL || lib_get_initial_state == NULL || lib_print_state == NULL) { FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename); } // added interface functions lib_get_state_variable_count = (size_t (*)()) dlsym( dlHandle, "lib_get_state_variable_count"); lib_get_state_variable_name = (const char* (*)(int var)) dlsym( dlHandle, "lib_get_state_variable_name" ); lib_get_state_variable_type_count = (size_t (*)()) dlsym( dlHandle, "lib_get_state_variable_type_count"); lib_get_state_variable_type_name = (const char* (*)(int type)) dlsym( dlHandle, "lib_get_state_variable_type_name"); lib_get_state_variable_type = (const int (*)(int var)) dlsym( dlHandle, "lib_get_state_variable_type"); lib_get_state_variable_type_value_count = (size_t (*)(int)) dlsym( dlHandle, "lib_get_state_variable_type_value_count"); lib_get_state_variable_type_value = (const char* (*)(int type, int value)) dlsym( dlHandle, "lib_get_state_variable_type_value"); lib_project_state_to_int_array = (void (*)(state_t state, int* proj)) dlsym( dlHandle, "lib_project_state_to_int_array"); lib_project_int_array_to_state = (void (*)(int* proj, state_t state)) dlsym( dlHandle, "lib_project_int_array_to_state"); lib_get_transition_proj = (int* (*)(int trans)) dlsym( dlHandle, "lib_get_transition_proj"); lib_get_transition_succ = (int (*)(size_int_t transition, state_t state, succ_container_t & succ_container)) dlsym( dlHandle, "lib_get_transition_succ"); lib_get_transition_count = (int (*)()) dlsym( dlHandle, "lib_get_transition_count"); lib_new_state = (divine::state_t (*)()) dlsym( dlHandle, "lib_new_state"); // test dveC file if (lib_get_state_variable_count == NULL || lib_get_state_variable_name == NULL || lib_get_state_variable_type_count == NULL || lib_get_state_variable_type_name == NULL || lib_get_state_variable_type == NULL || lib_get_state_variable_type_value_count == NULL || lib_get_state_variable_type_value == NULL || lib_project_state_to_int_array == NULL || lib_project_int_array_to_state == NULL || lib_get_transition_proj == NULL || lib_get_transition_succ == NULL || lib_get_transition_count == NULL || lib_new_state == NULL) { FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename); } // get ltstypes int state_length = lib_get_state_variable_count(); ltstype=lts_type_create(); // adding types int ntypes = lib_get_state_variable_type_count(); for(int i=0; i < ntypes; i++) { const char* type_name = lib_get_state_variable_type_name(i); if (lts_type_add_type(ltstype,type_name,NULL) != i) { Fatal(1,error,"wrong type number"); } } lts_type_set_state_length(ltstype, state_length); // set state name & type for(int i=0; i < state_length; ++i) { const char* name = lib_get_state_variable_name(i); const int type = lib_get_state_variable_type(i); lts_type_set_state_name(ltstype,i,name); lts_type_set_state_typeno(ltstype,i,type); } GBsetLTStype(model, ltstype); // setting values for types // chunk_str doesn't work for(int i=0; i < ntypes; i++) { int type_value_count = lib_get_state_variable_type_value_count(i); if (type_value_count > 0) { for(int j=0; j < type_value_count; ++j) { const char* type_value = lib_get_state_variable_type_value(i, j); GBchunkPut(model, i, (chunk){strlen(type_value),(char*)type_value}); } } } lts_type_validate(ltstype); int ngroups = lib_get_transition_count(); dm_create(&dm_info, ngroups, state_length); for(int i=0; i < dm_nrows(&dm_info); i++) { int* proj = lib_get_transition_proj(i); for(int j=0; j<state_length; j++) { if (proj[j]) dm_set(&dm_info, i, j); } } GBsetDMInfo(model, &dm_info); // there are no state labels dm_create(&sl_info, 0, state_length); GBsetStateLabelInfo(model, &sl_info); // get initial state int state[state_length]; divine_get_initial_state(state); GBsetInitialState(model,state); GBsetNextStateAll (model, divine_get_transitions_all); GBsetNextStateLong (model, divine_get_transitions_long); } } // extern "C" <|endoftext|>
<commit_before>#ifndef PI #define PI 3.14159265359f #endif #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #include "world.hpp" #include "shader.hpp" extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this. namespace model { World::World() { // constructor. } World::~World() { // destructor. std::cout << "This world will be destroyed.\n"; // destroy all shaders of this world. std::cout << "All shaders of this world will be destroyed.\n"; model::delete_children<model::Shader*>(this->shader_pointer_vector); } void World::render() { this->compute_matrices_from_inputs(); // render World by calling `render()` function of each Shader. model::render_children<model::Shader*>(this->shader_pointer_vector); } void World::set_shader_pointer(GLuint childID, void* parent_pointer) { set_child_pointer(childID, parent_pointer, this->shader_pointer_vector, this->free_shaderID_queue); } void World::set_world_species_pointer(void* world_species_pointer) { this->world_species_pointer = world_species_pointer; } void World::compute_matrices_from_inputs() { // glfwGetTime is called only once, the first time this function is called static double lastTime = glfwGetTime(); // Compute time difference between current and last frame double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); // Get mouse position double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2); if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001)) { hasMouseEverMoved = true; // Compute new orientation horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos); horizontalAngle = remainder(horizontalAngle, (2.0f * PI)); if (is_invert_mouse_in_use) { // invert mouse. verticalAngle -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } else { // don't invert mouse. verticalAngle += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } verticalAngle = remainder(verticalAngle, (2.0f * PI)); } // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - PI/2.0f), 0, cos(horizontalAngle - PI/2.0f) ); // Up vector glm::vec3 up = glm::cross(right, direction); GLfloat temp_speed; // Turbo. if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) && (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = twin_turbo_factor * speed; } else if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = turbo_factor * speed; } else { temp_speed = speed; } // Move forward if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction * deltaTime * temp_speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction * deltaTime * temp_speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right * deltaTime * temp_speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right * deltaTime * temp_speed; } // Move up. if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { position.y += deltaTime * temp_speed; } // Move down. if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { position.y -= deltaTime * temp_speed; } // Move west. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { position.x -= deltaTime * temp_speed; } // Move east. if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { position.x += deltaTime * temp_speed; } // Move north. if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) { position.z -= deltaTime * temp_speed; } // Move south. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { position.z += deltaTime * temp_speed; } // Flight mode on. if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) { fallSpeed = 0.0f; inFlightmode = true; } // Run mode on. if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) { fallSpeed = 0.0f; inFlightmode = false; } if (!inFlightmode) { fallSpeed += gravity; position.y -= fallSpeed; } GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS) { if (is_key_I_released) { if (is_invert_mouse_in_use) { is_invert_mouse_in_use = false; } else { is_invert_mouse_in_use = true; } } } else { is_key_I_released = true; } // adjust position according to the ground. if (!inFlightmode) { if (this->world_species_pointer != NULL) { GLfloat ground_y = model::get_floor_level(static_cast<model::Species*>(this->world_species_pointer), position); if (!std::isnan(ground_y)) { if (position.y < ground_y) { position.y = ground_y; fallSpeed = 0.0f; } } } } #ifdef TESTING_SPHERICAL_WORLD_IN_USE // compute spherical coordinates. spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z)); spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z)); spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x)); #endif earth_radius = EARTH_RADIUS; camera_position = position; camera_position.y += 2.0f; // Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = glm::perspective(FoV, ASPECT_RATIO, 0.001f, 5000.0f + 2.0f * (GLfloat) earth_radius); // Camera matrix ViewMatrix = glm::lookAt( camera_position, // Camera is here camera_position+direction, // and looks here : at the same position, plus "direction" up // Head is up (set to 0,-1,0 to look upside-down) ); // For the next frame, the "last time" will be "now" lastTime = currentTime; } } <commit_msg>Bugikorjaus: Invert mouse toimii nyt oikein.<commit_after>#ifndef PI #define PI 3.14159265359f #endif #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #include "world.hpp" #include "shader.hpp" extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this. namespace model { World::World() { // constructor. } World::~World() { // destructor. std::cout << "This world will be destroyed.\n"; // destroy all shaders of this world. std::cout << "All shaders of this world will be destroyed.\n"; model::delete_children<model::Shader*>(this->shader_pointer_vector); } void World::render() { this->compute_matrices_from_inputs(); // render World by calling `render()` function of each Shader. model::render_children<model::Shader*>(this->shader_pointer_vector); } void World::set_shader_pointer(GLuint childID, void* parent_pointer) { set_child_pointer(childID, parent_pointer, this->shader_pointer_vector, this->free_shaderID_queue); } void World::set_world_species_pointer(void* world_species_pointer) { this->world_species_pointer = world_species_pointer; } void World::compute_matrices_from_inputs() { // glfwGetTime is called only once, the first time this function is called static double lastTime = glfwGetTime(); // Compute time difference between current and last frame double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); // Get mouse position double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2); if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001)) { hasMouseEverMoved = true; // Compute new orientation horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos); horizontalAngle = remainder(horizontalAngle, (2.0f * PI)); if (is_invert_mouse_in_use) { // invert mouse. verticalAngle -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } else { // don't invert mouse. verticalAngle += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } verticalAngle = remainder(verticalAngle, (2.0f * PI)); } // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - PI/2.0f), 0, cos(horizontalAngle - PI/2.0f) ); // Up vector glm::vec3 up = glm::cross(right, direction); GLfloat temp_speed; // Turbo. if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) && (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = twin_turbo_factor * speed; } else if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = turbo_factor * speed; } else { temp_speed = speed; } // Move forward if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction * deltaTime * temp_speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction * deltaTime * temp_speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right * deltaTime * temp_speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right * deltaTime * temp_speed; } // Move up. if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { position.y += deltaTime * temp_speed; } // Move down. if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { position.y -= deltaTime * temp_speed; } // Move west. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { position.x -= deltaTime * temp_speed; } // Move east. if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { position.x += deltaTime * temp_speed; } // Move north. if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) { position.z -= deltaTime * temp_speed; } // Move south. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { position.z += deltaTime * temp_speed; } // Flight mode on. if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) { fallSpeed = 0.0f; inFlightmode = true; } // Run mode on. if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) { fallSpeed = 0.0f; inFlightmode = false; } if (!inFlightmode) { fallSpeed += gravity; position.y -= fallSpeed; } GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS) { if (is_key_I_released) { if (is_invert_mouse_in_use) { is_invert_mouse_in_use = false; } else { is_invert_mouse_in_use = true; } is_key_I_released = false; } } else if (glfwGetKey(window, GLFW_KEY_I) == GLFW_RELEASE) { is_key_I_released = true; } // adjust position according to the ground. if (!inFlightmode) { if (this->world_species_pointer != NULL) { GLfloat ground_y = model::get_floor_level(static_cast<model::Species*>(this->world_species_pointer), position); if (!std::isnan(ground_y)) { if (position.y < ground_y) { position.y = ground_y; fallSpeed = 0.0f; } } } } #ifdef TESTING_SPHERICAL_WORLD_IN_USE // compute spherical coordinates. spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z)); spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z)); spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x)); #endif earth_radius = EARTH_RADIUS; camera_position = position; camera_position.y += 2.0f; // Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = glm::perspective(FoV, ASPECT_RATIO, 0.001f, 5000.0f + 2.0f * (GLfloat) earth_radius); // Camera matrix ViewMatrix = glm::lookAt( camera_position, // Camera is here camera_position+direction, // and looks here : at the same position, plus "direction" up // Head is up (set to 0,-1,0 to look upside-down) ); // For the next frame, the "last time" will be "now" lastTime = currentTime; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mediator.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-15 16:17:41 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef _MEDIATOR_HXX #define _MEDIATOR_HXX #include <string.h> #include <stdarg.h> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _VOS_PIPE_HXX_ #include <vos/pipe.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _VOS_CONDITN_HXX_ #include <vos/conditn.hxx> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif struct MediatorMessage { ULONG m_nID; ULONG m_nBytes; char* m_pBytes; char* m_pRun; MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ), m_pBytes( NULL ), m_pRun( NULL ) {} MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) : m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL ) { m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ~MediatorMessage() { if( m_pBytes ) delete m_pBytes; } void Set( ULONG nBytes, char* pBytes ) { if( m_pBytes ) delete m_pBytes; m_nBytes = nBytes; m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ULONG ExtractULONG(); char* GetString(); UINT32 GetUINT32(); void* GetBytes( ULONG& ); void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); } void Rewind() { m_pRun = NULL; } }; DECLARE_LIST( MediatorMessageList, MediatorMessage* ); class MediatorListener; class Mediator { friend class MediatorListener; protected: int m_nSocket; MediatorMessageList m_aMessageQueue; NAMESPACE_VOS(OMutex) m_aQueueMutex; NAMESPACE_VOS(OMutex) m_aSendMutex; // only one thread can send a message at any given time NAMESPACE_VOS(OCondition) m_aNewMessageCdtn; MediatorListener* m_pListener; // thread to fill the queue ULONG m_nCurrentID; // will be constantly increased with each message sent bool m_bValid; Link m_aConnectionLostHdl; Link m_aNewMessageHdl; public: Mediator( int nSocket ); ~Mediator(); // mark mediator as invalid. No more messages will be processed, // SendMessage, WaitForMessage, TransactMessage will return immediatly // with error void invalidate() { m_bValid = false; } ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 ); ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 ) { return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID ); } BOOL WaitForMessage( ULONG nTimeOut = 5000 ); // timeout in ms // TRUE: Message came in // FALSE: timed out // if timeout is set, WaitForMessage will wait even if there are messages // in the queue virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); // wait for an answer message ( ID >= 1 << 24 ) // the message will be removed from the queue and returned MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes ); // sends a message and waits for an answer MediatorMessage* GetNextMessage( BOOL bWait = FALSE ); Link SetConnectionLostHdl( const Link& rLink ) { Link aRet = m_aConnectionLostHdl; m_aConnectionLostHdl = rLink; return aRet; } Link SetNewMessageHdl( const Link& rLink ) { Link aRet = m_aNewMessageHdl; m_aNewMessageHdl = rLink; return aRet; } }; class MediatorListener : public NAMESPACE_VOS( OThread ) { friend class Mediator; private: Mediator* m_pMediator; ::vos::OMutex m_aMutex; MediatorListener( Mediator* ); ~MediatorListener(); virtual void run(); virtual void onTerminated(); }; inline void medDebug( int condition, char* pFormat, ... ) { #if OSL_DEBUG_LEVEL > 1 if( condition ) { va_list ap; va_start( ap, pFormat ); vfprintf( stderr, pFormat, ap ); va_end( ap ); } #endif } #endif // _MEDIATOR_HXX <commit_msg>INTEGRATION: CWS vcl09 (1.3.10); FILE MERGED 2003/05/08 18:46:19 pl 1.3.10.1: #109426# make rpnp.so work on Linux<commit_after>/************************************************************************* * * $RCSfile: mediator.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-05-28 12:37:54 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef _MEDIATOR_HXX #define _MEDIATOR_HXX #include <string.h> #include <stdarg.h> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _VOS_PIPE_HXX_ #include <vos/pipe.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _VOS_CONDITN_HXX_ #include <vos/conditn.hxx> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif struct MediatorMessage { ULONG m_nID; ULONG m_nBytes; char* m_pBytes; char* m_pRun; MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ), m_pBytes( NULL ), m_pRun( NULL ) {} MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) : m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL ) { m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ~MediatorMessage() { if( m_pBytes ) delete [] m_pBytes; } void Set( ULONG nBytes, char* pBytes ) { if( m_pBytes ) delete [] m_pBytes; m_nBytes = nBytes; m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ULONG ExtractULONG(); char* GetString(); UINT32 GetUINT32(); void* GetBytes( ULONG& ); void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); } void Rewind() { m_pRun = NULL; } }; DECLARE_LIST( MediatorMessageList, MediatorMessage* ); class MediatorListener; class Mediator { friend class MediatorListener; protected: int m_nSocket; MediatorMessageList m_aMessageQueue; NAMESPACE_VOS(OMutex) m_aQueueMutex; NAMESPACE_VOS(OMutex) m_aSendMutex; // only one thread can send a message at any given time NAMESPACE_VOS(OCondition) m_aNewMessageCdtn; MediatorListener* m_pListener; // thread to fill the queue ULONG m_nCurrentID; // will be constantly increased with each message sent bool m_bValid; Link m_aConnectionLostHdl; Link m_aNewMessageHdl; public: Mediator( int nSocket ); ~Mediator(); // mark mediator as invalid. No more messages will be processed, // SendMessage, WaitForMessage, TransactMessage will return immediatly // with error void invalidate() { m_bValid = false; } ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 ); ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 ) { return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID ); } BOOL WaitForMessage( ULONG nTimeOut = 5000 ); // timeout in ms // TRUE: Message came in // FALSE: timed out // if timeout is set, WaitForMessage will wait even if there are messages // in the queue virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); // wait for an answer message ( ID >= 1 << 24 ) // the message will be removed from the queue and returned MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes ); // sends a message and waits for an answer MediatorMessage* GetNextMessage( BOOL bWait = FALSE ); Link SetConnectionLostHdl( const Link& rLink ) { Link aRet = m_aConnectionLostHdl; m_aConnectionLostHdl = rLink; return aRet; } Link SetNewMessageHdl( const Link& rLink ) { Link aRet = m_aNewMessageHdl; m_aNewMessageHdl = rLink; return aRet; } }; class MediatorListener : public NAMESPACE_VOS( OThread ) { friend class Mediator; private: Mediator* m_pMediator; ::vos::OMutex m_aMutex; MediatorListener( Mediator* ); ~MediatorListener(); virtual void run(); virtual void onTerminated(); }; inline void medDebug( int condition, char* pFormat, ... ) { #if OSL_DEBUG_LEVEL > 1 if( condition ) { va_list ap; va_start( ap, pFormat ); vfprintf( stderr, pFormat, ap ); va_end( ap ); } #endif } #endif // _MEDIATOR_HXX <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include "ds5/ds5-options.h" #include "ds5/ds5-motion.h" #include "synthetic-stream.h" #include "motion-transform.h" namespace librealsense { template<rs2_format FORMAT> void copy_hid_axes(byte * const dest[], const byte * source, double factor) { using namespace librealsense; auto hid = (hid_data*)(source); auto res = float3{ float(hid->x), float(hid->y), float(hid->z) } *float(factor); librealsense::copy(dest[0], &res, sizeof(float3)); } // The Accelerometer input format: signed int 16bit. data units 1LSB=0.001g; // Librealsense output format: floating point 32bit. units m/s^2, template<rs2_format FORMAT> void unpack_accel_axes(byte * const dest[], const byte * source, int width, int height, int output_size) { static constexpr float gravity = 9.80665f; // Standard Gravitation Acceleration static constexpr double accelerator_transform_factor = 0.001*gravity; copy_hid_axes<FORMAT>(dest, source, accelerator_transform_factor); } // The Gyro input format: signed int 16bit. data units 1LSB=0.1deg/sec; // Librealsense output format: floating point 32bit. units rad/sec, template<rs2_format FORMAT> void unpack_gyro_axes(byte * const dest[], const byte * source, int width, int height, int output_size) { static const double gyro_transform_factor = deg2rad(0.1); copy_hid_axes<FORMAT>(dest, source, gyro_transform_factor); } motion_transform::motion_transform(rs2_format target_format, rs2_stream target_stream, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform("Motion Transform", target_format, target_stream, mm_calib, mm_correct_opt) {} motion_transform::motion_transform(const char* name, rs2_format target_format, rs2_stream target_stream, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : functional_processing_block(name, target_format, target_stream, RS2_EXTENSION_MOTION_FRAME), _mm_correct_opt(mm_correct_opt) { if (mm_calib) { _imu2depth_cs_alignment_matrix = (*mm_calib).imu_to_depth_alignment(); if (_mm_correct_opt) { auto accel_intr = (*mm_calib).get_intrinsic(RS2_STREAM_ACCEL); auto gyro_intr = (*mm_calib).get_intrinsic(RS2_STREAM_GYRO); _accel_sensitivity = accel_intr.sensitivity; _accel_bias = accel_intr.bias; _gyro_sensitivity = gyro_intr.sensitivity; _gyro_bias = gyro_intr.bias; } } else { // TODO Define L500 base transformation alignment _imu2depth_cs_alignment_matrix = { {1,0,0},{0,1,0}, {0,0,1} }; } } rs2::frame motion_transform::process_frame(const rs2::frame_source& source, const rs2::frame& f) { auto&& ret = functional_processing_block::process_frame(source, f); correct_motion(&ret); return ret; } void motion_transform::correct_motion(rs2::frame* f) { auto xyz = (float3*)(f->get_data()); if (_mm_correct_opt) { if ((_mm_correct_opt->query() > 0.f)) // TBD resolve duality of is_enabled/is_active { auto&& s = f->get_profile().stream_type(); if (s == RS2_STREAM_ACCEL) *xyz = (_accel_sensitivity * (*xyz)) - _accel_bias; if (s == RS2_STREAM_GYRO) *xyz = _gyro_sensitivity * (*xyz) - _gyro_bias; } } // The IMU sensor orientation shall be aligned with depth sensor's coordinate system *xyz = _imu2depth_cs_alignment_matrix * (*xyz); } acceleration_transform::acceleration_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : acceleration_transform("Acceleration Transform", mm_calib, mm_correct_opt) {} acceleration_transform::acceleration_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_ACCEL, mm_calib, mm_correct_opt) {} void acceleration_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size) { unpack_accel_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size); } gyroscope_transform::gyroscope_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : gyroscope_transform("Gyroscope Transform", mm_calib, mm_correct_opt) {} gyroscope_transform::gyroscope_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_GYRO, mm_calib, mm_correct_opt) {} void gyroscope_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size) { unpack_gyro_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size); } } <commit_msg>fix imu motion correction issues<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include "ds5/ds5-options.h" #include "ds5/ds5-motion.h" #include "synthetic-stream.h" #include "motion-transform.h" namespace librealsense { template<rs2_format FORMAT> void copy_hid_axes(byte * const dest[], const byte * source, double factor) { using namespace librealsense; auto hid = (hid_data*)(source); auto res = float3{ float(hid->x), float(hid->y), float(hid->z) } *float(factor); librealsense::copy(dest[0], &res, sizeof(float3)); } // The Accelerometer input format: signed int 16bit. data units 1LSB=0.001g; // Librealsense output format: floating point 32bit. units m/s^2, template<rs2_format FORMAT> void unpack_accel_axes(byte * const dest[], const byte * source, int width, int height, int output_size) { static constexpr float gravity = 9.80665f; // Standard Gravitation Acceleration static constexpr double accelerator_transform_factor = 0.001*gravity; copy_hid_axes<FORMAT>(dest, source, accelerator_transform_factor); } // The Gyro input format: signed int 16bit. data units 1LSB=0.1deg/sec; // Librealsense output format: floating point 32bit. units rad/sec, template<rs2_format FORMAT> void unpack_gyro_axes(byte * const dest[], const byte * source, int width, int height, int output_size) { static const double gyro_transform_factor = deg2rad(0.1); copy_hid_axes<FORMAT>(dest, source, gyro_transform_factor); } motion_transform::motion_transform(rs2_format target_format, rs2_stream target_stream, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform("Motion Transform", target_format, target_stream, mm_calib, mm_correct_opt) {} motion_transform::motion_transform(const char* name, rs2_format target_format, rs2_stream target_stream, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : functional_processing_block(name, target_format, target_stream, RS2_EXTENSION_MOTION_FRAME), _mm_correct_opt(mm_correct_opt) { if (mm_calib) { _imu2depth_cs_alignment_matrix = (*mm_calib).imu_to_depth_alignment(); if (_mm_correct_opt) { auto accel_intr = (*mm_calib).get_intrinsic(RS2_STREAM_ACCEL); auto gyro_intr = (*mm_calib).get_intrinsic(RS2_STREAM_GYRO); _accel_sensitivity = accel_intr.sensitivity; _accel_bias = accel_intr.bias; _gyro_sensitivity = gyro_intr.sensitivity; _gyro_bias = gyro_intr.bias; } } else { // TODO Define L500 base transformation alignment _imu2depth_cs_alignment_matrix = { {1,0,0},{0,1,0}, {0,0,1} }; } } rs2::frame motion_transform::process_frame(const rs2::frame_source& source, const rs2::frame& f) { auto&& ret = functional_processing_block::process_frame(source, f); correct_motion(&ret); return ret; } void motion_transform::correct_motion(rs2::frame* f) { auto xyz = (float3*)(f->get_data()); // The IMU sensor orientation shall be aligned with depth sensor's coordinate system *xyz = _imu2depth_cs_alignment_matrix * (*xyz); // IMU calibration is done with data in depth sensor's coordinate system, so calibration parameters should be applied for motion correction // in the same coordinate system if (_mm_correct_opt) { if ((_mm_correct_opt->query() > 0.f)) // TBD resolve duality of is_enabled/is_active { auto&& s = f->get_profile().stream_type(); if (s == RS2_STREAM_ACCEL) *xyz = (_accel_sensitivity * (*xyz)) - _accel_bias; if (s == RS2_STREAM_GYRO) *xyz = _gyro_sensitivity * (*xyz) - _gyro_bias; } } } acceleration_transform::acceleration_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : acceleration_transform("Acceleration Transform", mm_calib, mm_correct_opt) {} acceleration_transform::acceleration_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_ACCEL, mm_calib, mm_correct_opt) {} void acceleration_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size) { unpack_accel_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size); } gyroscope_transform::gyroscope_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : gyroscope_transform("Gyroscope Transform", mm_calib, mm_correct_opt) {} gyroscope_transform::gyroscope_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt) : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_GYRO, mm_calib, mm_correct_opt) {} void gyroscope_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size) { unpack_gyro_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size); } } <|endoftext|>
<commit_before>#include "arch/runtime/runtime.hpp" #include "arch/runtime/starter.hpp" #include "utils.hpp" #include <boost/bind.hpp> #include "arch/runtime/thread_pool.hpp" #include "do_on_thread.hpp" int get_thread_id() { return linux_thread_pool_t::thread_id; } int get_num_threads() { return linux_thread_pool_t::thread_pool->n_threads; } int thread_local_randint(int n) { return linux_thread_pool_t::thread->thread_local_rng.randint(n); } #ifndef NDEBUG void assert_good_thread_id(int thread) { rassert(thread >= 0, "(thread = %d)", thread); rassert(thread < get_num_threads(), "(thread = %d, n_threads = %d)", thread, get_num_threads()); } #endif bool continue_on_thread(int thread, linux_thread_message_t *msg) { assert_good_thread_id(thread); if (thread == linux_thread_pool_t::thread_id) { // The thread to continue on is the thread we are already on return true; } else { linux_thread_pool_t::thread->message_hub.store_message(thread, msg); return false; } } void call_later_on_this_thread(linux_thread_message_t *msg) { linux_thread_pool_t::thread->message_hub.store_message(linux_thread_pool_t::thread_id, msg); } struct starter_t : public thread_message_t { linux_thread_pool_t *tp; boost::function<void()> run; starter_t(linux_thread_pool_t *_tp, const boost::function<void()>& _fun) : tp(_tp), run(boost::bind(&starter_t::run_wrapper, this, _fun)) { } void on_thread_switch() { const int run_thread = 0; rassert(get_thread_id() != run_thread); do_on_thread(run_thread, boost::bind(&coro_t::spawn_now< boost::function<void()> >, boost::ref(run))); } private: void run_wrapper(const boost::function<void()>& fun) { fun(); tp->shutdown(); } }; void run_in_thread_pool(const boost::function<void()>& fun, int num_threads) { linux_thread_pool_t thread_pool(num_threads, false); starter_t starter(&thread_pool, fun); thread_pool.run(&starter); } <commit_msg>Make run_in_thread_pool() not try to switch back after spawning coroutine. Fixes #565.<commit_after>#include "arch/runtime/runtime.hpp" #include "arch/runtime/starter.hpp" #include "utils.hpp" #include <boost/bind.hpp> #include "arch/runtime/thread_pool.hpp" #include "do_on_thread.hpp" int get_thread_id() { return linux_thread_pool_t::thread_id; } int get_num_threads() { return linux_thread_pool_t::thread_pool->n_threads; } int thread_local_randint(int n) { return linux_thread_pool_t::thread->thread_local_rng.randint(n); } #ifndef NDEBUG void assert_good_thread_id(int thread) { rassert(thread >= 0, "(thread = %d)", thread); rassert(thread < get_num_threads(), "(thread = %d, n_threads = %d)", thread, get_num_threads()); } #endif bool continue_on_thread(int thread, linux_thread_message_t *msg) { assert_good_thread_id(thread); if (thread == linux_thread_pool_t::thread_id) { // The thread to continue on is the thread we are already on return true; } else { linux_thread_pool_t::thread->message_hub.store_message(thread, msg); return false; } } void call_later_on_this_thread(linux_thread_message_t *msg) { linux_thread_pool_t::thread->message_hub.store_message(linux_thread_pool_t::thread_id, msg); } struct starter_t : public thread_message_t { linux_thread_pool_t *tp; boost::function<void()> run; starter_t(linux_thread_pool_t *_tp, const boost::function<void()>& _fun) : tp(_tp), run(boost::bind(&starter_t::run_wrapper, this, _fun)) { } void on_thread_switch() { const int run_thread = 0; rassert(get_thread_id() != run_thread); one_way_do_on_thread(run_thread, boost::bind(&coro_t::spawn_sometime< boost::function<void()> >, boost::ref(run))); } private: void run_wrapper(const boost::function<void()>& fun) { fun(); tp->shutdown(); } }; void run_in_thread_pool(const boost::function<void()>& fun, int num_threads) { linux_thread_pool_t thread_pool(num_threads, false); starter_t starter(&thread_pool, fun); thread_pool.run(&starter); } <|endoftext|>
<commit_before>#pragma once #include <vector> #include "graph.hpp" namespace simple_graph { template<typename V, typename E> bool bellman_ford(const Graph<V, E> &g, size_t start_idx, size_t goal_idx, std::vector<size_t> *path) { std::vector<size_t> distance(g.vertex_num(), std::numeric_limits<size_t>::max()); std::vector<size_t> predecessor(g.vertex_num(), 0); distance[start_idx] = 0; Graph<V, E> *fg = const_cast<Graph<V, E>*>(&g); for (size_t i = 0; i < g.vertex_num(); ++i) { for (auto e : fg->edges()) { if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) { distance[e.idx2()] = distance[e.idx1()] + e.weight(); predecessor[e.idx2()] = e.idx1(); } } } for (auto e : fg->edges()) { if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) { return false; } } if (distance[goal_idx] == 0) { return false; } size_t idx = goal_idx; while (idx != start_idx) { path->push_back(idx); idx = predecessor[idx]; } path->push_back(idx); std::reverse(path->begin(), path->end()); return true; } } // simple_graph <commit_msg>Fix Bellman-Ford algorithm for negative edge weights<commit_after>#pragma once #include <vector> #include "graph.hpp" namespace simple_graph { template<typename V, typename E> bool bellman_ford(const Graph<V, E> &g, size_t start_idx, size_t goal_idx, std::vector<size_t> *path) { std::vector<E> distance(g.vertex_num(), std::numeric_limits<E>::max()); std::vector<size_t> predecessor(g.vertex_num(), 0); distance[start_idx] = 0; Graph<V, E> *fg = const_cast<Graph<V, E>*>(&g); for (size_t i = 0; i < g.vertex_num(); ++i) { for (auto e : fg->edges()) { if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) { distance[e.idx2()] = distance[e.idx1()] + e.weight(); predecessor[e.idx2()] = e.idx1(); } } } for (auto e : fg->edges()) { if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) { return false; } } if (distance[goal_idx] == 0) { return false; } size_t idx = goal_idx; while (idx != start_idx) { path->push_back(idx); idx = predecessor[idx]; } path->push_back(idx); std::reverse(path->begin(), path->end()); return true; } } // simple_graph <|endoftext|>
<commit_before>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #define TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #include <cstddef> #include <cstdint> #include <string> #include <string_view> #include "iterator.hpp" #include "../config.hpp" #include "../position.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { [[nodiscard]] inline const char* begin_c_ptr( const char* p ) noexcept { return p; } [[nodiscard]] inline const char* begin_c_ptr( const iterator& it ) noexcept { return it.data; } template< typename Input > class action_input { public: using input_t = Input; using iterator_t = typename Input::iterator_t; action_input( const iterator_t& in_begin, const Input& in_input ) noexcept : m_begin( in_begin ), m_input( in_input ) { } action_input( const action_input& ) = delete; action_input( action_input&& ) = delete; ~action_input() = default; action_input& operator=( const action_input& ) = delete; action_input& operator=( action_input&& ) = delete; [[nodiscard]] const iterator_t& iterator() const noexcept { return m_begin; } [[nodiscard]] const Input& input() const noexcept { return m_input; } [[nodiscard]] const char* begin() const noexcept { return begin_c_ptr( iterator() ); } [[nodiscard]] const char* end() const noexcept { return input().current(); } [[nodiscard]] bool empty() const noexcept { return begin() == end(); } [[nodiscard]] std::size_t size() const noexcept { return std::size_t( end() - begin() ); } [[nodiscard]] std::string string() const { return std::string( begin(), end() ); } [[nodiscard]] std::string_view string_view() const noexcept { return std::string_view( begin(), size() ); } [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept { return begin()[ offset ]; } [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept { return static_cast< std::uint8_t >( peek_char( offset ) ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const { return input().position( iterator() ); // NOTE: Not efficient with lazy inputs. } protected: const iterator_t m_begin; const Input& m_input; }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif <commit_msg>Modernize<commit_after>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #define TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #include <cstddef> #include <cstdint> #include <string> #include <string_view> #include "iterator.hpp" #include "../config.hpp" #include "../position.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename Input > class action_input { public: using input_t = Input; using iterator_t = typename Input::iterator_t; action_input( const iterator_t& in_begin, const Input& in_input ) noexcept : m_begin( in_begin ), m_input( in_input ) { } action_input( const action_input& ) = delete; action_input( action_input&& ) = delete; ~action_input() = default; action_input& operator=( const action_input& ) = delete; action_input& operator=( action_input&& ) = delete; [[nodiscard]] const iterator_t& iterator() const noexcept { return m_begin; } [[nodiscard]] const Input& input() const noexcept { return m_input; } [[nodiscard]] const char* begin() const noexcept { if constexpr( std::is_same_v< iterator_t, const char* > ) { return iterator(); } else { // NOLINT return iterator().data; } } [[nodiscard]] const char* end() const noexcept { return input().current(); } [[nodiscard]] bool empty() const noexcept { return begin() == end(); } [[nodiscard]] std::size_t size() const noexcept { return std::size_t( end() - begin() ); } [[nodiscard]] std::string string() const { return std::string( begin(), end() ); } [[nodiscard]] std::string_view string_view() const noexcept { return std::string_view( begin(), size() ); } [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept { return begin()[ offset ]; } [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept { return static_cast< std::uint8_t >( peek_char( offset ) ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const { return input().position( iterator() ); // NOTE: Not efficient with lazy inputs. } protected: const iterator_t m_begin; const Input& m_input; }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2013 Aldebaran Robotics */ #include <qi/iocolor.hpp> #include <sstream> #include <qi/os.hpp> #if defined(__APPLE__) or defined(__linux__) static std::string makeCol(char c, char modifier = -1) { std::stringstream ret; ret << "\033[" << (int)c; if (modifier > 0) ret << ";" << (int)modifier; ret << "m"; return ret.str(); } static void posix_print(std::ostream& os, qi::StreamColor col) { switch (col) { case qi::StreamColor_None: break; case qi::StreamColor_Reset: os << makeCol(0); break; case qi::StreamColor_Bold: os << makeCol(1); break; case qi::StreamColor_Faint: os << makeCol(2); break; case qi::StreamColor_Standout: os << makeCol(3); break; case qi::StreamColor_Underline: os << makeCol(4); break; case qi::StreamColor_Blink: os << makeCol(5); break; case qi::StreamColor_Overline: os << makeCol(6); break; case qi::StreamColor_Black: os << makeCol(30, 0); break; case qi::StreamColor_DarkRed: os << makeCol(31, 0); break; case qi::StreamColor_DarkGreen: os << makeCol(32, 0); break; case qi::StreamColor_Brown: os << makeCol(33, 0); break; case qi::StreamColor_DarkBlue: os << makeCol(34, 0); break; case qi::StreamColor_Purple: os << makeCol(35, 0); break; case qi::StreamColor_Teal: os << makeCol(36, 0); break; case qi::StreamColor_LightGray: os << makeCol(37, 0); break; case qi::StreamColor_DarkGray: os << makeCol(30, 1); break; case qi::StreamColor_Red: os << makeCol(31, 1); break; case qi::StreamColor_Green: os << makeCol(32, 1); break; case qi::StreamColor_Yellow: os << makeCol(33, 1); break; case qi::StreamColor_Blue: os << makeCol(34, 1); break; case qi::StreamColor_Fuchsia: os << makeCol(35, 1); break; case qi::StreamColor_Turquoise: os << makeCol(36, 1); break; case qi::StreamColor_White: os << makeCol(37, 1); break; }; } #endif namespace std { std::ostream& operator<<(std::ostream& os, qi::StreamColor col) { if (&os == &(std::cout) && !qi::os::isatty(1)) return os; if (&os == &(std::cerr) && !qi::os::isatty(2)) return os; #if defined(__APPLE__) or defined(__linux__) posix_print(os, col); #endif return os; } } <commit_msg>blind fix for windows warning<commit_after>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2013 Aldebaran Robotics */ #include <qi/iocolor.hpp> #include <sstream> #include <qi/os.hpp> #if defined(__APPLE__) || defined(__linux__) static std::string makeCol(char c, char modifier = -1) { std::stringstream ret; ret << "\033[" << (int)c; if (modifier > 0) ret << ";" << (int)modifier; ret << "m"; return ret.str(); } static void posix_print(std::ostream& os, qi::StreamColor col) { switch (col) { case qi::StreamColor_None: break; case qi::StreamColor_Reset: os << makeCol(0); break; case qi::StreamColor_Bold: os << makeCol(1); break; case qi::StreamColor_Faint: os << makeCol(2); break; case qi::StreamColor_Standout: os << makeCol(3); break; case qi::StreamColor_Underline: os << makeCol(4); break; case qi::StreamColor_Blink: os << makeCol(5); break; case qi::StreamColor_Overline: os << makeCol(6); break; case qi::StreamColor_Black: os << makeCol(30, 0); break; case qi::StreamColor_DarkRed: os << makeCol(31, 0); break; case qi::StreamColor_DarkGreen: os << makeCol(32, 0); break; case qi::StreamColor_Brown: os << makeCol(33, 0); break; case qi::StreamColor_DarkBlue: os << makeCol(34, 0); break; case qi::StreamColor_Purple: os << makeCol(35, 0); break; case qi::StreamColor_Teal: os << makeCol(36, 0); break; case qi::StreamColor_LightGray: os << makeCol(37, 0); break; case qi::StreamColor_DarkGray: os << makeCol(30, 1); break; case qi::StreamColor_Red: os << makeCol(31, 1); break; case qi::StreamColor_Green: os << makeCol(32, 1); break; case qi::StreamColor_Yellow: os << makeCol(33, 1); break; case qi::StreamColor_Blue: os << makeCol(34, 1); break; case qi::StreamColor_Fuchsia: os << makeCol(35, 1); break; case qi::StreamColor_Turquoise: os << makeCol(36, 1); break; case qi::StreamColor_White: os << makeCol(37, 1); break; }; } #endif namespace std { std::ostream& operator<<(std::ostream& os, qi::StreamColor col) { if (&os == &(std::cout) && !qi::os::isatty(1)) return os; if (&os == &(std::cerr) && !qi::os::isatty(2)) return os; #if defined(__APPLE__) || defined(__linux__) posix_print(os, col); #endif return os; } } <|endoftext|>
<commit_before>#ifndef CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ #define CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ #include <string> #include "errors.hpp" #include <boost/uuid/uuid.hpp> #include "utils.hpp" #include "http/json/json_adapter.hpp" enum _issue_type_t { VCLOCK_CONFLICT, MACHINE_DOWN, NAME_CONFLICT_ISSUE, PERSISTENCE_ISSUE, PINNINGS_SHARDS_MISMATCH }; class issue_type_t { public: _issue_type_t issue_type; }; //json adapter concept for issue_type_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_type_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(issue_type_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, issue_type_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(issue_type_t *, const ctx_t &); class issue_json_t { public: bool critical; std::string description; issue_type_t type; ticks_t time; }; //json adapter concept for issue_json_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_json_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(issue_json_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, issue_json_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(issue_json_t *, const ctx_t &); //A local issue occurs on a single machine class local_issue_json_t : public issue_json_t { public: boost::uuids::uuid machine; }; //json adapter concept for local_issue_json_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(local_issue_json_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(local_issue_json_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, local_issue_json_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(local_issue_json_t *, const ctx_t &); #include "clustering/administration/issues/json.tcc" #endif // CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ <commit_msg>Added a TODO comment about local_issue_json_t.<commit_after>#ifndef CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ #define CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ #include <string> #include "errors.hpp" #include <boost/uuid/uuid.hpp> #include "utils.hpp" #include "http/json/json_adapter.hpp" enum _issue_type_t { VCLOCK_CONFLICT, MACHINE_DOWN, NAME_CONFLICT_ISSUE, PERSISTENCE_ISSUE, PINNINGS_SHARDS_MISMATCH }; class issue_type_t { public: _issue_type_t issue_type; }; //json adapter concept for issue_type_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_type_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(issue_type_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, issue_type_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(issue_type_t *, const ctx_t &); class issue_json_t { public: bool critical; std::string description; issue_type_t type; ticks_t time; }; //json adapter concept for issue_json_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_json_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(issue_json_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, issue_json_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(issue_json_t *, const ctx_t &); // TODO: Why the fuck is this inheriting instead of using composition? //A local issue occurs on a single machine class local_issue_json_t : public issue_json_t { public: boost::uuids::uuid machine; }; //json adapter concept for local_issue_json_t template <class ctx_t> typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(local_issue_json_t *, const ctx_t &); template <class ctx_t> cJSON *render_as_json(local_issue_json_t *, const ctx_t &); template <class ctx_t> void apply_json_to(cJSON *, local_issue_json_t *, const ctx_t &); template <class ctx_t> void on_subfield_change(local_issue_json_t *, const ctx_t &); #include "clustering/administration/issues/json.tcc" #endif // CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_ <|endoftext|>
<commit_before>/** * Copyright (c) 2014, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h" #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "auto_mem.hh" #include "lnav_log.hh" #include "sql_util.hh" #include "environ_vtab.hh" using namespace std; extern char **environ; const char *ENVIRON_CREATE_STMT = "\ -- Access lnav's environment variables through this table.\n\ CREATE TABLE environ (\n\ name text PRIMARY KEY,\n\ value text\n\ );\n\ "; struct vtab { sqlite3_vtab base; sqlite3 * db; }; struct vtab_cursor { sqlite3_vtab_cursor base; char **env_cursor; }; static int vt_destructor(sqlite3_vtab *p_svt); static int vt_create(sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **pp_vt, char **pzErr) { vtab *p_vt; /* Allocate the sqlite3_vtab/vtab structure itself */ p_vt = (vtab *)sqlite3_malloc(sizeof(*p_vt)); if (p_vt == NULL) { return SQLITE_NOMEM; } memset(&p_vt->base, 0, sizeof(sqlite3_vtab)); p_vt->db = db; *pp_vt = &p_vt->base; int rc = sqlite3_declare_vtab(db, ENVIRON_CREATE_STMT); return rc; } static int vt_destructor(sqlite3_vtab *p_svt) { vtab *p_vt = (vtab *)p_svt; /* Free the SQLite structure */ sqlite3_free(p_vt); return SQLITE_OK; } static int vt_connect(sqlite3 *db, void *p_aux, int argc, const char *const *argv, sqlite3_vtab **pp_vt, char **pzErr) { return vt_create(db, p_aux, argc, argv, pp_vt, pzErr); } static int vt_disconnect(sqlite3_vtab *pVtab) { return vt_destructor(pVtab); } static int vt_destroy(sqlite3_vtab *p_vt) { return vt_destructor(p_vt); } static int vt_next(sqlite3_vtab_cursor *cur); static int vt_open(sqlite3_vtab *p_svt, sqlite3_vtab_cursor **pp_cursor) { vtab *p_vt = (vtab *)p_svt; p_vt->base.zErrMsg = NULL; vtab_cursor *p_cur = (vtab_cursor *)new vtab_cursor(); if (p_cur == NULL) { return SQLITE_NOMEM; } else { *pp_cursor = (sqlite3_vtab_cursor *)p_cur; p_cur->base.pVtab = p_svt; p_cur->env_cursor = environ; vt_next((sqlite3_vtab_cursor *)p_cur); } return SQLITE_OK; } static int vt_close(sqlite3_vtab_cursor *cur) { vtab_cursor *p_cur = (vtab_cursor *)cur; /* Free cursor struct. */ delete p_cur; return SQLITE_OK; } static int vt_eof(sqlite3_vtab_cursor *cur) { vtab_cursor *vc = (vtab_cursor *)cur; return vc->env_cursor[0] == NULL; } static int vt_next(sqlite3_vtab_cursor *cur) { vtab_cursor *vc = (vtab_cursor *)cur; if (vc->env_cursor[0] != NULL) { vc->env_cursor += 1; } return SQLITE_OK; } static int vt_column(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int col) { vtab_cursor *vc = (vtab_cursor *)cur; const char *eq = strchr(vc->env_cursor[0], '='); switch (col) { case 0: sqlite3_result_text(ctx, vc->env_cursor[0], eq - vc->env_cursor[0], SQLITE_TRANSIENT); break; case 1: sqlite3_result_text(ctx, eq + 1, -1, SQLITE_TRANSIENT); break; } return SQLITE_OK; } static int vt_rowid(sqlite3_vtab_cursor *cur, sqlite_int64 *p_rowid) { vtab_cursor *p_cur = (vtab_cursor *)cur; *p_rowid = (int64_t)p_cur->env_cursor[0]; return SQLITE_OK; } static int vt_best_index(sqlite3_vtab *tab, sqlite3_index_info *p_info) { return SQLITE_OK; } static int vt_filter(sqlite3_vtab_cursor *p_vtc, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) { return SQLITE_OK; } static int vt_update(sqlite3_vtab *tab, int argc, sqlite3_value **argv, sqlite_int64 *rowid) { const char *name = ( argc > 2 ? (const char *)sqlite3_value_text(argv[2]) : NULL); vtab *p_vt = (vtab *)tab; int retval = SQLITE_ERROR; if (argc != 1 && (argc < 3 || sqlite3_value_type(argv[2]) == SQLITE_NULL || sqlite3_value_type(argv[3]) == SQLITE_NULL || sqlite3_value_text(argv[2])[0] == '\0')) { tab->zErrMsg = sqlite3_mprintf( "A non-empty name and value must be provided when inserting an " "environment variable"); return SQLITE_ERROR; } if (name != NULL && strchr(name, '=') != NULL) { tab->zErrMsg = sqlite3_mprintf( "Environment variable names cannot contain an equals sign (=)"); return SQLITE_ERROR; } if (sqlite3_value_type(argv[0]) != SQLITE_NULL) { int64_t index = sqlite3_value_int64(argv[0]); const char *var = (const char *)index; const char *eq = strchr(var, '='); size_t namelen = eq - var; char name[namelen + 1]; memcpy(name, var, namelen); name[namelen] = '\0'; unsetenv(name); retval = SQLITE_OK; } else if (name != NULL && getenv(name) != NULL) { #ifdef SQLITE_FAIL int rc; rc = sqlite3_vtab_on_conflict(p_vt->db); switch (rc) { case SQLITE_FAIL: case SQLITE_ABORT: tab->zErrMsg = sqlite3_mprintf( "An environment variable with the name '%s' already exists", name); return rc; case SQLITE_IGNORE: return SQLITE_OK; case SQLITE_REPLACE: break; default: return rc; } #endif } if (name != NULL && argc == 4) { const unsigned char *value = sqlite3_value_text(argv[3]); setenv((const char *)name, (const char *)value, 1); return SQLITE_OK; } return retval; } static sqlite3_module vtab_module = { 0, /* iVersion */ vt_create, /* xCreate - create a vtable */ vt_connect, /* xConnect - associate a vtable with a connection */ vt_best_index, /* xBestIndex - best index */ vt_disconnect, /* xDisconnect - disassociate a vtable with a connection */ vt_destroy, /* xDestroy - destroy a vtable */ vt_open, /* xOpen - open a cursor */ vt_close, /* xClose - close a cursor */ vt_filter, /* xFilter - configure scan constraints */ vt_next, /* xNext - advance a cursor */ vt_eof, /* xEof - inidicate end of result set*/ vt_column, /* xColumn - read data */ vt_rowid, /* xRowid - read data */ vt_update, /* xUpdate - write data */ NULL, /* xBegin - begin transaction */ NULL, /* xSync - sync transaction */ NULL, /* xCommit - commit transaction */ NULL, /* xRollback - rollback transaction */ NULL, /* xFindFunction - function overloading */ }; int register_environ_vtab(sqlite3 *db) { auto_mem<char, sqlite3_free> errmsg; int rc; rc = sqlite3_create_module(db, "environ_vtab_impl", &vtab_module, NULL); assert(rc == SQLITE_OK); if ((rc = sqlite3_exec(db, "CREATE VIRTUAL TABLE environ USING environ_vtab_impl()", NULL, NULL, errmsg.out())) != SQLITE_OK) { fprintf(stderr, "wtf %s\n", errmsg.in()); } return rc; } <commit_msg>[environ_vtab] the first var was being skipped<commit_after>/** * Copyright (c) 2014, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h" #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "auto_mem.hh" #include "lnav_log.hh" #include "sql_util.hh" #include "environ_vtab.hh" using namespace std; extern char **environ; const char *ENVIRON_CREATE_STMT = "\ -- Access lnav's environment variables through this table.\n\ CREATE TABLE environ (\n\ name text PRIMARY KEY,\n\ value text\n\ );\n\ "; struct vtab { sqlite3_vtab base; sqlite3 * db; }; struct vtab_cursor { sqlite3_vtab_cursor base; char **env_cursor; }; static int vt_destructor(sqlite3_vtab *p_svt); static int vt_create(sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **pp_vt, char **pzErr) { vtab *p_vt; /* Allocate the sqlite3_vtab/vtab structure itself */ p_vt = (vtab *)sqlite3_malloc(sizeof(*p_vt)); if (p_vt == NULL) { return SQLITE_NOMEM; } memset(&p_vt->base, 0, sizeof(sqlite3_vtab)); p_vt->db = db; *pp_vt = &p_vt->base; int rc = sqlite3_declare_vtab(db, ENVIRON_CREATE_STMT); return rc; } static int vt_destructor(sqlite3_vtab *p_svt) { vtab *p_vt = (vtab *)p_svt; /* Free the SQLite structure */ sqlite3_free(p_vt); return SQLITE_OK; } static int vt_connect(sqlite3 *db, void *p_aux, int argc, const char *const *argv, sqlite3_vtab **pp_vt, char **pzErr) { return vt_create(db, p_aux, argc, argv, pp_vt, pzErr); } static int vt_disconnect(sqlite3_vtab *pVtab) { return vt_destructor(pVtab); } static int vt_destroy(sqlite3_vtab *p_vt) { return vt_destructor(p_vt); } static int vt_next(sqlite3_vtab_cursor *cur); static int vt_open(sqlite3_vtab *p_svt, sqlite3_vtab_cursor **pp_cursor) { vtab *p_vt = (vtab *)p_svt; p_vt->base.zErrMsg = NULL; vtab_cursor *p_cur = (vtab_cursor *)new vtab_cursor(); if (p_cur == NULL) { return SQLITE_NOMEM; } else { *pp_cursor = (sqlite3_vtab_cursor *)p_cur; p_cur->base.pVtab = p_svt; p_cur->env_cursor = environ; } return SQLITE_OK; } static int vt_close(sqlite3_vtab_cursor *cur) { vtab_cursor *p_cur = (vtab_cursor *)cur; /* Free cursor struct. */ delete p_cur; return SQLITE_OK; } static int vt_eof(sqlite3_vtab_cursor *cur) { vtab_cursor *vc = (vtab_cursor *)cur; return vc->env_cursor[0] == NULL; } static int vt_next(sqlite3_vtab_cursor *cur) { vtab_cursor *vc = (vtab_cursor *)cur; if (vc->env_cursor[0] != NULL) { vc->env_cursor += 1; } return SQLITE_OK; } static int vt_column(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int col) { vtab_cursor *vc = (vtab_cursor *)cur; const char *eq = strchr(vc->env_cursor[0], '='); switch (col) { case 0: sqlite3_result_text(ctx, vc->env_cursor[0], eq - vc->env_cursor[0], SQLITE_TRANSIENT); break; case 1: sqlite3_result_text(ctx, eq + 1, -1, SQLITE_TRANSIENT); break; } return SQLITE_OK; } static int vt_rowid(sqlite3_vtab_cursor *cur, sqlite_int64 *p_rowid) { vtab_cursor *p_cur = (vtab_cursor *)cur; *p_rowid = (int64_t)p_cur->env_cursor[0]; return SQLITE_OK; } static int vt_best_index(sqlite3_vtab *tab, sqlite3_index_info *p_info) { return SQLITE_OK; } static int vt_filter(sqlite3_vtab_cursor *p_vtc, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) { return SQLITE_OK; } static int vt_update(sqlite3_vtab *tab, int argc, sqlite3_value **argv, sqlite_int64 *rowid) { const char *name = ( argc > 2 ? (const char *)sqlite3_value_text(argv[2]) : NULL); vtab *p_vt = (vtab *)tab; int retval = SQLITE_ERROR; if (argc != 1 && (argc < 3 || sqlite3_value_type(argv[2]) == SQLITE_NULL || sqlite3_value_type(argv[3]) == SQLITE_NULL || sqlite3_value_text(argv[2])[0] == '\0')) { tab->zErrMsg = sqlite3_mprintf( "A non-empty name and value must be provided when inserting an " "environment variable"); return SQLITE_ERROR; } if (name != NULL && strchr(name, '=') != NULL) { tab->zErrMsg = sqlite3_mprintf( "Environment variable names cannot contain an equals sign (=)"); return SQLITE_ERROR; } if (sqlite3_value_type(argv[0]) != SQLITE_NULL) { int64_t index = sqlite3_value_int64(argv[0]); const char *var = (const char *)index; const char *eq = strchr(var, '='); size_t namelen = eq - var; char name[namelen + 1]; memcpy(name, var, namelen); name[namelen] = '\0'; unsetenv(name); retval = SQLITE_OK; } else if (name != NULL && getenv(name) != NULL) { #ifdef SQLITE_FAIL int rc; rc = sqlite3_vtab_on_conflict(p_vt->db); switch (rc) { case SQLITE_FAIL: case SQLITE_ABORT: tab->zErrMsg = sqlite3_mprintf( "An environment variable with the name '%s' already exists", name); return rc; case SQLITE_IGNORE: return SQLITE_OK; case SQLITE_REPLACE: break; default: return rc; } #endif } if (name != NULL && argc == 4) { const unsigned char *value = sqlite3_value_text(argv[3]); setenv((const char *)name, (const char *)value, 1); return SQLITE_OK; } return retval; } static sqlite3_module vtab_module = { 0, /* iVersion */ vt_create, /* xCreate - create a vtable */ vt_connect, /* xConnect - associate a vtable with a connection */ vt_best_index, /* xBestIndex - best index */ vt_disconnect, /* xDisconnect - disassociate a vtable with a connection */ vt_destroy, /* xDestroy - destroy a vtable */ vt_open, /* xOpen - open a cursor */ vt_close, /* xClose - close a cursor */ vt_filter, /* xFilter - configure scan constraints */ vt_next, /* xNext - advance a cursor */ vt_eof, /* xEof - inidicate end of result set*/ vt_column, /* xColumn - read data */ vt_rowid, /* xRowid - read data */ vt_update, /* xUpdate - write data */ NULL, /* xBegin - begin transaction */ NULL, /* xSync - sync transaction */ NULL, /* xCommit - commit transaction */ NULL, /* xRollback - rollback transaction */ NULL, /* xFindFunction - function overloading */ }; int register_environ_vtab(sqlite3 *db) { auto_mem<char, sqlite3_free> errmsg; int rc; rc = sqlite3_create_module(db, "environ_vtab_impl", &vtab_module, NULL); assert(rc == SQLITE_OK); if ((rc = sqlite3_exec(db, "CREATE VIRTUAL TABLE environ USING environ_vtab_impl()", NULL, NULL, errmsg.out())) != SQLITE_OK) { fprintf(stderr, "wtf %s\n", errmsg.in()); } return rc; } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <rapidjson/rapidjson.h> #include <rapidjson/filereadstream.h> #include <rapidjson/document.h> #include "Sprite.h" #include "CompileConfig.h" #include "Engine.h" #include "Renderer.h" #include "Texture.h" #include "Shader.h" #include "Utils.h" #include "Camera.h" #include "SceneManager.h" #include "FileSystem.h" #include "File.h" #include "Layer.h" #include "Cache.h" namespace ouzel { namespace scene { std::shared_ptr<Sprite> Sprite::createFromFile(const std::string& filename, bool mipmaps) { std::shared_ptr<Sprite> result = std::make_shared<Sprite>(); if (!result->initFromFile(filename, mipmaps)) { result.reset(); } return result; } Sprite::Sprite() { updateCallback = std::make_shared<UpdateCallback>(); updateCallback->callback = std::bind(&Sprite::update, this, std::placeholders::_1); } Sprite::~Sprite() { sharedEngine->unscheduleUpdate(updateCallback); } bool Sprite::initFromFile(const std::string& filename, bool mipmaps) { frames.clear(); boundingBox.reset(); frames = sharedEngine->getCache()->getSpriteFrames(filename, mipmaps); for (const SpriteFramePtr& frame : frames) { boundingBox.insertPoint(frame->getRectangle().bottomLeft()); boundingBox.insertPoint(frame->getRectangle().topRight()); if (frame->getRectangle().width > size.width) { size.width = frame->getRectangle().width; } if (frame->getRectangle().height > size.height) { size.height = frame->getRectangle().height; } } blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); if (!blendState) { return false; } shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); if (!shader) { return false; } return true; } void Sprite::update(float delta) { if (playing) { timeSinceLastFrame += delta; while (timeSinceLastFrame > frameInterval) { timeSinceLastFrame -= frameInterval; currentFrame++; if (repeat && currentFrame >= frames.size()) { currentFrame = 0; } else if (!repeat && currentFrame >= frames.size() - 1) { currentFrame = static_cast<uint32_t>(frames.size() - 1); playing = false; sharedEngine->unscheduleUpdate(updateCallback); } } } } void Sprite::draw(const Matrix4& projectionMatrix, const Matrix4& transformMatrix, const graphics::Color& drawColor) { Drawable::draw(projectionMatrix, transformMatrix, drawColor); if (currentFrame < frames.size()) { sharedEngine->getRenderer()->activateBlendState(blendState); sharedEngine->getRenderer()->activateShader(shader); Matrix4 modelViewProj = projectionMatrix * transformMatrix; float colorVector[] = { drawColor.getR(), drawColor.getG(), drawColor.getB(), drawColor.getA() }; shader->setVertexShaderConstant(0, sizeof(Matrix4), 1, modelViewProj.m); shader->setPixelShaderConstant(0, sizeof(colorVector), 1, colorVector); sharedEngine->getRenderer()->activateTexture(frames[currentFrame]->getRexture(), 0); sharedEngine->getRenderer()->drawMeshBuffer(frames[currentFrame]->getMeshBuffer()); } } void Sprite::setShader(const graphics::ShaderPtr& newShader) { shader = newShader; } void Sprite::play(bool pRepeat, float newFrameInterval) { if (newFrameInterval == 0.0f) { playing = false; return; } repeat = pRepeat; frameInterval = newFrameInterval; if (!playing && frames.size() > 1) { playing = true; if (currentFrame >= frames.size() - 1) { currentFrame = 0; timeSinceLastFrame = 0.0f; } sharedEngine->scheduleUpdate(updateCallback); } } void Sprite::stop(bool resetAnimation) { if (playing) { playing = false; sharedEngine->unscheduleUpdate(updateCallback); } if (resetAnimation) { reset(); } } void Sprite::reset() { playing = false; currentFrame = 0; timeSinceLastFrame = 0.0f; } } // namespace scene } // namespace ouzel <commit_msg>Simplify sprite update code<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <rapidjson/rapidjson.h> #include <rapidjson/filereadstream.h> #include <rapidjson/document.h> #include "Sprite.h" #include "CompileConfig.h" #include "Engine.h" #include "Renderer.h" #include "Texture.h" #include "Shader.h" #include "Utils.h" #include "Camera.h" #include "SceneManager.h" #include "FileSystem.h" #include "File.h" #include "Layer.h" #include "Cache.h" namespace ouzel { namespace scene { std::shared_ptr<Sprite> Sprite::createFromFile(const std::string& filename, bool mipmaps) { std::shared_ptr<Sprite> result = std::make_shared<Sprite>(); if (!result->initFromFile(filename, mipmaps)) { result.reset(); } return result; } Sprite::Sprite() { updateCallback = std::make_shared<UpdateCallback>(); updateCallback->callback = std::bind(&Sprite::update, this, std::placeholders::_1); } Sprite::~Sprite() { sharedEngine->unscheduleUpdate(updateCallback); } bool Sprite::initFromFile(const std::string& filename, bool mipmaps) { frames.clear(); boundingBox.reset(); frames = sharedEngine->getCache()->getSpriteFrames(filename, mipmaps); for (const SpriteFramePtr& frame : frames) { boundingBox.insertPoint(frame->getRectangle().bottomLeft()); boundingBox.insertPoint(frame->getRectangle().topRight()); if (frame->getRectangle().width > size.width) { size.width = frame->getRectangle().width; } if (frame->getRectangle().height > size.height) { size.height = frame->getRectangle().height; } } blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); if (!blendState) { return false; } shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); if (!shader) { return false; } return true; } void Sprite::update(float delta) { if (playing) { timeSinceLastFrame += delta; while (timeSinceLastFrame > frameInterval) { timeSinceLastFrame -= frameInterval; currentFrame++; if (currentFrame >= frames.size()) { if (repeat) { currentFrame = 0; } else { currentFrame = static_cast<uint32_t>(frames.size() - 1); playing = false; sharedEngine->unscheduleUpdate(updateCallback); } } } } } void Sprite::draw(const Matrix4& projectionMatrix, const Matrix4& transformMatrix, const graphics::Color& drawColor) { Drawable::draw(projectionMatrix, transformMatrix, drawColor); if (currentFrame < frames.size()) { sharedEngine->getRenderer()->activateBlendState(blendState); sharedEngine->getRenderer()->activateShader(shader); Matrix4 modelViewProj = projectionMatrix * transformMatrix; float colorVector[] = { drawColor.getR(), drawColor.getG(), drawColor.getB(), drawColor.getA() }; shader->setVertexShaderConstant(0, sizeof(Matrix4), 1, modelViewProj.m); shader->setPixelShaderConstant(0, sizeof(colorVector), 1, colorVector); sharedEngine->getRenderer()->activateTexture(frames[currentFrame]->getRexture(), 0); sharedEngine->getRenderer()->drawMeshBuffer(frames[currentFrame]->getMeshBuffer()); } } void Sprite::setShader(const graphics::ShaderPtr& newShader) { shader = newShader; } void Sprite::play(bool pRepeat, float newFrameInterval) { if (newFrameInterval == 0.0f) { playing = false; return; } repeat = pRepeat; frameInterval = newFrameInterval; if (!playing && frames.size() > 1) { playing = true; if (currentFrame >= frames.size() - 1) { currentFrame = 0; timeSinceLastFrame = 0.0f; } sharedEngine->scheduleUpdate(updateCallback); } } void Sprite::stop(bool resetAnimation) { if (playing) { playing = false; sharedEngine->unscheduleUpdate(updateCallback); } if (resetAnimation) { reset(); } } void Sprite::reset() { playing = false; currentFrame = 0; timeSinceLastFrame = 0.0f; } } // namespace scene } // namespace ouzel <|endoftext|>
<commit_before>#include "athena/VectorWriter.hpp" #include <cstdio> #include <cstring> #include <vector> #include <iostream> namespace athena::io { void VectorWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError("Position outside stream bounds"); setError(); return; } if ((atUint64)position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError("Position outside stream bounds"); setError(); return; } if (m_position + position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position += position; break; case SeekOrigin::End: if (((atInt64)m_data.size() - position) < 0) { atError("Position outside stream bounds"); setError(); return; } if ((atUint64)position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position = m_data.size() - position; break; } } void VectorWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError("data cannnot be NULL"); setError(); return; } if (m_position < m_data.size()) { size_t delta = std::min(m_data.size() - m_position, length); memmove(reinterpret_cast<atInt8*>(&m_data[m_position]), data, delta); data += delta; length -= delta; m_position += delta; } if (length != 0) { size_t insertPos = m_data.size(); m_data.resize(insertPos + length); memmove(reinterpret_cast<atInt8*>(&m_data[insertPos]), data, length); m_position += length; } } } // Athena <commit_msg>Windows compile fix<commit_after>#include "athena/VectorWriter.hpp" #include <cstdio> #include <cstring> #include <vector> #include <iostream> #include <algorithm> namespace athena::io { void VectorWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError("Position outside stream bounds"); setError(); return; } if ((atUint64)position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError("Position outside stream bounds"); setError(); return; } if (m_position + position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position += position; break; case SeekOrigin::End: if (((atInt64)m_data.size() - position) < 0) { atError("Position outside stream bounds"); setError(); return; } if ((atUint64)position > m_data.size()) { atError("data exceeds vector size"); setError(); return; } m_position = m_data.size() - position; break; } } void VectorWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError("data cannnot be NULL"); setError(); return; } if (m_position < m_data.size()) { size_t delta = std::min(m_data.size() - m_position, length); memmove(reinterpret_cast<atInt8*>(&m_data[m_position]), data, delta); data += delta; length -= delta; m_position += delta; } if (length != 0) { size_t insertPos = m_data.size(); m_data.resize(insertPos + length); memmove(reinterpret_cast<atInt8*>(&m_data[insertPos]), data, length); m_position += length; } } } // Athena <|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 "net/base/net_errors.h" #include <winsock2.h> #include "base/logging.h" namespace net { // Map winsock error to Chromium error. Error MapSystemError(int os_error) { // There are numerous Winsock error codes, but these are the ones we thus far // find interesting. switch (os_error) { case WSAEACCES: return ERR_ACCESS_DENIED; case WSAENETDOWN: return ERR_INTERNET_DISCONNECTED; case WSAETIMEDOUT: return ERR_TIMED_OUT; case WSAECONNRESET: case WSAENETRESET: // Related to keep-alive return ERR_CONNECTION_RESET; case WSAECONNABORTED: return ERR_CONNECTION_ABORTED; case WSAECONNREFUSED: return ERR_CONNECTION_REFUSED; case WSA_IO_INCOMPLETE: case WSAEDISCON: return ERR_CONNECTION_CLOSED; case WSAEHOSTUNREACH: case WSAENETUNREACH: return ERR_ADDRESS_UNREACHABLE; case WSAEADDRNOTAVAIL: return ERR_ADDRESS_INVALID; case WSAENOTCONN: return ERR_SOCKET_NOT_CONNECTED; case WSAEAFNOSUPPORT: return ERR_ADDRESS_UNREACHABLE; case ERROR_SUCCESS: return OK; default: LOG(WARNING) << "Unknown error " << os_error << " mapped to net::ERR_FAILED"; return ERR_FAILED; } } } // namespace net <commit_msg>Map WSAEWOULDBLOCK to ERR_IO_PENDING on Windows.<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 "net/base/net_errors.h" #include <winsock2.h> #include "base/logging.h" namespace net { // Map winsock error to Chromium error. Error MapSystemError(int os_error) { // There are numerous Winsock error codes, but these are the ones we thus far // find interesting. switch (os_error) { case WSAEWOULDBLOCK: return ERR_IO_PENDING; case WSAEACCES: return ERR_ACCESS_DENIED; case WSAENETDOWN: return ERR_INTERNET_DISCONNECTED; case WSAETIMEDOUT: return ERR_TIMED_OUT; case WSAECONNRESET: case WSAENETRESET: // Related to keep-alive return ERR_CONNECTION_RESET; case WSAECONNABORTED: return ERR_CONNECTION_ABORTED; case WSAECONNREFUSED: return ERR_CONNECTION_REFUSED; case WSA_IO_INCOMPLETE: case WSAEDISCON: return ERR_CONNECTION_CLOSED; case WSAEHOSTUNREACH: case WSAENETUNREACH: return ERR_ADDRESS_UNREACHABLE; case WSAEADDRNOTAVAIL: return ERR_ADDRESS_INVALID; case WSAENOTCONN: return ERR_SOCKET_NOT_CONNECTED; case WSAEAFNOSUPPORT: return ERR_ADDRESS_UNREACHABLE; case ERROR_SUCCESS: return OK; default: LOG(WARNING) << "Unknown error " << os_error << " mapped to net::ERR_FAILED"; return ERR_FAILED; } } } // namespace net <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CanonicalType.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/Type.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Overload.h" #include "clang/Sema/Sema.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Module.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/raw_ostream.h" #include <iostream> #include <sstream> namespace { ///\brief The allocation starts with this layout; it is followed by the /// value's object at m_Payload. This class does not inherit from /// llvm::RefCountedBase because deallocation cannot use this type but must /// free the character array. class AllocatedValue { public: typedef void (*DtorFunc_t)(void*); private: ///\brief The reference count - once 0, this object will be deallocated. mutable unsigned m_RefCnt; ///\brief The destructor function. DtorFunc_t m_DtorFunc; ///\brief The size of the allocation (for arrays) unsigned long m_AllocSize; ///\brief The number of elements in the array unsigned long m_NElements; ///\brief The start of the allocation. char m_Payload[1]; static DtorFunc_t PtrToFunc(void* ptr) { union { void* m_Ptr; DtorFunc_t m_Func; }; m_Ptr = ptr; return m_Func; } public: ///\brief Initialize the storage management part of the allocated object. /// The allocator is referencing it, thus initialize m_RefCnt with 1. ///\param [in] dtorFunc - the function to be called before deallocation. AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements): m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize), m_NElements(nElements) {} char* getPayload() { return m_Payload; } static unsigned getPayloadOffset() { static const AllocatedValue Dummy(0,0,0); return Dummy.m_Payload - (const char*)&Dummy; } static AllocatedValue* getFromPayload(void* payload) { return reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset()); } void Retain() { ++m_RefCnt; } ///\brief This object must be allocated as a char array. Deallocate it as /// such. void Release() { assert (m_RefCnt > 0 && "Reference count is already zero."); if (--m_RefCnt == 0) { if (m_DtorFunc) { char* payload = getPayload(); for (size_t el = 0; el < m_NElements; ++el) (*m_DtorFunc)(payload + el * m_AllocSize / m_NElements); } delete [] (char*)this; } } }; } namespace cling { Value::Value(const Value& other): m_Storage(other.m_Storage), m_StorageType(other.m_StorageType), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { if (other.needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); } Value::Value(clang::QualType clangTy, Interpreter& Interp): m_StorageType(determineStorageType(clangTy)), m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) { if (needsManagedAllocation()) ManagedAllocate(); } Value& Value::operator =(const Value& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Retain new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_StorageType = other.m_StorageType; m_Interpreter = other.m_Interpreter; if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); return *this; } Value& Value::operator =(Value&& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Move new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_StorageType = other.m_StorageType; m_Interpreter = other.m_Interpreter; // Invalidate other so it will not release. other.m_StorageType = kUnsupportedType; return *this; } Value::~Value() { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); } clang::QualType Value::getType() const { return clang::QualType::getFromOpaquePtr(m_Type); } clang::ASTContext& Value::getASTContext() const { return m_Interpreter->getCI()->getASTContext(); } bool Value::isValid() const { return !getType().isNull(); } bool Value::isVoid() const { const clang::ASTContext& Ctx = getASTContext(); return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy); } unsigned long Value::GetNumberOfElements() const { if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(getType())) { llvm::APInt arrSize(sizeof(unsigned long)*8, 1); do { arrSize *= ArrTy->getSize(); ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType() .getTypePtr()); } while (ArrTy); return (unsigned long)arrSize.getZExtValue(); } return 1; } Value::EStorageType Value::determineStorageType(clang::QualType QT) { const clang::Type* desugCanon = QT.getCanonicalType().getTypePtr(); if (desugCanon->isSignedIntegerOrEnumerationType()) return kSignedIntegerOrEnumerationType; else if (desugCanon->isUnsignedIntegerOrEnumerationType()) return kUnsignedIntegerOrEnumerationType; else if (desugCanon->isRealFloatingType()) { const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>(); if (BT->getKind() == clang::BuiltinType::Double) return kDoubleType; else if (BT->getKind() == clang::BuiltinType::Float) return kFloatType; else if (BT->getKind() == clang::BuiltinType::LongDouble) return kLongDoubleType; } else if (desugCanon->isPointerType() || desugCanon->isObjectType() || desugCanon->isReferenceType()) { if (desugCanon->isRecordType() || desugCanon->isConstantArrayType() || desugCanon->isMemberPointerType()) return kManagedAllocation; return kPointerType; } return kUnsupportedType; } void Value::ManagedAllocate() { assert(needsManagedAllocation() && "Does not need managed allocation"); void* dtorFunc = 0; clang::QualType DtorType = getType(); // For arrays we destruct the elements. if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) { DtorType = ArrTy->getElementType(); } if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>()) dtorFunc = m_Interpreter->compileDtorCallFor(RTy->getDecl()); const clang::ASTContext& ctx = getASTContext(); unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity(); char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize]; AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize, GetNumberOfElements()); m_Storage.m_Ptr = allocVal->getPayload(); } void Value::AssertOnUnsupportedTypeCast() const { assert("unsupported type in Value, cannot cast simplistically!" && 0); } namespace valuePrinterInternal { std::string printTypeInternal(const Value& V); std::string printValueInternal(const Value& V); } // end namespace valuePrinterInternal void Value::print(llvm::raw_ostream& Out) const { // Get the default type string representation std::string typeStr = cling::valuePrinterInternal::printTypeInternal(*this); // Get the value string representation, by printValue() method overloading std::string valueStr = cling::valuePrinterInternal::printValueInternal(*this); // Print the type and the value: Out << typeStr + " " + valueStr << "\n"; } void Value::dump() const { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). // Alternatively we could use llvm::errs() std::unique_ptr<llvm::raw_ostream> Out; Out.reset(new llvm::raw_os_ostream(std::cout)); print(*Out.get()); } } // end namespace cling <commit_msg>Remove useless heap allocation in Value::dump.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CanonicalType.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/Type.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Overload.h" #include "clang/Sema/Sema.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Module.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/raw_ostream.h" #include <iostream> #include <sstream> namespace { ///\brief The allocation starts with this layout; it is followed by the /// value's object at m_Payload. This class does not inherit from /// llvm::RefCountedBase because deallocation cannot use this type but must /// free the character array. class AllocatedValue { public: typedef void (*DtorFunc_t)(void*); private: ///\brief The reference count - once 0, this object will be deallocated. mutable unsigned m_RefCnt; ///\brief The destructor function. DtorFunc_t m_DtorFunc; ///\brief The size of the allocation (for arrays) unsigned long m_AllocSize; ///\brief The number of elements in the array unsigned long m_NElements; ///\brief The start of the allocation. char m_Payload[1]; static DtorFunc_t PtrToFunc(void* ptr) { union { void* m_Ptr; DtorFunc_t m_Func; }; m_Ptr = ptr; return m_Func; } public: ///\brief Initialize the storage management part of the allocated object. /// The allocator is referencing it, thus initialize m_RefCnt with 1. ///\param [in] dtorFunc - the function to be called before deallocation. AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements): m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize), m_NElements(nElements) {} char* getPayload() { return m_Payload; } static unsigned getPayloadOffset() { static const AllocatedValue Dummy(0,0,0); return Dummy.m_Payload - (const char*)&Dummy; } static AllocatedValue* getFromPayload(void* payload) { return reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset()); } void Retain() { ++m_RefCnt; } ///\brief This object must be allocated as a char array. Deallocate it as /// such. void Release() { assert (m_RefCnt > 0 && "Reference count is already zero."); if (--m_RefCnt == 0) { if (m_DtorFunc) { char* payload = getPayload(); for (size_t el = 0; el < m_NElements; ++el) (*m_DtorFunc)(payload + el * m_AllocSize / m_NElements); } delete [] (char*)this; } } }; } namespace cling { Value::Value(const Value& other): m_Storage(other.m_Storage), m_StorageType(other.m_StorageType), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { if (other.needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); } Value::Value(clang::QualType clangTy, Interpreter& Interp): m_StorageType(determineStorageType(clangTy)), m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) { if (needsManagedAllocation()) ManagedAllocate(); } Value& Value::operator =(const Value& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Retain new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_StorageType = other.m_StorageType; m_Interpreter = other.m_Interpreter; if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); return *this; } Value& Value::operator =(Value&& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Move new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_StorageType = other.m_StorageType; m_Interpreter = other.m_Interpreter; // Invalidate other so it will not release. other.m_StorageType = kUnsupportedType; return *this; } Value::~Value() { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); } clang::QualType Value::getType() const { return clang::QualType::getFromOpaquePtr(m_Type); } clang::ASTContext& Value::getASTContext() const { return m_Interpreter->getCI()->getASTContext(); } bool Value::isValid() const { return !getType().isNull(); } bool Value::isVoid() const { const clang::ASTContext& Ctx = getASTContext(); return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy); } unsigned long Value::GetNumberOfElements() const { if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(getType())) { llvm::APInt arrSize(sizeof(unsigned long)*8, 1); do { arrSize *= ArrTy->getSize(); ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType() .getTypePtr()); } while (ArrTy); return (unsigned long)arrSize.getZExtValue(); } return 1; } Value::EStorageType Value::determineStorageType(clang::QualType QT) { const clang::Type* desugCanon = QT.getCanonicalType().getTypePtr(); if (desugCanon->isSignedIntegerOrEnumerationType()) return kSignedIntegerOrEnumerationType; else if (desugCanon->isUnsignedIntegerOrEnumerationType()) return kUnsignedIntegerOrEnumerationType; else if (desugCanon->isRealFloatingType()) { const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>(); if (BT->getKind() == clang::BuiltinType::Double) return kDoubleType; else if (BT->getKind() == clang::BuiltinType::Float) return kFloatType; else if (BT->getKind() == clang::BuiltinType::LongDouble) return kLongDoubleType; } else if (desugCanon->isPointerType() || desugCanon->isObjectType() || desugCanon->isReferenceType()) { if (desugCanon->isRecordType() || desugCanon->isConstantArrayType() || desugCanon->isMemberPointerType()) return kManagedAllocation; return kPointerType; } return kUnsupportedType; } void Value::ManagedAllocate() { assert(needsManagedAllocation() && "Does not need managed allocation"); void* dtorFunc = 0; clang::QualType DtorType = getType(); // For arrays we destruct the elements. if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) { DtorType = ArrTy->getElementType(); } if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>()) dtorFunc = m_Interpreter->compileDtorCallFor(RTy->getDecl()); const clang::ASTContext& ctx = getASTContext(); unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity(); char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize]; AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize, GetNumberOfElements()); m_Storage.m_Ptr = allocVal->getPayload(); } void Value::AssertOnUnsupportedTypeCast() const { assert("unsupported type in Value, cannot cast simplistically!" && 0); } namespace valuePrinterInternal { std::string printTypeInternal(const Value& V); std::string printValueInternal(const Value& V); } // end namespace valuePrinterInternal void Value::print(llvm::raw_ostream& Out) const { // Get the default type string representation std::string typeStr = cling::valuePrinterInternal::printTypeInternal(*this); // Get the value string representation, by printValue() method overloading std::string valueStr = cling::valuePrinterInternal::printValueInternal(*this); // Print the type and the value: Out << typeStr + " " + valueStr << "\n"; } void Value::dump() const { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). llvm::raw_os_ostream Out(std::cout); print(Out); } } // end namespace cling <|endoftext|>
<commit_before>//filename: Balanced.cpp #include "StackType.h" #include <iostream> using namespace std; bool IsOpen(char symbol); bool IsClosed(char symbol); bool Matches(char symbol, char openSymbol); int main() { char symbol; StackType stack; bool balanced = true; char openSymbol; cout << "Enter an expression and press return." << endl; cin.get(symbol); while (symbol != '\n' && balanced) { if (IsOpen(symbol)) stack.Push(symbol); else if (IsClosed(symbol)) { if (stack.IsEmpty()) balanced = false; else { openSymbol = stack.Top(); stack.Pop(); balanced = Matches(symbol, openSymbol); } } cin.get(symbol); } if (balanced) cout << "Expression is well formed." << endl; else cout << "Expression is not well formed." << endl; return 0; } bool IsOpen(char symbol) { if (symbol == '(' || symbol == '{' || symbol == '[') return true; else return false; } bool IsClosed(char symbol) { if (symbol == ')' || symbol == '}' || symbol == ']') return true; else return false; } bool Matches(char symbol, char openSymbol) { return ((openSymbol == '(' && symbol == ')') || (openSymbol == '{' && symbol == '}') || (openSymbol == '[' && symbol == ']')); } <commit_msg>Update Balanced.cpp<commit_after>//filename: Balanced.cpp #include "StackType.h" #include <iostream> using namespace std; bool IsOpen(char symbol); bool IsClosed(char symbol); bool Matches(char symbol, char openSymbol); int main() { char symbol; StackType stack; bool balanced = true; char openSymbol; cout << "Enter an expression and press return." << endl; cin.get(symbol); try{ while (symbol != '\n' && balanced) { if (IsOpen(symbol)) stack.Push(symbol); else if (IsClosed(symbol)) { if (stack.IsEmpty()) balanced = false; else { openSymbol = stack.Top(); stack.Pop(); balanced = Matches(symbol, openSymbol); } } cin.get(symbol); } if (balanced) cout << "Expression is well formed." << endl; else cout << "Expression is not well formed." << endl; } catch(FullStack) { cout << "Stack is full." << endl; } return 0; } bool IsOpen(char symbol) { if (symbol == '(' || symbol == '{' || symbol == '[') return true; else return false; } bool IsClosed(char symbol) { if (symbol == ')' || symbol == '}' || symbol == ']') return true; else return false; } bool Matches(char symbol, char openSymbol) { return ((openSymbol == '(' && symbol == ')') || (openSymbol == '{' && symbol == '}') || (openSymbol == '[' && symbol == ']')); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011 The QXmpp developers * * Author: * Olivier Goffart <ogoffart@woboq.com> * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppResultSet.h" #include "QXmppUtils.h" #include <QDomElement> #include <QDebug> static const char *ns_rsm = "http://jabber.org/protocol/rsm"; QXmppResultSetQuery::QXmppResultSetQuery() : m_index(-1) , m_max(-1) {} int QXmppResultSetQuery::max() const { return m_max; } void QXmppResultSetQuery::setMax(int max) { m_max = max; } int QXmppResultSetQuery::index() const { return m_index; } void QXmppResultSetQuery::setIndex(int index) { m_index=index; } QString QXmppResultSetQuery::before() const { return m_before; } void QXmppResultSetQuery::setBefore(const QString& before) { m_before=before; } QString QXmppResultSetQuery::after() const { return m_after; } void QXmppResultSetQuery::setAfter(const QString& after) { m_after=after; } bool QXmppResultSetQuery::isNull() const { return m_max == -1 && m_index == -1 && m_after.isNull() && m_before.isNull(); } void QXmppResultSetQuery::parse(const QDomElement& element) { QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement("set"); if (setElement.namespaceURI() == ns_rsm) { bool ok = false; m_max = setElement.firstChildElement("max").text().toInt(&ok); if (!ok) m_max = -1; m_after = setElement.firstChildElement("after").text(); m_before = setElement.firstChildElement("before").text(); m_index = setElement.firstChildElement("index").text().toInt(&ok); if (!ok) m_index = -1; } } void QXmppResultSetQuery::toXml(QXmlStreamWriter* writer) const { if (isNull()) return; writer->writeStartElement("set"); writer->writeAttribute("xmlns", ns_rsm); if (m_max >= 0) helperToXmlAddTextElement(writer, "max", QString::number(m_max)); if (!m_after.isNull()) helperToXmlAddTextElement(writer, "after", m_after); if (!m_before.isNull()) helperToXmlAddTextElement(writer, "before", m_before); if (m_index >= 0) helperToXmlAddTextElement(writer, "index", QString::number(m_index)); writer->writeEndElement(); } QXmppResultSetReply::QXmppResultSetReply() : m_count(-1) , m_index(-1) {} QString QXmppResultSetReply::first() const { return m_first; } void QXmppResultSetReply::setFirst(const QString& first) { m_first=first; } QString QXmppResultSetReply::last() const { return m_last; } void QXmppResultSetReply::setLast(const QString& last) { m_last=last; } int QXmppResultSetReply::count() const { return m_count; } void QXmppResultSetReply::setCount(int count) { m_count = count; } int QXmppResultSetReply::index() const { return m_index; } void QXmppResultSetReply::setIndex(int index) { m_index=index; } bool QXmppResultSetReply::isNull() const { return m_count == -1 && m_index == -1 && m_first.isNull() && m_last.isNull(); } void QXmppResultSetReply::parse(const QDomElement& element) { QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement("set"); if (setElement.namespaceURI() == ns_rsm) { m_count = setElement.firstChildElement("count").text().toInt(); QDomElement firstElem = setElement.firstChildElement("first"); m_first = firstElem.text(); bool ok = false; m_index = firstElem.attribute("index").toInt(&ok); if(!ok) m_index = -1; m_last = setElement.firstChildElement("last").text(); } } void QXmppResultSetReply::toXml(QXmlStreamWriter* writer) const { if (isNull()) return; writer->writeStartElement("set"); writer->writeAttribute("xmlns", ns_rsm); if (!m_first.isNull() || m_index >= 0) { writer->writeStartElement("first"); if (m_index >= 0) writer->writeAttribute("index", QString::number(m_index)); writer->writeCharacters(m_first); writer->writeEndElement(); } if (!m_last.isNull()) helperToXmlAddTextElement(writer, "last", m_last); if (m_count >= 0) helperToXmlAddTextElement(writer, "count", QString::number(m_count)); writer->writeEndElement(); } <commit_msg>add some documentation to QXmppResultSetQuery/Reply<commit_after>/* * Copyright (C) 2008-2011 The QXmpp developers * * Author: * Olivier Goffart <ogoffart@woboq.com> * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppResultSet.h" #include "QXmppUtils.h" #include <QDomElement> #include <QDebug> static const char *ns_rsm = "http://jabber.org/protocol/rsm"; QXmppResultSetQuery::QXmppResultSetQuery() : m_index(-1) , m_max(-1) {} /// Returns the maximum number of results. /// /// \note -1 means no limit, 0 means no results are wanted. /// int QXmppResultSetQuery::max() const { return m_max; } /// Sets the maximum number of results. /// /// \note -1 means no limit, 0 means no results are wanted. /// /// \param max void QXmppResultSetQuery::setMax(int max) { m_max = max; } int QXmppResultSetQuery::index() const { return m_index; } void QXmppResultSetQuery::setIndex(int index) { m_index=index; } /// Returns the UID of the first result in the next page. /// /// This is used for for paging backwards through results. QString QXmppResultSetQuery::before() const { return m_before; } /// Sets the UID of the first result in the next page. /// /// This is used for for paging backwards through results. void QXmppResultSetQuery::setBefore(const QString& before) { m_before=before; } /// Returns the UID of the last result in the previous page. /// /// This is used for for paging forwards through results. QString QXmppResultSetQuery::after() const { return m_after; } /// Sets the UID of the last result in the previous page. /// /// This is used for for paging forwards through results. void QXmppResultSetQuery::setAfter(const QString& after) { m_after=after; } bool QXmppResultSetQuery::isNull() const { return m_max == -1 && m_index == -1 && m_after.isNull() && m_before.isNull(); } void QXmppResultSetQuery::parse(const QDomElement& element) { QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement("set"); if (setElement.namespaceURI() == ns_rsm) { bool ok = false; m_max = setElement.firstChildElement("max").text().toInt(&ok); if (!ok) m_max = -1; m_after = setElement.firstChildElement("after").text(); m_before = setElement.firstChildElement("before").text(); m_index = setElement.firstChildElement("index").text().toInt(&ok); if (!ok) m_index = -1; } } void QXmppResultSetQuery::toXml(QXmlStreamWriter* writer) const { if (isNull()) return; writer->writeStartElement("set"); writer->writeAttribute("xmlns", ns_rsm); if (m_max >= 0) helperToXmlAddTextElement(writer, "max", QString::number(m_max)); if (!m_after.isNull()) helperToXmlAddTextElement(writer, "after", m_after); if (!m_before.isNull()) helperToXmlAddTextElement(writer, "before", m_before); if (m_index >= 0) helperToXmlAddTextElement(writer, "index", QString::number(m_index)); writer->writeEndElement(); } QXmppResultSetReply::QXmppResultSetReply() : m_count(-1) , m_index(-1) {} /// Returns the UID of the first result in the set. QString QXmppResultSetReply::first() const { return m_first; } /// Sets the UID of the first result in the set. void QXmppResultSetReply::setFirst(const QString& first) { m_first=first; } /// Returns the UID of the last result in the set. QString QXmppResultSetReply::last() const { return m_last; } /// Sets the UID of the last result in the set. void QXmppResultSetReply::setLast(const QString& last) { m_last=last; } /// Returns the number of items in the set. /// /// \note This may be an approximate count. int QXmppResultSetReply::count() const { return m_count; } /// Sets the number of items in the set. /// /// \note This may be an approximate count. void QXmppResultSetReply::setCount(int count) { m_count = count; } int QXmppResultSetReply::index() const { return m_index; } void QXmppResultSetReply::setIndex(int index) { m_index = index; } bool QXmppResultSetReply::isNull() const { return m_count == -1 && m_index == -1 && m_first.isNull() && m_last.isNull(); } void QXmppResultSetReply::parse(const QDomElement& element) { QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement("set"); if (setElement.namespaceURI() == ns_rsm) { m_count = setElement.firstChildElement("count").text().toInt(); QDomElement firstElem = setElement.firstChildElement("first"); m_first = firstElem.text(); bool ok = false; m_index = firstElem.attribute("index").toInt(&ok); if(!ok) m_index = -1; m_last = setElement.firstChildElement("last").text(); } } void QXmppResultSetReply::toXml(QXmlStreamWriter* writer) const { if (isNull()) return; writer->writeStartElement("set"); writer->writeAttribute("xmlns", ns_rsm); if (!m_first.isNull() || m_index >= 0) { writer->writeStartElement("first"); if (m_index >= 0) writer->writeAttribute("index", QString::number(m_index)); writer->writeCharacters(m_first); writer->writeEndElement(); } if (!m_last.isNull()) helperToXmlAddTextElement(writer, "last", m_last); if (m_count >= 0) helperToXmlAddTextElement(writer, "count", QString::number(m_count)); writer->writeEndElement(); } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" #include <map> //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { // argv[1] is the features file //// Initializations --------------------------------------------- // // M is collection of targets, sky fibers, and standard stars // each target has a priority provided by the mtl file // all targets with the same priority are collected into a class check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read input files for standards, skys and targets. // Try to read SS and SF before targets to avoid wasting time if these // smaller files can't be read. init_time_at(time,"# Read target, SS, SF files",t); MTL SStars = read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF = read_MTLfile(F.SkyFfile, F,0,1); MTL Targ = read_MTLfile(F.Targfile, F,0,0); print_time(time,"# ...read targets took :"); //combine the three input files M=Targ; printf(" Target size %d \n",M.size()); std::cout.flush(); //need to be able to match immutable target id to position in list //check for duplicates on mtl only to allow duplication with SS std::map<long long,int> invert_target; std::map<long long,int>::iterator targetid_to_idx; std::pair<std::map<long long,int>::iterator,bool> ret; for(unsigned i=0;i<M.size();++i) { ret = invert_target.insert(std::make_pair(M[i].id,i)); //check for duplicates (std::map.insert only created keys, fails on duplicate keys) if(ret.second == false ){ std::ostringstream o; o<<"Duplicate targetid "<<M[i].id<<" in MTL"; throw std::logic_error(o.str().c_str()); } } M.insert(M.end(),SStars.begin(),SStars.end()); printf(" Standard Star size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" Sky Fiber size %d \n",M.size()); init_time_at(time,"# map position in target list to immutable targetid",t); init_time_at(time,"# assign priority classes",t); F.Ngal = M.size(); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i=0;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i=0;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } print_time(time,"# ...priority list took :"); init_time_at(time,"# Start positioners",t); // fiber positioners F.Npetal = 10;//spectrometers run 0 to 9 unless pacman FP pp =read_fiber_positions(F); //order the fibers by their fiber number (fib_num) not simply order in list //need to fix spectrom (List) and fp F.Nfiber = pp.size(); //each fiber has two co-ordinates so divide by two F.Nfbp = F.Nfiber/F.Npetal;// fibers per petal = 500 print_time(time,"# ..posiioners took :"); // init_time_at(time,"# Start plates",t); //P is original list of plates Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // print_time(time,"# ..plates took :"); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# Doing kd-tree... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); // Make a plan ---------------------------------------------------- print_time(t,"# Start assignment at : "); simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); // Smooth out distribution of free fibers, and increase the number of assignments // probably should not hard wire the limits i<1, i<3 in redistribute and improve for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } init_time_at(time,"# assign SS and SF ",t); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } // Results -------------------------------------------------------*/ std::vector <int> total_used_by_class(M.priority_list.size(),0); int total_used_SS=0; int total_used_SF=0; for (int jused=0;jused<F.NUsedplate;++jused){ std::vector <int> used_by_class(M.priority_list.size(),0); int used_SS=0; int used_SF=0; int j=A.suborder[jused]; for(int k=0;k<F.Nfiber;++k){ int g=A.TF[j][k]; if(g!=-1){ if(M[g].SS){ total_used_SS++; used_SS++; } else if(M[g].SF){ used_SF++; total_used_SF++; } else{ used_by_class[M[g].priority_class]++; total_used_by_class[M[g].priority_class]++; } } } } init_time_at(time,"# count SS and SF ",t); printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,total_used_by_class[pr]); } printf("\n"); init_time_at(time,"# print fits files ",t); if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(j,F.outDir,M,P,pp,F,A); // Write output } print_time(t,"# Finished !... in"); return(0); } <commit_msg>add stdexcept<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" #include <map> #include <stdexcept> //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { // argv[1] is the features file //// Initializations --------------------------------------------- // // M is collection of targets, sky fibers, and standard stars // each target has a priority provided by the mtl file // all targets with the same priority are collected into a class check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read input files for standards, skys and targets. // Try to read SS and SF before targets to avoid wasting time if these // smaller files can't be read. init_time_at(time,"# Read target, SS, SF files",t); MTL SStars = read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF = read_MTLfile(F.SkyFfile, F,0,1); MTL Targ = read_MTLfile(F.Targfile, F,0,0); print_time(time,"# ...read targets took :"); //combine the three input files M=Targ; printf(" Target size %d \n",M.size()); std::cout.flush(); //need to be able to match immutable target id to position in list //check for duplicates on mtl only to allow duplication with SS std::map<long long,int> invert_target; std::map<long long,int>::iterator targetid_to_idx; std::pair<std::map<long long,int>::iterator,bool> ret; for(unsigned i=0;i<M.size();++i) { ret = invert_target.insert(std::make_pair(M[i].id,i)); //check for duplicates (std::map.insert only created keys, fails on duplicate keys) if(ret.second == false ){ std::ostringstream o; o<<"Duplicate targetid "<<M[i].id<<" in MTL"; throw std::logic_error(o.str().c_str()); } } M.insert(M.end(),SStars.begin(),SStars.end()); printf(" Standard Star size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" Sky Fiber size %d \n",M.size()); init_time_at(time,"# map position in target list to immutable targetid",t); init_time_at(time,"# assign priority classes",t); F.Ngal = M.size(); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i=0;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i=0;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } print_time(time,"# ...priority list took :"); init_time_at(time,"# Start positioners",t); // fiber positioners F.Npetal = 10;//spectrometers run 0 to 9 unless pacman FP pp =read_fiber_positions(F); //order the fibers by their fiber number (fib_num) not simply order in list //need to fix spectrom (List) and fp F.Nfiber = pp.size(); //each fiber has two co-ordinates so divide by two F.Nfbp = F.Nfiber/F.Npetal;// fibers per petal = 500 print_time(time,"# ..posiioners took :"); // init_time_at(time,"# Start plates",t); //P is original list of plates Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // print_time(time,"# ..plates took :"); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# Doing kd-tree... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); // Make a plan ---------------------------------------------------- print_time(t,"# Start assignment at : "); simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); // Smooth out distribution of free fibers, and increase the number of assignments // probably should not hard wire the limits i<1, i<3 in redistribute and improve for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } init_time_at(time,"# assign SS and SF ",t); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } // Results -------------------------------------------------------*/ std::vector <int> total_used_by_class(M.priority_list.size(),0); int total_used_SS=0; int total_used_SF=0; for (int jused=0;jused<F.NUsedplate;++jused){ std::vector <int> used_by_class(M.priority_list.size(),0); int used_SS=0; int used_SF=0; int j=A.suborder[jused]; for(int k=0;k<F.Nfiber;++k){ int g=A.TF[j][k]; if(g!=-1){ if(M[g].SS){ total_used_SS++; used_SS++; } else if(M[g].SF){ used_SF++; total_used_SF++; } else{ used_by_class[M[g].priority_class]++; total_used_by_class[M[g].priority_class]++; } } } } init_time_at(time,"# count SS and SF ",t); printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,total_used_by_class[pr]); } printf("\n"); init_time_at(time,"# print fits files ",t); if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(j,F.outDir,M,P,pp,F,A); // Write output } print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>// Copyright 2022 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Codegen/LLVMGPU/LLVMGPUUtils.h" #include "iree/compiler/Codegen/PassDetail.h" #include "iree/compiler/Codegen/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" namespace mlir { namespace iree_compiler { constexpr unsigned kWorkgroupTileLevel = 0; constexpr int kSharedMemSizeBytes = 64 * 1024; LogicalResult verifyGPUMatmulSimtPassPipeline( Operation *op, IREE::Codegen::LoweringConfigAttr loweringConfig, IREE::Codegen::TranslationInfoAttr translationInfo, ArrayRef<int64_t> workgroupSize) { auto pipeline = IREE::Codegen::DispatchLoweringPassPipeline::LLVMGPUMatmulSimt; StringRef pipelineName = stringifyEnum(pipeline); if (workgroupSize.empty()) { return op->emitOpError("expected workgroup size for GPU pipelines"); } if (!isa<linalg::MatmulOp, linalg::BatchMatmulOp>(op)) { return success(); // Only verify batched and unbatched matmul. } Type inputType = op->getOperand(0).getType(); SmallVector<int64_t> firstLevelTileSizes = loweringConfig.getTileSizeVals(kWorkgroupTileLevel); if (linalg::BatchMatmulOp batchMatmulOp = dyn_cast<linalg::BatchMatmulOp>(op)) { // First tile dimensions should be 1 for batched, use remaining dimensions // for comparisons. if (firstLevelTileSizes[0] != 1) { op->emitError("Received first tile dimension of ") << firstLevelTileSizes[0] << " instead of 1 for " << pipelineName; } firstLevelTileSizes = {firstLevelTileSizes[1], firstLevelTileSizes[2], firstLevelTileSizes[3]}; } // Verify the total workgroup size is <= 1024 int64_t totalWorkgroupSize = workgroupSize[0] * workgroupSize[1] * workgroupSize[2]; if (totalWorkgroupSize > 1024) { return op->emitOpError("expected workgroup size to be <=1024 for ") << pipelineName << ", got " << totalWorkgroupSize; } // Verify the workgroup.z component should always be 1 if (workgroupSize[2] != 1) { return op->emitOpError("expected workgroup z component to be 1 for ") << pipelineName << ", got " << workgroupSize[2]; } // Verify shared memory usage of operands after tiling requires <= 64Kb // combined space. unsigned bytesSize; if (MemRefType type = inputType.dyn_cast<mlir::MemRefType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else if (RankedTensorType type = inputType.dyn_cast<RankedTensorType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else if (UnrankedTensorType type = inputType.dyn_cast<UnrankedTensorType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else { // Unable to determine type, skip rest of verification. return success(); } // Input shape sizes: A [ M x K], B [ K x N] unsigned totalSharedMemSizeBytes = (firstLevelTileSizes[0] * firstLevelTileSizes[2] + firstLevelTileSizes[1] * firstLevelTileSizes[2]) * bytesSize; if (totalSharedMemSizeBytes > kSharedMemSizeBytes) { return op->emitOpError("expected shared memory usage <= 64Kb for ") << pipelineName << ", got " << totalSharedMemSizeBytes; } return success(); } LogicalResult verifyGPUMatmulTensorCorePipeline( Operation *op, IREE::Codegen::LoweringConfigAttr loweringConfig, IREE::Codegen::TranslationInfoAttr translationInfo, ArrayRef<int64_t> workgroupSize) { auto pipeline = IREE::Codegen::DispatchLoweringPassPipeline::LLVMGPUMatmulTensorCore; StringRef pipelineName = stringifyEnum(pipeline); if (workgroupSize.empty()) { return op->emitOpError("expected workgroup size for GPU pipelines"); } if (!isa<linalg::MatmulOp, linalg::BatchMatmulOp>(op)) { return success(); // Only verify batched and unbatched matmul. } Type inputType = op->getOperand(0).getType(); ArrayRef<int64_t> lhsShape = getUntiledShape(op->getOperand(0)); ArrayRef<int64_t> rhsShape = getUntiledShape(op->getOperand(1)); SmallVector<int64_t> firstLevelTileSizes = loweringConfig.getTileSizeVals(kWorkgroupTileLevel); if (linalg::BatchMatmulOp batchMatmulOp = dyn_cast<linalg::BatchMatmulOp>(op)) { // First dimension is the batch dimension. We don't check the shape batch. lhsShape = lhsShape.drop_front(1); rhsShape = rhsShape.drop_front(1); // First tile dimensions should be 1 for batched, use remaining dimensions // for comparisons. if (firstLevelTileSizes[0] != 1) { op->emitError("Received first tile dimension of ") << firstLevelTileSizes[0] << " instead of 1 for " << pipelineName; } firstLevelTileSizes = {firstLevelTileSizes[1], firstLevelTileSizes[2], firstLevelTileSizes[3]}; } // Verify the total workgroup size is <= 1024 int64_t totalWorkgroupSize = workgroupSize[0] * workgroupSize[1] * workgroupSize[2]; if (totalWorkgroupSize > 1024) { return op->emitOpError("expected workgroup size to be <=1024 for ") << pipelineName << ", got " << totalWorkgroupSize; } // Verify that the workgroup X dimension is 32 aligned if (workgroupSize[0] % 32 != 0) { return op->emitOpError("workgroup size is not 32 aligned for ") << pipelineName << ", got " << workgroupSize[0]; } // Verify the workgroup.z component should always be 1 if (workgroupSize[2] != 1) { return op->emitOpError("expected workgroup z component to be 1 for ") << pipelineName << ", got " << workgroupSize[2]; } // The second level of tiling = first level tile size divided by the // warps per workgroup size SmallVector<int64_t, 3> warpsPerWorkgroup = { workgroupSize[0] / kWarpSize, workgroupSize[1], workgroupSize[2]}; SmallVector<int64_t, 3> secondLevelTileSizes; for (int i = 0; i < 3; ++i) { secondLevelTileSizes.push_back(firstLevelTileSizes[i] / warpsPerWorkgroup[i]); } // Verify the TensorCore size divides the second level tile size SmallVector<int64_t, 3> tensorCoreSize({16, 16, 8}); if (secondLevelTileSizes[0] % tensorCoreSize[0] != 0 || secondLevelTileSizes[1] % tensorCoreSize[1] != 0 || secondLevelTileSizes[2] % tensorCoreSize[2] != 0) { return op->emitOpError( "tensorcore size doesn't factor into second level tile size " "for ") << pipelineName; } // Verify the first level tile size divides the matmul // inputs A [M x K] & B [K x N] if (lhsShape[0] % firstLevelTileSizes[0] != 0 || lhsShape[1] % firstLevelTileSizes[2] != 0) { return op->emitOpError( "lhsShape doesn't factor into first level tile size for ") << pipelineName << " [ " << lhsShape[0] << ", " << lhsShape[1] << "]"; } if (rhsShape[0] % firstLevelTileSizes[2] != 0 || rhsShape[1] % firstLevelTileSizes[1] != 0) { return op->emitOpError( "rhsShape doesn't factor into first level tile size for ") << pipelineName << " [ " << rhsShape[0] << ", " << rhsShape[1] << "]"; } // Verify shared memory usage of operands after tiling requires <= 64Kb // combined space. unsigned bytesSize; if (MemRefType type = inputType.dyn_cast<mlir::MemRefType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else if (RankedTensorType type = inputType.dyn_cast<RankedTensorType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else if (UnrankedTensorType type = inputType.dyn_cast<UnrankedTensorType>()) { bytesSize = type.getElementType().getIntOrFloatBitWidth() / 8; } else { // Unable to determine type, skip rest of verification. return success(); } // Input shape sizes: A [ M x K], B [ K x N] unsigned totalSharedMemSizeBytes = (firstLevelTileSizes[0] * firstLevelTileSizes[2] + firstLevelTileSizes[1] * firstLevelTileSizes[2]) * bytesSize; if (totalSharedMemSizeBytes > kSharedMemSizeBytes) { return op->emitOpError("expected shared memory usage <= 64Kb for ") << pipelineName << ", got " << totalSharedMemSizeBytes; } return success(); } } // namespace iree_compiler } // namespace mlir <commit_msg>thomas nit<commit_after>// Copyright 2022 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Codegen/LLVMGPU/LLVMGPUUtils.h" #include "iree/compiler/Codegen/PassDetail.h" #include "iree/compiler/Codegen/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" namespace mlir { namespace iree_compiler { constexpr unsigned kWorkgroupTileLevel = 0; constexpr int kSharedMemSizeBytes = 64 * 1024; LogicalResult verifyGPUMatmulSimtPassPipeline( Operation *op, IREE::Codegen::LoweringConfigAttr loweringConfig, IREE::Codegen::TranslationInfoAttr translationInfo, ArrayRef<int64_t> workgroupSize) { auto pipeline = IREE::Codegen::DispatchLoweringPassPipeline::LLVMGPUMatmulSimt; StringRef pipelineName = stringifyEnum(pipeline); if (workgroupSize.empty()) { return op->emitOpError("expected workgroup size for GPU pipelines"); } if (!isa<linalg::MatmulOp, linalg::BatchMatmulOp>(op)) { return success(); // Only verify batched and unbatched matmul. } Type inputType = op->getOperand(0).getType(); SmallVector<int64_t> firstLevelTileSizes = loweringConfig.getTileSizeVals(kWorkgroupTileLevel); if (linalg::BatchMatmulOp batchMatmulOp = dyn_cast<linalg::BatchMatmulOp>(op)) { // First tile dimensions should be 1 for batched, use remaining dimensions // for comparisons. if (firstLevelTileSizes[0] != 1) { op->emitError("Received first tile dimension of ") << firstLevelTileSizes[0] << " instead of 1 for " << pipelineName; } firstLevelTileSizes = {firstLevelTileSizes[1], firstLevelTileSizes[2], firstLevelTileSizes[3]}; } // Verify the total workgroup size is <= 1024 int64_t totalWorkgroupSize = workgroupSize[0] * workgroupSize[1] * workgroupSize[2]; if (totalWorkgroupSize > 1024) { return op->emitOpError("expected workgroup size to be <=1024 for ") << pipelineName << ", got " << totalWorkgroupSize; } // Verify the workgroup.z component should always be 1 if (workgroupSize[2] != 1) { return op->emitOpError("expected workgroup z component to be 1 for ") << pipelineName << ", got " << workgroupSize[2]; } // Verify shared memory usage of operands after tiling requires <= 64Kb // combined space. unsigned bytesSize = inputType.cast<ShapedType>().getElementType().getIntOrFloatBitWidth() / 8; // Input shape sizes: A [ M x K], B [ K x N] unsigned totalSharedMemSizeBytes = (firstLevelTileSizes[0] * firstLevelTileSizes[2] + firstLevelTileSizes[1] * firstLevelTileSizes[2]) * bytesSize; if (totalSharedMemSizeBytes > kSharedMemSizeBytes) { return op->emitOpError("expected shared memory usage <= 64Kb for ") << pipelineName << ", got " << totalSharedMemSizeBytes; } return success(); } LogicalResult verifyGPUMatmulTensorCorePipeline( Operation *op, IREE::Codegen::LoweringConfigAttr loweringConfig, IREE::Codegen::TranslationInfoAttr translationInfo, ArrayRef<int64_t> workgroupSize) { auto pipeline = IREE::Codegen::DispatchLoweringPassPipeline::LLVMGPUMatmulTensorCore; StringRef pipelineName = stringifyEnum(pipeline); if (workgroupSize.empty()) { return op->emitOpError("expected workgroup size for GPU pipelines"); } if (!isa<linalg::MatmulOp, linalg::BatchMatmulOp>(op)) { return success(); // Only verify batched and unbatched matmul. } Type inputType = op->getOperand(0).getType(); ArrayRef<int64_t> lhsShape = getUntiledShape(op->getOperand(0)); ArrayRef<int64_t> rhsShape = getUntiledShape(op->getOperand(1)); SmallVector<int64_t> firstLevelTileSizes = loweringConfig.getTileSizeVals(kWorkgroupTileLevel); if (linalg::BatchMatmulOp batchMatmulOp = dyn_cast<linalg::BatchMatmulOp>(op)) { // First dimension is the batch dimension. We don't check the shape batch. lhsShape = lhsShape.drop_front(1); rhsShape = rhsShape.drop_front(1); // First tile dimensions should be 1 for batched, use remaining dimensions // for comparisons. if (firstLevelTileSizes[0] != 1) { op->emitError("Received first tile dimension of ") << firstLevelTileSizes[0] << " instead of 1 for " << pipelineName; } firstLevelTileSizes = {firstLevelTileSizes[1], firstLevelTileSizes[2], firstLevelTileSizes[3]}; } // Verify the total workgroup size is <= 1024 int64_t totalWorkgroupSize = workgroupSize[0] * workgroupSize[1] * workgroupSize[2]; if (totalWorkgroupSize > 1024) { return op->emitOpError("expected workgroup size to be <=1024 for ") << pipelineName << ", got " << totalWorkgroupSize; } // Verify that the workgroup X dimension is 32 aligned if (workgroupSize[0] % 32 != 0) { return op->emitOpError("workgroup size is not 32 aligned for ") << pipelineName << ", got " << workgroupSize[0]; } // Verify the workgroup.z component should always be 1 if (workgroupSize[2] != 1) { return op->emitOpError("expected workgroup z component to be 1 for ") << pipelineName << ", got " << workgroupSize[2]; } // The second level of tiling = first level tile size divided by the // warps per workgroup size SmallVector<int64_t, 3> warpsPerWorkgroup = { workgroupSize[0] / kWarpSize, workgroupSize[1], workgroupSize[2]}; SmallVector<int64_t, 3> secondLevelTileSizes; for (int i = 0; i < 3; ++i) { secondLevelTileSizes.push_back(firstLevelTileSizes[i] / warpsPerWorkgroup[i]); } // Verify the TensorCore size divides the second level tile size SmallVector<int64_t, 3> tensorCoreSize({16, 16, 8}); if (secondLevelTileSizes[0] % tensorCoreSize[0] != 0 || secondLevelTileSizes[1] % tensorCoreSize[1] != 0 || secondLevelTileSizes[2] % tensorCoreSize[2] != 0) { return op->emitOpError( "tensorcore size doesn't factor into second level tile size " "for ") << pipelineName; } // Verify the first level tile size divides the matmul // inputs A [M x K] & B [K x N] if (lhsShape[0] % firstLevelTileSizes[0] != 0 || lhsShape[1] % firstLevelTileSizes[2] != 0) { return op->emitOpError( "lhsShape doesn't factor into first level tile size for ") << pipelineName << " [ " << lhsShape[0] << ", " << lhsShape[1] << "]"; } if (rhsShape[0] % firstLevelTileSizes[2] != 0 || rhsShape[1] % firstLevelTileSizes[1] != 0) { return op->emitOpError( "rhsShape doesn't factor into first level tile size for ") << pipelineName << " [ " << rhsShape[0] << ", " << rhsShape[1] << "]"; } // Verify shared memory usage of operands after tiling requires <= 64Kb // combined space. unsigned bytesSize = inputType.cast<ShapedType>().getElementType().getIntOrFloatBitWidth() / 8; // Input shape sizes: A [ M x K], B [ K x N] unsigned totalSharedMemSizeBytes = (firstLevelTileSizes[0] * firstLevelTileSizes[2] + firstLevelTileSizes[1] * firstLevelTileSizes[2]) * bytesSize; if (totalSharedMemSizeBytes > kSharedMemSizeBytes) { return op->emitOpError("expected shared memory usage <= 64Kb for ") << pipelineName << ", got " << totalSharedMemSizeBytes; } return success(); } } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>#include "Task.h" #include <ESP8266WiFi.h> #include "ThingSpeak.h" #include "Setting.h" #define LED_FIELD 1 #define FAN_FIELD 2 #define WATER_PUMP_FIELD 3 #define COOLER_FIELD 4 #define HEATER_FIELD 5 #define VALUE_CONTROL_FOR_DEVICE(device, controlVal, maxValOfDevice ) analogWrite( device, map(controlVal, 0, maxValOfDevice, 0, 255) ) void performTasks(int channel_ID){ Serial.println("Reading brightness, fanSpeed, heaterValue , coolerValue, waterPumpVal from ThingSpeak......\n"); int ledBrightness = ThingSpeak.readFloatField(channel_ID, LED_FIELD); int fanSpeed = ThingSpeak.readFloatField(channel_ID, FAN_FIELD); int waterPumpVal = ThingSpeak.readFloatField(channel_ID, WATER_PUMP_FIELD); int coolerVal = ThingSpeak.readFloatField(channel_ID, HEATER_FIELD); int heaterVal = ThingSpeak.readFloatField(channel_ID, COOLER_FIELD); Serial.printf("ledBrightness : %d Lux\n", ledBrightness); Serial.printf("fanSpeed : %d \n", fanSpeed); Serial.printf("waterPumpVal : %d \n", waterPumpVal); Serial.printf("coolerVal : %d \n", coolerVal); Serial.printf("heaterVal : %d \n", heaterVal); VALUE_CONTROL_FOR_DEVICE( LED , ledBrightness , 35000); //Set 35000 Lux as the max Brightness of LED VALUE_CONTROL_FOR_DEVICE( FAN , fanSpeed , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( WATER_PUMP, waterPumpVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( COOLER , coolerVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( HEATER , heaterVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing } <commit_msg>corrected wrong assigns of cooler and heater<commit_after>#include "Task.h" #include <ESP8266WiFi.h> #include "ThingSpeak.h" #include "Setting.h" #define LED_FIELD 1 #define FAN_FIELD 2 #define WATER_PUMP_FIELD 3 #define COOLER_FIELD 4 #define HEATER_FIELD 5 #define VALUE_CONTROL_FOR_DEVICE(device, controlVal, maxValOfDevice ) analogWrite( device, map(controlVal, 0, maxValOfDevice, 0, 255) ) void performTasks(int channel_ID){ Serial.println("Reading brightness, fanSpeed, heaterValue , coolerValue, waterPumpVal from ThingSpeak......\n"); int ledBrightness = ThingSpeak.readFloatField(channel_ID, LED_FIELD); int fanSpeed = ThingSpeak.readFloatField(channel_ID, FAN_FIELD); int waterPumpVal = ThingSpeak.readFloatField(channel_ID, WATER_PUMP_FIELD); int heaterVal = ThingSpeak.readFloatField(channel_ID, HEATER_FIELD); int coolerVal = ThingSpeak.readFloatField(channel_ID, COOLER_FIELD); Serial.printf("ledBrightness : %d Lux\n", ledBrightness); Serial.printf("fanSpeed : %d \n", fanSpeed); Serial.printf("waterPumpVal : %d \n", waterPumpVal); Serial.printf("coolerVal : %d \n", coolerVal); Serial.printf("heaterVal : %d \n", heaterVal); VALUE_CONTROL_FOR_DEVICE( LED , ledBrightness , 35000); //Set 35000 Lux as the max Brightness of LED VALUE_CONTROL_FOR_DEVICE( FAN , fanSpeed , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( WATER_PUMP, waterPumpVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( COOLER , coolerVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing VALUE_CONTROL_FOR_DEVICE( HEATER , heaterVal , 1); //Use 1 and 0 as On/Off, doesn't has value skecthing } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // BZFlag common header #include "common.h" #include <sys/types.h> #include <sys/stat.h> #if defined(_WIN32) # include <shlobj.h> # include <direct.h> #else # include <pwd.h> # include <dirent.h> #endif /* defined(_WIN32) */ #include "clientConfig.h" #include "version.h" #include "StateDatabase.h" #include "KeyManager.h" #include "TextUtils.h" #include "DirectoryNames.h" #include "ErrorHandler.h" std::vector<std::string> configQualityValues; std::vector<std::string> configViewValues; void initConfigData ( void ) { configQualityValues.push_back(std::string("low")); configQualityValues.push_back(std::string("medium")); configQualityValues.push_back(std::string("high")); configQualityValues.push_back(std::string("experimental")); configViewValues.push_back(std::string("normal")); configViewValues.push_back(std::string("stereo")); configViewValues.push_back(std::string("stacked")); configViewValues.push_back(std::string("three")); configViewValues.push_back(std::string("anaglyph")); configViewValues.push_back(std::string("interlaced")); } std::string getOldConfigFileName(void) { #if !defined(_WIN32) std::string name = getConfigDirName(); name += "config"; // add in hostname on UNIX if (getenv("HOST")) { name += "."; name += getenv("HOST"); } return name; #elif defined(_WIN32) /* !defined(_WIN32) */ std::string name("C:"); char dir[MAX_PATH]; ITEMIDLIST* idl; if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL , &idl))) { if (SHGetPathFromIDList(idl, dir)) { struct stat statbuf; if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0) name = dir; } IMalloc* shalloc; if (SUCCEEDED(SHGetMalloc(&shalloc))) { shalloc->Free(idl); shalloc->Release(); } } name += "\\My BZFlag Files\\2.0\\config.cfg"; return name; #endif /* !defined(_WIN32) */ } #if !defined(_WIN32) // who uses this sucker any more? static std::string getReallyOldConfigFileName() { std::string name = getConfigDirName(); name += "config"; return name; } #endif std::string getCurrentConfigFileName(void) { std::string configFile = BZ_CONFIG_FILE_NAME; std::string name = getConfigDirName(BZ_CONFIG_DIR_VERSION); name += configFile; #if !defined(_WIN32) // add in hostname on UNIX if (getenv("HOST")) { name += "."; name += getenv("HOST"); } #endif return name; } // this function will look for the config, if it's not there, // it will TRY and find an old one and copy it // so that the update function can upgrade it to the current version // the assumption is that there is a unique config per version void findConfigFile(void) { // look for the current file std::string configName = getCurrentConfigFileName(); FILE *fp = fopen(configName.c_str(), "rb"); if (fp) { // we found the current file, nothing to do, just return fclose(fp); return; } // try and find the old file std::string oldConfigName = getOldConfigFileName(); fp = fopen(oldConfigName.c_str(), "rb"); if (fp) { // there is an old config so lets copy it to the new dir and let the update take care of it. #if defined(_WIN32) fclose(fp); // make the dir if we need to std::string configDir = getConfigDirName(BZ_CONFIG_DIR_VERSION); mkdir(configDir.c_str()); // copy the old config to the new dir location with the new name CopyFile(oldConfigName.c_str(), configName.c_str(),true); #else // the other OSs should do what they need to do mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755); FILE *newFile = fopen(configName.c_str(),"wb"); if (newFile) { fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); unsigned char* temp = (unsigned char*) malloc(len); fread(temp, len, 1, fp); fwrite(temp, len, 1, newFile); free(temp); fclose(newFile); fclose(fp); } #endif } // try and find the REALLY old file // who uses this sucker any more? #if !defined(_WIN32) std::string realyOldConfigName = getReallyOldConfigFileName(); fp = fopen(realyOldConfigName.c_str(), "rb"); if (fp) { // there is an old config so lets copy it to the new dir and let the update take care of it. // apparently only linux needs this so do the magic mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755); FILE *newFile = fopen(configName.c_str(),"wb"); if (newFile) { fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); unsigned char* temp = (unsigned char*) malloc(len); fread(temp, len, 1, fp); fwrite(temp, len, 1, newFile); free(temp); fclose(newFile); fclose(fp); } } #endif } void updateConfigFile(void) { int configVersion = 0; if (BZDB.isSet("config_version")) configVersion = (int)BZDB.eval("config_version"); switch (configVersion) { case 0: // 1.10-1.12 // update from old unversioned config // roaming fixes - remove keys bound to "roam translate *" and "roam rotate *" KEYMGR.unbindCommand("roam translate left"); KEYMGR.unbindCommand("roam translate right"); KEYMGR.unbindCommand("roam translate up"); KEYMGR.unbindCommand("roam translate down"); KEYMGR.unbindCommand("roam translate forward"); KEYMGR.unbindCommand("roam translate backward"); KEYMGR.unbindCommand("roam rotate left"); KEYMGR.unbindCommand("roam rotate right"); KEYMGR.unbindCommand("roam rotate up"); KEYMGR.unbindCommand("roam rotate down"); KEYMGR.unbindCommand("roam rotate stop"); // add new default keybindings if there's no conflict // iconify BzfKeyEvent key; if (KEYMGR.stringToKeyEvent("F4", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "iconify"); // toggle console & radar if (KEYMGR.stringToKeyEvent("Q", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "toggleRadar"); if (KEYMGR.stringToKeyEvent("W", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "toggleConsole"); // controlpanel tabs - all or nothing if (KEYMGR.stringToKeyEvent("Shift+F1", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F2", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F3", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F4", key) && (KEYMGR.get(key, true) == "")) { KEYMGR.stringToKeyEvent("Shift+F1", key); KEYMGR.bind(key, true, "messagepanel all"); KEYMGR.stringToKeyEvent("Shift+F2", key); KEYMGR.bind(key, true, "messagepanel chat"); KEYMGR.stringToKeyEvent("Shift+F3", key); KEYMGR.bind(key, true, "messagepanel server"); KEYMGR.stringToKeyEvent("Shift+F4", key); KEYMGR.bind(key, true, "messagepanel misc"); } // TODO - any other breaking changes from 1.10 to 2.0 case 1: // 1.11.20 if (KEYMGR.stringToKeyEvent("Tab", key) && (KEYMGR.get(key, false) == "")) KEYMGR.bind(key, false, "jump"); case 2: // 2.0 if (KEYMGR.stringToKeyEvent("7", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "addhunt"); case 3: // Upgrade from 2.0.x to 2.4.x // Convert from email to motto // If the email is set, see if we should convert it if (BZDB.isSet("email")) { std::string email = BZDB.get("email"); // If the email is set and does not contain an @ sign, move it to motto if (!email.empty() && email.find('@') == std::string::npos) { BZDB.set("motto", email); } BZDB.unset("email"); // discard email string from before version 2.4 } if (BZDB.isSet("emailDispLen")) { BZDB.set("mottoDispLen", BZDB.get("emailDispLen")); BZDB.unset("emailDispLen"); // discard setting from before version 2.4 } if (BZDB.isSet("hideEmails")) { BZDB.setBool("hideMottos", BZDB.isTrue("hideEmails")); BZDB.unset("hideEmails"); // discard setting from before version 2.4 } // Get rid of geometry setting BZDB.unset("geometry"); // Turn off dithering (since none of our automatic performance checks turn it on anymore) BZDB.setBool("dither", false); break; case 4: // Upgrade 2.4.x to .... (Do nothing right now as this is the current version) break; default: // hm, we don't know about this one... printError(TextUtils::format("Config file is tagged version \"%d\", " "which was not expected (too new perhaps). " "Trying to load anyhow.", configVersion)); break; } // set us as the updated version configVersion = BZ_CONFIG_FILE_VERSION; BZDB.setInt("config_version", configVersion); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Properly locate the old 2.0.x configuration file on non-Windows platforms so it can be upgraded.<commit_after>/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // BZFlag common header #include "common.h" #include <sys/types.h> #include <sys/stat.h> #if defined(_WIN32) # include <shlobj.h> # include <direct.h> #else # include <pwd.h> # include <dirent.h> #endif /* defined(_WIN32) */ #include "clientConfig.h" #include "version.h" #include "StateDatabase.h" #include "KeyManager.h" #include "TextUtils.h" #include "DirectoryNames.h" #include "ErrorHandler.h" std::vector<std::string> configQualityValues; std::vector<std::string> configViewValues; void initConfigData ( void ) { configQualityValues.push_back(std::string("low")); configQualityValues.push_back(std::string("medium")); configQualityValues.push_back(std::string("high")); configQualityValues.push_back(std::string("experimental")); configViewValues.push_back(std::string("normal")); configViewValues.push_back(std::string("stereo")); configViewValues.push_back(std::string("stacked")); configViewValues.push_back(std::string("three")); configViewValues.push_back(std::string("anaglyph")); configViewValues.push_back(std::string("interlaced")); } std::string getOldConfigFileName(void) { #if !defined(_WIN32) std::string name = getConfigDirName("2.0"); name += "config.cfg"; // add in hostname on UNIX if (getenv("HOST")) { name += "."; name += getenv("HOST"); } return name; #elif defined(_WIN32) /* !defined(_WIN32) */ std::string name("C:"); char dir[MAX_PATH]; ITEMIDLIST* idl; if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL , &idl))) { if (SHGetPathFromIDList(idl, dir)) { struct stat statbuf; if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0) name = dir; } IMalloc* shalloc; if (SUCCEEDED(SHGetMalloc(&shalloc))) { shalloc->Free(idl); shalloc->Release(); } } name += "\\My BZFlag Files\\2.0\\config.cfg"; return name; #endif /* !defined(_WIN32) */ } #if !defined(_WIN32) // who uses this sucker any more? static std::string getReallyOldConfigFileName() { std::string name = getConfigDirName(); name += "config"; return name; } #endif std::string getCurrentConfigFileName(void) { std::string configFile = BZ_CONFIG_FILE_NAME; std::string name = getConfigDirName(BZ_CONFIG_DIR_VERSION); name += configFile; #if !defined(_WIN32) // add in hostname on UNIX if (getenv("HOST")) { name += "."; name += getenv("HOST"); } #endif return name; } // this function will look for the config, if it's not there, // it will TRY and find an old one and copy it // so that the update function can upgrade it to the current version // the assumption is that there is a unique config per version void findConfigFile(void) { // look for the current file std::string configName = getCurrentConfigFileName(); FILE *fp = fopen(configName.c_str(), "rb"); if (fp) { // we found the current file, nothing to do, just return fclose(fp); return; } // try and find the old file std::string oldConfigName = getOldConfigFileName(); fp = fopen(oldConfigName.c_str(), "rb"); if (fp) { // there is an old config so lets copy it to the new dir and let the update take care of it. #if defined(_WIN32) fclose(fp); // make the dir if we need to std::string configDir = getConfigDirName(BZ_CONFIG_DIR_VERSION); mkdir(configDir.c_str()); // copy the old config to the new dir location with the new name CopyFile(oldConfigName.c_str(), configName.c_str(),true); #else // the other OSs should do what they need to do mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755); FILE *newFile = fopen(configName.c_str(),"wb"); if (newFile) { fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); unsigned char* temp = (unsigned char*) malloc(len); fread(temp, len, 1, fp); fwrite(temp, len, 1, newFile); free(temp); fclose(newFile); fclose(fp); } #endif } // try and find the REALLY old file // who uses this sucker any more? #if !defined(_WIN32) std::string realyOldConfigName = getReallyOldConfigFileName(); fp = fopen(realyOldConfigName.c_str(), "rb"); if (fp) { // there is an old config so lets copy it to the new dir and let the update take care of it. // apparently only linux needs this so do the magic mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755); FILE *newFile = fopen(configName.c_str(),"wb"); if (newFile) { fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); unsigned char* temp = (unsigned char*) malloc(len); fread(temp, len, 1, fp); fwrite(temp, len, 1, newFile); free(temp); fclose(newFile); fclose(fp); } } #endif } void updateConfigFile(void) { int configVersion = 0; if (BZDB.isSet("config_version")) configVersion = (int)BZDB.eval("config_version"); switch (configVersion) { case 0: // 1.10-1.12 // update from old unversioned config // roaming fixes - remove keys bound to "roam translate *" and "roam rotate *" KEYMGR.unbindCommand("roam translate left"); KEYMGR.unbindCommand("roam translate right"); KEYMGR.unbindCommand("roam translate up"); KEYMGR.unbindCommand("roam translate down"); KEYMGR.unbindCommand("roam translate forward"); KEYMGR.unbindCommand("roam translate backward"); KEYMGR.unbindCommand("roam rotate left"); KEYMGR.unbindCommand("roam rotate right"); KEYMGR.unbindCommand("roam rotate up"); KEYMGR.unbindCommand("roam rotate down"); KEYMGR.unbindCommand("roam rotate stop"); // add new default keybindings if there's no conflict // iconify BzfKeyEvent key; if (KEYMGR.stringToKeyEvent("F4", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "iconify"); // toggle console & radar if (KEYMGR.stringToKeyEvent("Q", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "toggleRadar"); if (KEYMGR.stringToKeyEvent("W", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "toggleConsole"); // controlpanel tabs - all or nothing if (KEYMGR.stringToKeyEvent("Shift+F1", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F2", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F3", key) && (KEYMGR.get(key, true) == "") && KEYMGR.stringToKeyEvent("Shift+F4", key) && (KEYMGR.get(key, true) == "")) { KEYMGR.stringToKeyEvent("Shift+F1", key); KEYMGR.bind(key, true, "messagepanel all"); KEYMGR.stringToKeyEvent("Shift+F2", key); KEYMGR.bind(key, true, "messagepanel chat"); KEYMGR.stringToKeyEvent("Shift+F3", key); KEYMGR.bind(key, true, "messagepanel server"); KEYMGR.stringToKeyEvent("Shift+F4", key); KEYMGR.bind(key, true, "messagepanel misc"); } // TODO - any other breaking changes from 1.10 to 2.0 case 1: // 1.11.20 if (KEYMGR.stringToKeyEvent("Tab", key) && (KEYMGR.get(key, false) == "")) KEYMGR.bind(key, false, "jump"); case 2: // 2.0 if (KEYMGR.stringToKeyEvent("7", key) && (KEYMGR.get(key, true) == "")) KEYMGR.bind(key, true, "addhunt"); case 3: // Upgrade from 2.0.x to 2.4.x // Convert from email to motto // If the email is set, see if we should convert it if (BZDB.isSet("email")) { std::string email = BZDB.get("email"); // If the email is set and does not contain an @ sign, move it to motto if (!email.empty() && email.find('@') == std::string::npos) { BZDB.set("motto", email); } BZDB.unset("email"); // discard email string from before version 2.4 } if (BZDB.isSet("emailDispLen")) { BZDB.set("mottoDispLen", BZDB.get("emailDispLen")); BZDB.unset("emailDispLen"); // discard setting from before version 2.4 } if (BZDB.isSet("hideEmails")) { BZDB.setBool("hideMottos", BZDB.isTrue("hideEmails")); BZDB.unset("hideEmails"); // discard setting from before version 2.4 } // Get rid of geometry setting BZDB.unset("geometry"); // Turn off dithering (since none of our automatic performance checks turn it on anymore) BZDB.setBool("dither", false); break; case 4: // Upgrade 2.4.x to .... (Do nothing right now as this is the current version) break; default: // hm, we don't know about this one... printError(TextUtils::format("Config file is tagged version \"%d\", " "which was not expected (too new perhaps). " "Trying to load anyhow.", configVersion)); break; } // set us as the updated version configVersion = BZ_CONFIG_FILE_VERSION; BZDB.setInt("config_version", configVersion); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================ * * Filename:g3log.hpp Framework for Logging and Design By Contract * Created: 2011 by Kjell Hedström * * PUBLIC DOMAIN and Not copywrited since it was built on public-domain software and influenced * at least in "spirit" from the following sources * 1. kjellkod.cc ;) * 2. Dr.Dobbs, Petru Marginean: http://drdobbs.com/article/printableArticle.jhtml?articleId=201804215&dept_url=/caddpp/ * 3. Dr.Dobbs, Michael Schulze: http://drdobbs.com/article/printableArticle.jhtml?articleId=225700666&dept_url=/cpp/ * 4. Google 'glog': http://google-glog.googlecode.com/svn/trunk/doc/glog.html * 5. Various Q&A at StackOverflow * ********************************************* */ #pragma once #include "g3log/loglevels.hpp" #include "g3log/logcapture.hpp" #include "g3log/logmessage.hpp" #include "g3log/generated_definitions.hpp" #include <string> #include <functional> #if !(defined(__PRETTY_FUNCTION__)) #define __PRETTY_FUNCTION__ __FUNCTION__ #endif // thread_local doesn't exist before VS2013 // it exists on VS2015 #if !(defined(thread_local)) && defined(_MSC_VER) && _MSC_VER < 1900 #define thread_local __declspec(thread) #endif /** namespace for LOG() and CHECK() frameworks * History lesson: Why the names 'g3' and 'g3log'?: * The framework was made in my own free time as PUBLIC DOMAIN but the * first commercial project to use it used 'g3' as an internal denominator for * the current project. g3 as in 'generation 2'. I decided to keep the g3 and g3log names * to give credit to the people in that project (you know who you are :) and I guess also * for 'sentimental' reasons. That a big influence was Google's glog is just a happy * coincidence or subconscious choice. Either way g3log became the name for this logger. * * --- Thanks for a great 2011 and good luck with 'g3' --- KjellKod */ namespace g3 { class LogWorker; struct LogMessage; struct FatalMessage; /** Should be called at very first startup of the software with \ref g3LogWorker * pointer. Ownership of the \ref g3LogWorker is the responsibility of the caller */ void initializeLogging(LogWorker *logger); /** setFatalPreLoggingHook() provides an optional extra step before the fatalExitHandler is called * * Set a function-hook before a fatal message will be sent to the logger * i.e. this is a great place to put a break point, either in your debugger * or programatically to catch LOG(FATAL), CHECK(...) or an OS fatal event (exception or signal) * This will be reset to default (does nothing) at initializeLogging(...); * * Example usage: * Windows: g3::setFatalPreLoggingHook([]{__debugbreak();}); // remember #include <intrin.h> * WARNING: '__debugbreak()' when not running in Debug in your Visual Studio IDE will likely * trigger a recursive crash if used here. It should only be used when debugging * in your Visual Studio IDE. Recursive crashes are handled but are unnecessary. * * Linux: g3::setFatalPreLoggingHook([]{ raise(SIGTRAP); }); */ void setFatalPreLoggingHook(std::function<void(void)> pre_fatal_hook); /** If the @ref setFatalPreLoggingHook is not enough and full fatal exit handling is needed then * use "setFatalExithandler". Please see g3log.cpp and crashhandler_windows.cpp or crashhandler_unix for * example of restoring signal and exception handlers, flushing the log and shutting down. */ void setFatalExitHandler(std::function<void(FatalMessagePtr)> fatal_call); #ifdef G3_DYNAMIC_MAX_MESSAGE_SIZE // only_change_at_initialization namespace is for changes to be done only during initialization. More specifically // items here would be called prior to calling other parts of g3log namespace only_change_at_initialization { // Sets the MaxMessageSize to be used when capturing log messages. Currently this value is set to 2KB. Messages // Longer than this are bound to 2KB with the string "[...truncated...]" at the end. This function allows // this limit to be changed. void setMaxMessageSize(size_t max_size); } #endif /* G3_DYNAMIC_MAX_MESSAGE_SIZE */ // internal namespace is for completely internal or semi-hidden from the g3 namespace due to that it is unlikely // that you will use these namespace internal { /// @returns true if logger is initialized bool isLoggingInitialized(); // Save the created LogMessage to any existing sinks void saveMessage(const char *message, const char *file, int line, const char *function, const LEVELS &level, const char *boolean_expression, int fatal_signal, const char *stack_trace); // forwards the message to all sinks void pushMessageToLogger(LogMessagePtr log_entry); // forwards a FATAL message to all sinks,. after which the g3logworker // will trigger crashhandler / g3::internal::exitWithDefaultSignalHandler // // By default the "fatalCall" will forward a FatalMessageptr to this function // this behavior can be changed if you set a different fatal handler through // "setFatalExitHandler" void pushFatalMessageToLogger(FatalMessagePtr message); // Saves the created FatalMessage to any existing sinks and exits with // the originating fatal signal,. or SIGABRT if it originated from a broken contract. // By default forwards to: pushFatalMessageToLogger, see "setFatalExitHandler" to override // // If you override it then you probably want to call "pushFatalMessageToLogger" after your // custom fatal handler is done. This will make sure that the fatal message the pushed // to sinks as well as shutting down the process void fatalCall(FatalMessagePtr message); // Shuts down logging. No object cleanup but further LOG(...) calls will be ignored. void shutDownLogging(); // Shutdown logging, but ONLY if the active logger corresponds to the one currently initialized bool shutDownLoggingForActiveOnly(LogWorker *active); } // internal } // g3 #define INTERNAL_LOG_MESSAGE(level) LogCapture(__FILE__, __LINE__, static_cast<const char*>(__PRETTY_FUNCTION__), level) #define INTERNAL_CONTRACT_MESSAGE(boolean_expression) \ LogCapture(__FILE__, __LINE__, __PRETTY_FUNCTION__, g3::internal::CONTRACT, boolean_expression) // LOG(level) is the API for the stream log #define LOG(level) if(!g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).stream() // 'Conditional' stream log #define LOG_IF(level, boolean_expression) \ if (false == (boolean_expression) || !g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).stream() // 'Design By Contract' stream API. For Broken Contracts: // unit testing: it will throw std::runtime_error when a contract breaks // I.R.L : it will exit the application by using fatal signal SIGABRT #define CHECK(boolean_expression) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).stream() /** For details please see this * REFERENCE: http://www.cppreference.com/wiki/io/c/printf_format * \verbatim * There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot. Code Format %[flags][width][.precision][length]specifier SPECIFIERS ---------- %c character %d signed integers %i signed integers %e scientific notation, with a lowercase “e” %E scientific notation, with a uppercase “E” %f floating point %g use %e or %f, whichever is shorter %G use %E or %f, whichever is shorter %o octal %s a string of characters %u unsigned integer %x unsigned hexadecimal, with lowercase letters %X unsigned hexadecimal, with uppercase letters %p a pointer %n the argument shall be a pointer to an integer into which is placed the number of characters written so far For flags, width, precision etc please see the above references. EXAMPLES: { LOGF(INFO, "Characters: %c %c \n", 'a', 65); LOGF(INFO, "Decimals: %d %ld\n", 1977, 650000L); // printing long LOGF(INFO, "Preceding with blanks: %10d \n", 1977); LOGF(INFO, "Preceding with zeros: %010d \n", 1977); LOGF(INFO, "Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); LOGF(INFO, "floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); LOGF(INFO, "Width trick: %*d \n", 5, 10); LOGF(INFO, "%s \n", "A string"); return 0; } And here is possible output : Characters: a A : Decimals: 1977 650000 : Preceding with blanks: 1977 : Preceding with zeros: 0000001977 : Some different radixes: 100 64 144 0x64 0144 : floats: 3.14 +3e+000 3.141600E+000 : Width trick: 10 : A string \endverbatim */ #define LOGF(level, printf_like_message, ...) \ if (!g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).capturef(printf_like_message, ##__VA_ARGS__) // Conditional log printf syntax #define LOGF_IF(level,boolean_expression, printf_like_message, ...) \ if (false == (boolean_expression) || !g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).capturef(printf_like_message, ##__VA_ARGS__) // Design By Contract, printf-like API syntax with variadic input parameters. // Throws std::runtime_eror if contract breaks #define CHECKF(boolean_expression, printf_like_message, ...) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).capturef(printf_like_message, ##__VA_ARGS__) // Backwards compatible. The same as CHECKF. // Design By Contract, printf-like API syntax with variadic input parameters. // Throws std::runtime_eror if contract breaks #define CHECK_F(boolean_expression, printf_like_message, ...) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).capturef(printf_like_message, ##__VA_ARGS__) <commit_msg>updated code comments since SIGABRT is used with default fatal handler instead of a throw<commit_after>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================ * * Filename:g3log.hpp Framework for Logging and Design By Contract * Created: 2011 by Kjell Hedström * * PUBLIC DOMAIN and Not copywrited since it was built on public-domain software and influenced * at least in "spirit" from the following sources * 1. kjellkod.cc ;) * 2. Dr.Dobbs, Petru Marginean: http://drdobbs.com/article/printableArticle.jhtml?articleId=201804215&dept_url=/caddpp/ * 3. Dr.Dobbs, Michael Schulze: http://drdobbs.com/article/printableArticle.jhtml?articleId=225700666&dept_url=/cpp/ * 4. Google 'glog': http://google-glog.googlecode.com/svn/trunk/doc/glog.html * 5. Various Q&A at StackOverflow * ********************************************* */ #pragma once #include "g3log/loglevels.hpp" #include "g3log/logcapture.hpp" #include "g3log/logmessage.hpp" #include "g3log/generated_definitions.hpp" #include <string> #include <functional> #if !(defined(__PRETTY_FUNCTION__)) #define __PRETTY_FUNCTION__ __FUNCTION__ #endif // thread_local doesn't exist before VS2013 // it exists on VS2015 #if !(defined(thread_local)) && defined(_MSC_VER) && _MSC_VER < 1900 #define thread_local __declspec(thread) #endif /** namespace for LOG() and CHECK() frameworks * History lesson: Why the names 'g3' and 'g3log'?: * The framework was made in my own free time as PUBLIC DOMAIN but the * first commercial project to use it used 'g3' as an internal denominator for * the current project. g3 as in 'generation 2'. I decided to keep the g3 and g3log names * to give credit to the people in that project (you know who you are :) and I guess also * for 'sentimental' reasons. That a big influence was Google's glog is just a happy * coincidence or subconscious choice. Either way g3log became the name for this logger. * * --- Thanks for a great 2011 and good luck with 'g3' --- KjellKod */ namespace g3 { class LogWorker; struct LogMessage; struct FatalMessage; /** Should be called at very first startup of the software with \ref g3LogWorker * pointer. Ownership of the \ref g3LogWorker is the responsibility of the caller */ void initializeLogging(LogWorker *logger); /** setFatalPreLoggingHook() provides an optional extra step before the fatalExitHandler is called * * Set a function-hook before a fatal message will be sent to the logger * i.e. this is a great place to put a break point, either in your debugger * or programatically to catch LOG(FATAL), CHECK(...) or an OS fatal event (exception or signal) * This will be reset to default (does nothing) at initializeLogging(...); * * Example usage: * Windows: g3::setFatalPreLoggingHook([]{__debugbreak();}); // remember #include <intrin.h> * WARNING: '__debugbreak()' when not running in Debug in your Visual Studio IDE will likely * trigger a recursive crash if used here. It should only be used when debugging * in your Visual Studio IDE. Recursive crashes are handled but are unnecessary. * * Linux: g3::setFatalPreLoggingHook([]{ raise(SIGTRAP); }); */ void setFatalPreLoggingHook(std::function<void(void)> pre_fatal_hook); /** If the @ref setFatalPreLoggingHook is not enough and full fatal exit handling is needed then * use "setFatalExithandler". Please see g3log.cpp and crashhandler_windows.cpp or crashhandler_unix for * example of restoring signal and exception handlers, flushing the log and shutting down. */ void setFatalExitHandler(std::function<void(FatalMessagePtr)> fatal_call); #ifdef G3_DYNAMIC_MAX_MESSAGE_SIZE // only_change_at_initialization namespace is for changes to be done only during initialization. More specifically // items here would be called prior to calling other parts of g3log namespace only_change_at_initialization { // Sets the MaxMessageSize to be used when capturing log messages. Currently this value is set to 2KB. Messages // Longer than this are bound to 2KB with the string "[...truncated...]" at the end. This function allows // this limit to be changed. void setMaxMessageSize(size_t max_size); } #endif /* G3_DYNAMIC_MAX_MESSAGE_SIZE */ // internal namespace is for completely internal or semi-hidden from the g3 namespace due to that it is unlikely // that you will use these namespace internal { /// @returns true if logger is initialized bool isLoggingInitialized(); // Save the created LogMessage to any existing sinks void saveMessage(const char *message, const char *file, int line, const char *function, const LEVELS &level, const char *boolean_expression, int fatal_signal, const char *stack_trace); // forwards the message to all sinks void pushMessageToLogger(LogMessagePtr log_entry); // forwards a FATAL message to all sinks,. after which the g3logworker // will trigger crashhandler / g3::internal::exitWithDefaultSignalHandler // // By default the "fatalCall" will forward a FatalMessageptr to this function // this behavior can be changed if you set a different fatal handler through // "setFatalExitHandler" void pushFatalMessageToLogger(FatalMessagePtr message); // Saves the created FatalMessage to any existing sinks and exits with // the originating fatal signal,. or SIGABRT if it originated from a broken contract. // By default forwards to: pushFatalMessageToLogger, see "setFatalExitHandler" to override // // If you override it then you probably want to call "pushFatalMessageToLogger" after your // custom fatal handler is done. This will make sure that the fatal message the pushed // to sinks as well as shutting down the process void fatalCall(FatalMessagePtr message); // Shuts down logging. No object cleanup but further LOG(...) calls will be ignored. void shutDownLogging(); // Shutdown logging, but ONLY if the active logger corresponds to the one currently initialized bool shutDownLoggingForActiveOnly(LogWorker *active); } // internal } // g3 #define INTERNAL_LOG_MESSAGE(level) LogCapture(__FILE__, __LINE__, static_cast<const char*>(__PRETTY_FUNCTION__), level) #define INTERNAL_CONTRACT_MESSAGE(boolean_expression) \ LogCapture(__FILE__, __LINE__, __PRETTY_FUNCTION__, g3::internal::CONTRACT, boolean_expression) // LOG(level) is the API for the stream log #define LOG(level) if(!g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).stream() // 'Conditional' stream log #define LOG_IF(level, boolean_expression) \ if (false == (boolean_expression) || !g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).stream() // 'Design By Contract' stream API. For Broken Contracts: // unit testing: it will throw std::runtime_error when a contract breaks // I.R.L : it will exit the application by using fatal signal SIGABRT #define CHECK(boolean_expression) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).stream() /** For details please see this * REFERENCE: http://www.cppreference.com/wiki/io/c/printf_format * \verbatim * There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot. Code Format %[flags][width][.precision][length]specifier SPECIFIERS ---------- %c character %d signed integers %i signed integers %e scientific notation, with a lowercase “e” %E scientific notation, with a uppercase “E” %f floating point %g use %e or %f, whichever is shorter %G use %E or %f, whichever is shorter %o octal %s a string of characters %u unsigned integer %x unsigned hexadecimal, with lowercase letters %X unsigned hexadecimal, with uppercase letters %p a pointer %n the argument shall be a pointer to an integer into which is placed the number of characters written so far For flags, width, precision etc please see the above references. EXAMPLES: { LOGF(INFO, "Characters: %c %c \n", 'a', 65); LOGF(INFO, "Decimals: %d %ld\n", 1977, 650000L); // printing long LOGF(INFO, "Preceding with blanks: %10d \n", 1977); LOGF(INFO, "Preceding with zeros: %010d \n", 1977); LOGF(INFO, "Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); LOGF(INFO, "floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); LOGF(INFO, "Width trick: %*d \n", 5, 10); LOGF(INFO, "%s \n", "A string"); return 0; } And here is possible output : Characters: a A : Decimals: 1977 650000 : Preceding with blanks: 1977 : Preceding with zeros: 0000001977 : Some different radixes: 100 64 144 0x64 0144 : floats: 3.14 +3e+000 3.141600E+000 : Width trick: 10 : A string \endverbatim */ #define LOGF(level, printf_like_message, ...) \ if (!g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).capturef(printf_like_message, ##__VA_ARGS__) // Conditional log printf syntax #define LOGF_IF(level,boolean_expression, printf_like_message, ...) \ if (false == (boolean_expression) || !g3::logLevel(level)) {} else INTERNAL_LOG_MESSAGE(level).capturef(printf_like_message, ##__VA_ARGS__) // Design By Contract, printf-like API syntax with variadic input parameters. // Calls the signal handler if the contract failed with the default exit for a failed contract. This is typically SIGABRT // See g3log, setFatalExitHandler(...) which can be overriden for unit tests (ref test_io.cpp) #define CHECKF(boolean_expression, printf_like_message, ...) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).capturef(printf_like_message, ##__VA_ARGS__) // Backwards compatible. The same as CHECKF. // Design By Contract, printf-like API syntax with variadic input parameters. // Calls the signal handler if the contract failed. See g3log, setFatalExitHandler(...) which can be overriden for unit tests // (ref test_io.cpp) #define CHECK_F(boolean_expression, printf_like_message, ...) \ if (true == (boolean_expression)) {} else INTERNAL_CONTRACT_MESSAGE(#boolean_expression).capturef(printf_like_message, ##__VA_ARGS__) <|endoftext|>
<commit_before>#include "convergence/final_flux_or_n.h" #include <memory> #include <optional> #include "convergence/status.h" #include "convergence/flux/tests/multi_checker_mock.h" #include "data/system_fluxes.h" #include "test_helpers/test_helper_functions.h" #include "test_helpers/gmock_wrapper.h" using ::testing::_; using ::testing::NiceMock; class ConvergenceFinalFluxOrNTest : public ::testing::Test { protected: std::unique_ptr<bart::convergence::flux::MultiCheckerMock> mock_multi_checker_ptr; std::unique_ptr<NiceMock<bart::convergence::flux::MultiCheckerMock>> nice_mock_multi_checker_ptr; std::shared_ptr<bart::data::SystemFluxes> system_fluxes; void SetUp(); }; void ConvergenceFinalFluxOrNTest::SetUp() { mock_multi_checker_ptr = std::make_unique<bart::convergence::flux::MultiCheckerMock>(); nice_mock_multi_checker_ptr = std::make_unique<NiceMock<bart::convergence::flux::MultiCheckerMock>>(); system_fluxes = std::make_shared<bart::data::SystemFluxes>(); } TEST_F(ConvergenceFinalFluxOrNTest, DefaultStatus) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); bart::convergence::Status status; status = flux_tester.convergence_status(); ASSERT_EQ(status.iteration_number, 0); ASSERT_EQ(status.max_iterations, 1); ASSERT_FALSE(status.is_complete); ASSERT_FALSE(status.failed_index.has_value()); ASSERT_FALSE(status.delta.has_value()); } TEST_F(ConvergenceFinalFluxOrNTest, BadMaxIterations) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); EXPECT_ANY_THROW(flux_tester.SetMaxIterations(0)); EXPECT_ANY_THROW(flux_tester.SetMaxIterations(-1)); } TEST_F(ConvergenceFinalFluxOrNTest, BadIterations) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); EXPECT_ANY_THROW(flux_tester.SetIteration(0)); EXPECT_ANY_THROW(flux_tester.SetIteration(-1)); } /* Checks for proper handling of the MultiChecker returning a status of * complete, without reaching max iterations */ TEST_F(ConvergenceFinalFluxOrNTest, Convergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(true)); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(0); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); EXPECT_EQ(status.iteration_number, 1); EXPECT_FALSE(status.failed_index.has_value()); EXPECT_FALSE(status.delta.has_value()); } /* Checks for proper handling of the Multichecker returning a status of * not complete, without reaching max iterations */ TEST_F(ConvergenceFinalFluxOrNTest, NoConvergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(false)); EXPECT_CALL(*mock_multi_checker_ptr, failed_index()). WillOnce(::testing::Return(std::make_optional(2))); EXPECT_CALL(*mock_multi_checker_ptr, failed_delta()). WillOnce(::testing::Return(std::make_optional(1.3))); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(0); auto status = flux_tester.CheckFinalConvergence(); EXPECT_FALSE(status.is_complete); EXPECT_EQ(status.iteration_number, 1); EXPECT_EQ(status.failed_index.value(), 2); EXPECT_DOUBLE_EQ(status.delta.value(), 1.3); } /* Checks for proper handling of the Multichecker returning a status of * complete when max iterations is reached, even if not converged. */ TEST_F(ConvergenceFinalFluxOrNTest, MaxIterNoConvergence) { EXPECT_CALL(*nice_mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(false)); ON_CALL(*nice_mock_multi_checker_ptr, failed_index()). WillByDefault(::testing::Return(std::make_optional(2))); ON_CALL(*nice_mock_multi_checker_ptr, failed_delta()). WillByDefault(::testing::Return(std::make_optional(1.3))); bart::convergence::FinalFluxOrN flux_tester( std::move(nice_mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(4); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); } /* Checks for proper handling of the Multichecker returning a status of * complete when max iterations is reached, if converged. */ TEST_F(ConvergenceFinalFluxOrNTest, MaxIterConvergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(true)); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(4); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); } <commit_msg>corrected tests for FinalFluxOrN convergence handling<commit_after>#include "convergence/final_flux_or_n.h" #include <memory> #include <optional> #include "convergence/status.h" #include "convergence/flux/tests/multi_checker_mock.h" #include "data/system_fluxes.h" #include "test_helpers/test_helper_functions.h" #include "test_helpers/gmock_wrapper.h" using ::testing::_; using ::testing::NiceMock; class ConvergenceFinalFluxOrNTest : public ::testing::Test { protected: std::unique_ptr<bart::convergence::flux::MultiCheckerMock> mock_multi_checker_ptr; std::unique_ptr<NiceMock<bart::convergence::flux::MultiCheckerMock>> nice_mock_multi_checker_ptr; std::shared_ptr<bart::data::SystemFluxes> system_fluxes; void SetUp(); }; void ConvergenceFinalFluxOrNTest::SetUp() { mock_multi_checker_ptr = std::make_unique<bart::convergence::flux::MultiCheckerMock>(); nice_mock_multi_checker_ptr = std::make_unique<NiceMock<bart::convergence::flux::MultiCheckerMock>>(); system_fluxes = std::make_shared<bart::data::SystemFluxes>(); } TEST_F(ConvergenceFinalFluxOrNTest, DefaultStatus) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); bart::convergence::Status status; status = flux_tester.convergence_status(); ASSERT_EQ(status.iteration_number, 0); ASSERT_EQ(status.max_iterations, 1); ASSERT_FALSE(status.is_complete); ASSERT_FALSE(status.failed_index.has_value()); ASSERT_FALSE(status.delta.has_value()); } TEST_F(ConvergenceFinalFluxOrNTest, BadMaxIterations) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); EXPECT_ANY_THROW(flux_tester.SetMaxIterations(0)); EXPECT_ANY_THROW(flux_tester.SetMaxIterations(-1)); } TEST_F(ConvergenceFinalFluxOrNTest, BadIterations) { bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); EXPECT_ANY_THROW(flux_tester.SetIteration(-1)); } /* Checks for proper handling of the MultiChecker returning a status of * complete, without reaching max iterations */ TEST_F(ConvergenceFinalFluxOrNTest, Convergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(true)); EXPECT_CALL(*mock_multi_checker_ptr, failed_delta()). WillOnce(::testing::Return(std::nullopt)); EXPECT_CALL(*mock_multi_checker_ptr, failed_index()). WillOnce(::testing::Return(std::nullopt)); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(0); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); EXPECT_EQ(status.iteration_number, 1); EXPECT_FALSE(status.failed_index.has_value()); EXPECT_FALSE(status.delta.has_value()); } /* Checks for proper handling of the Multichecker returning a status of * not complete, without reaching max iterations */ TEST_F(ConvergenceFinalFluxOrNTest, NoConvergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(false)); EXPECT_CALL(*mock_multi_checker_ptr, failed_index()). WillOnce(::testing::Return(std::make_optional(2))); EXPECT_CALL(*mock_multi_checker_ptr, failed_delta()). WillOnce(::testing::Return(std::make_optional(1.3))); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(0); auto status = flux_tester.CheckFinalConvergence(); EXPECT_FALSE(status.is_complete); EXPECT_EQ(status.iteration_number, 1); EXPECT_EQ(status.failed_index.value(), 2); EXPECT_DOUBLE_EQ(status.delta.value(), 1.3); } /* Checks for proper handling of the Multichecker returning a status of * complete when max iterations is reached, even if not converged. */ TEST_F(ConvergenceFinalFluxOrNTest, MaxIterNoConvergence) { EXPECT_CALL(*nice_mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(false)); ON_CALL(*nice_mock_multi_checker_ptr, failed_index()). WillByDefault(::testing::Return(std::make_optional(2))); ON_CALL(*nice_mock_multi_checker_ptr, failed_delta()). WillByDefault(::testing::Return(std::make_optional(1.3))); bart::convergence::FinalFluxOrN flux_tester( std::move(nice_mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(4); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); } /* Checks for proper handling of the Multichecker returning a status of * complete when max iterations is reached, if converged. */ TEST_F(ConvergenceFinalFluxOrNTest, MaxIterConvergence) { EXPECT_CALL(*mock_multi_checker_ptr, CheckIfConverged(_,_)). WillOnce(::testing::Return(true)); EXPECT_CALL(*mock_multi_checker_ptr, failed_delta()). WillOnce(::testing::Return(std::nullopt)); EXPECT_CALL(*mock_multi_checker_ptr, failed_index()). WillOnce(::testing::Return(std::nullopt)); bart::convergence::FinalFluxOrN flux_tester(std::move(mock_multi_checker_ptr), system_fluxes); flux_tester.SetMaxIterations(5).SetIteration(4); auto status = flux_tester.CheckFinalConvergence(); EXPECT_TRUE(status.is_complete); } <|endoftext|>
<commit_before>/* * FileMode.hpp * * Copyright (C) 2009-12 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef CORE_SYSTEM_FILE_MODE_HPP #define CORE_SYSTEM_FILE_MODE_HPP #ifdef _WIN32 #error FileMode.hpp is is not supported on Windows #endif #include <sys/stat.h> #include <sys/unistd.h> #include <shared_core/Error.hpp> #include <shared_core/FilePath.hpp> #include <shared_core/SafeConvert.hpp> namespace rstudio { namespace core { namespace system { inline Error isFileReadable(const FilePath& filePath, bool* pReadable) { int result = ::access(filePath.getAbsolutePath().c_str(), R_OK); if (result == 0) { // user has access *pReadable = true; } else if (errno == EACCES) { // this error is expected when the user doesn't have access to the path *pReadable = false; } else { // some other error (unexpected) return systemError(errno, ERROR_LOCATION); } return Success(); } inline Error isFileWriteable(const FilePath& filePath, bool* pWriteable) { int result = ::access(filePath.getAbsolutePath().c_str(), W_OK); if (result == 0) { // user has access *pWriteable = true; } else if (errno == EACCES) { *pWriteable = false; } else { return systemError(errno, ERROR_LOCATION); } return Success(); } } // namespace system } // namespace core } // namespace rstudio #endif // CORE_SYSTEM_FILE_MODE_HPP <commit_msg>move the rest of the FileMode functions to FilePath<commit_after><|endoftext|>
<commit_before>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/OccupancyGrid.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <tf/transform_listener.h> #include <pcl_ros/transforms.h> #include <cmath> typedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ; nav_msgs::OccupancyGrid nav_map; ros::Publisher map_pub; tf::TransformListener* tf_listener; bool map_changed; int x_origin, y_origin; inline int round (const float a) { return int (a + 0.5); } void setCellOccupancy(const int x, const int y, const int value) { // only include this point if it falls within the map grid if(x < nav_map.info.width && x >= 0 && y < nav_map.info.height && y >= 0) { nav_map.data[y*nav_map.info.width + x] = value; } } void setCellOccupancy(const float x, const float y, const int value) { int x_coord = (int)(x/nav_map.info.resolution) + x_origin; int y_coord = (int)(y/nav_map.info.resolution) + y_origin; setCellOccupancy(x_coord, y_coord, value); } int getCellOccupancy(const int x, const int y) { if(x < nav_map.info.width && x >= 0 && y < nav_map.info.height && y >= 0) { return nav_map.data[y*nav_map.info.width + x]; } return 50; } int getCellOccupancy(const float x, const float y) { int x_coord = (int)(x/nav_map.info.resolution) + x_origin; int y_coord = (int)(y/nav_map.info.resolution) + y_origin; return getCellOccupancy(x_coord, y_coord); } void beamDDA(const tf::Vector3& beamStart, const tf::Vector3& beamEnd) { int dx = (int)((beamEnd.getX() - beamStart.getX())/nav_map.info.resolution); int dy = (int)((beamEnd.getY() - beamStart.getY())/nav_map.info.resolution); int steps; float xIncrement, yIncrement; float x = beamStart.getX()/nav_map.info.resolution; float y = beamStart.getY()/nav_map.info.resolution; if(fabs(dx) > fabs(dy)) steps = fabs(dx); else steps = fabs(dy); xIncrement = ((float)dx)/((float)steps); yIncrement = ((float)dy)/((float)steps); /* ROS_INFO("%3.3f, %3.3f, %3.3f, %3.3f, %d, %d, %d, %3.3f, %3.3f", beamStart.getX(), beamStart.getY(), beamEnd.getX(), beamEnd.getY(), dx, dy, steps, xIncrement, yIncrement);*/ setCellOccupancy(x, y, 0); for(int k=0; k<steps-1; k++) { x += xIncrement; y += yIncrement; int new_value = getCellOccupancy(round(x)+x_origin, round(y)+y_origin) - 5; if(new_value < 0) new_value = 0; setCellOccupancy(round(x)+x_origin, round(y)+y_origin, new_value); } } void laserCallback(const sensor_msgs::PointCloud2::ConstPtr& ros_cloud) { sensor_msgs::PointCloud2 map_ros_cloud; if(!tf_listener->waitForTransform( "/map", "/base_link", ros_cloud->header.stamp, ros::Duration(1.0))) { ROS_INFO("Transform from /map to /base_link failed"); return; // if a transform isn't found within one second give up } pcl_ros::transformPointCloud("/map", *ros_cloud, map_ros_cloud, *tf_listener); // get the start point of the laser beam tf::StampedTransform laser_transform; if(!tf_listener->waitForTransform( "/map", "/head_hokuyo_frame", ros_cloud->header.stamp, ros::Duration(1.0))) { ROS_INFO("Transform from /map to /head_hokuyo_frame failed"); return; } tf_listener->lookupTransform("/map", "/head_hokuyo_frame", ros_cloud->header.stamp, laser_transform); tf::Vector3 beam_start = laser_transform.getOrigin(); beam_start.setZ(0); // convert to the PCL format PointCloudXYZ pcl_cloud; pcl::fromROSMsg(map_ros_cloud, pcl_cloud); for(pcl::PointCloud<pcl::PointXYZ>::const_iterator point = pcl_cloud.points.begin(); point != pcl_cloud.points.end(); point++) { if(point->z > 1.2 || point->z < .8) continue; // ignore points outside of the scan plane // get the vector in the map plane tf::Vector3 beam_end(point->x, point->y, 0); beamDDA(beam_start, beam_end); double beam_length = beam_end.distance(beam_start); // ignore the max distance results and results that come from // within the bounding cylinder of the robot if(fabs(beam_length - 30.0) < .03 || fabs(beam_length) < .5) continue; // skip points that are near the max sensor range int new_value = getCellOccupancy(point->x, point->y) + 25; if(new_value > 100) new_value = 100; setCellOccupancy(point->x, point->y, new_value); } map_changed = true; } int main(int argc, char** argv) { ros::init(argc, argv, "map_creator_2d"); ros::NodeHandle nh; ros::NodeHandle priv_nh("~"); double map_resolution, x_offset, y_offset; int map_width, map_height; priv_nh.param<double>("resolution", map_resolution, 0.05); priv_nh.param<int>("width", map_width, 1000); priv_nh.param<int>("height", map_height, 1000); priv_nh.param<double>("x_offset", x_offset, .5); priv_nh.param<double>("y_offset", y_offset, .5); if(x_offset < 0 || x_offset > 1) { ROS_ERROR("Invalid x_offset. Must be in range [0, 1.0]"); return 1; } if(y_offset < 0 || y_offset > 1) { ROS_ERROR("Invalid y_offset. Must be in range [0, 1.0]"); return 1; } tf_listener = new tf::TransformListener(); // set the nav_map frame nav_map.header.frame_id = "/map"; // fill out the meta-data nav_map.info.map_load_time = ros::Time::now(); nav_map.info.resolution = map_resolution; nav_map.info.width = map_width; nav_map.info.height = map_height; nav_map.info.origin.position.x = -nav_map.info.resolution*nav_map.info.width*x_offset; nav_map.info.origin.position.y = -nav_map.info.resolution*nav_map.info.height*y_offset; nav_map.info.origin.orientation.w = 1.0; // initialize to all unknown for(int i=0; i<nav_map.info.height; i++) { for(int j=0; j<nav_map.info.width; j++) { nav_map.data.push_back(50); } } // get the origin coordinates in the map grid x_origin = (int)(nav_map.info.width*x_offset); y_origin = (int)(nav_map.info.height*y_offset); // now that the datastructure is initialized set up the ROS stuff map_pub = nh.advertise<nav_msgs::OccupancyGrid>("/map", 1, true); ros::Subscriber laser_sub = nh.subscribe<sensor_msgs::PointCloud2>("laser/points", 10, &laserCallback); ros::Rate loop_rate(10); while(ros::ok()) { if(map_changed) { nav_map.header.stamp = ros::Time::now(); map_pub.publish(nav_map); map_changed = false; } ros::spinOnce(); loop_rate.sleep(); } delete tf_listener; } <commit_msg>printing the resolution, size and origin that the map creator will be using.<commit_after>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/OccupancyGrid.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <tf/transform_listener.h> #include <pcl_ros/transforms.h> #include <cmath> typedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ; nav_msgs::OccupancyGrid nav_map; ros::Publisher map_pub; tf::TransformListener* tf_listener; bool map_changed; int x_origin, y_origin; inline int round (const float a) { return int (a + 0.5); } void setCellOccupancy(const int x, const int y, const int value) { // only include this point if it falls within the map grid if(x < nav_map.info.width && x >= 0 && y < nav_map.info.height && y >= 0) { nav_map.data[y*nav_map.info.width + x] = value; } } void setCellOccupancy(const float x, const float y, const int value) { int x_coord = (int)(x/nav_map.info.resolution) + x_origin; int y_coord = (int)(y/nav_map.info.resolution) + y_origin; setCellOccupancy(x_coord, y_coord, value); } int getCellOccupancy(const int x, const int y) { if(x < nav_map.info.width && x >= 0 && y < nav_map.info.height && y >= 0) { return nav_map.data[y*nav_map.info.width + x]; } return 50; } int getCellOccupancy(const float x, const float y) { int x_coord = (int)(x/nav_map.info.resolution) + x_origin; int y_coord = (int)(y/nav_map.info.resolution) + y_origin; return getCellOccupancy(x_coord, y_coord); } void beamDDA(const tf::Vector3& beamStart, const tf::Vector3& beamEnd) { int dx = (int)((beamEnd.getX() - beamStart.getX())/nav_map.info.resolution); int dy = (int)((beamEnd.getY() - beamStart.getY())/nav_map.info.resolution); int steps; float xIncrement, yIncrement; float x = beamStart.getX()/nav_map.info.resolution; float y = beamStart.getY()/nav_map.info.resolution; if(fabs(dx) > fabs(dy)) steps = fabs(dx); else steps = fabs(dy); xIncrement = ((float)dx)/((float)steps); yIncrement = ((float)dy)/((float)steps); /* ROS_INFO("%3.3f, %3.3f, %3.3f, %3.3f, %d, %d, %d, %3.3f, %3.3f", beamStart.getX(), beamStart.getY(), beamEnd.getX(), beamEnd.getY(), dx, dy, steps, xIncrement, yIncrement);*/ setCellOccupancy(x, y, 0); for(int k=0; k<steps-1; k++) { x += xIncrement; y += yIncrement; int new_value = getCellOccupancy(round(x)+x_origin, round(y)+y_origin) - 5; if(new_value < 0) new_value = 0; setCellOccupancy(round(x)+x_origin, round(y)+y_origin, new_value); } } void laserCallback(const sensor_msgs::PointCloud2::ConstPtr& ros_cloud) { sensor_msgs::PointCloud2 map_ros_cloud; if(!tf_listener->waitForTransform( "/map", "/base_link", ros_cloud->header.stamp, ros::Duration(1.0))) { ROS_INFO("Transform from /map to /base_link failed"); return; // if a transform isn't found within one second give up } pcl_ros::transformPointCloud("/map", *ros_cloud, map_ros_cloud, *tf_listener); // get the start point of the laser beam tf::StampedTransform laser_transform; if(!tf_listener->waitForTransform( "/map", "/head_hokuyo_frame", ros_cloud->header.stamp, ros::Duration(1.0))) { ROS_INFO("Transform from /map to /head_hokuyo_frame failed"); return; } tf_listener->lookupTransform("/map", "/head_hokuyo_frame", ros_cloud->header.stamp, laser_transform); tf::Vector3 beam_start = laser_transform.getOrigin(); beam_start.setZ(0); // convert to the PCL format PointCloudXYZ pcl_cloud; pcl::fromROSMsg(map_ros_cloud, pcl_cloud); for(pcl::PointCloud<pcl::PointXYZ>::const_iterator point = pcl_cloud.points.begin(); point != pcl_cloud.points.end(); point++) { if(point->z > 1.2 || point->z < .8) continue; // ignore points outside of the scan plane // get the vector in the map plane tf::Vector3 beam_end(point->x, point->y, 0); beamDDA(beam_start, beam_end); double beam_length = beam_end.distance(beam_start); // ignore the max distance results and results that come from // within the bounding cylinder of the robot if(fabs(beam_length - 30.0) < .03 || fabs(beam_length) < .5) continue; // skip points that are near the max sensor range int new_value = getCellOccupancy(point->x, point->y) + 25; if(new_value > 100) new_value = 100; setCellOccupancy(point->x, point->y, new_value); } map_changed = true; } int main(int argc, char** argv) { ros::init(argc, argv, "map_creator_2d"); ros::NodeHandle nh; ros::NodeHandle priv_nh("~"); double map_resolution, x_offset, y_offset; int map_width, map_height; priv_nh.param<double>("resolution", map_resolution, 0.05); priv_nh.param<int>("width", map_width, 1000); priv_nh.param<int>("height", map_height, 1000); priv_nh.param<double>("x_offset", x_offset, .5); priv_nh.param<double>("y_offset", y_offset, .5); ROS_INFO("Map Resolution %3.3f", map_resolution); ROS_INFO("Map Size (%d, %d)", map_width, map_height); ROS_INFO("Map Origin Offset (%3.3f, %3.3f)", x_offset, y_offset); if(x_offset < 0 || x_offset > 1) { ROS_ERROR("Invalid x_offset. Must be in range [0, 1.0]"); return 1; } if(y_offset < 0 || y_offset > 1) { ROS_ERROR("Invalid y_offset. Must be in range [0, 1.0]"); return 1; } tf_listener = new tf::TransformListener(); // set the nav_map frame nav_map.header.frame_id = "/map"; // fill out the meta-data nav_map.info.map_load_time = ros::Time::now(); nav_map.info.resolution = map_resolution; nav_map.info.width = map_width; nav_map.info.height = map_height; nav_map.info.origin.position.x = -nav_map.info.resolution*nav_map.info.width*x_offset; nav_map.info.origin.position.y = -nav_map.info.resolution*nav_map.info.height*y_offset; nav_map.info.origin.orientation.w = 1.0; // initialize to all unknown for(int i=0; i<nav_map.info.height; i++) { for(int j=0; j<nav_map.info.width; j++) { nav_map.data.push_back(50); } } // get the origin coordinates in the map grid x_origin = (int)(nav_map.info.width*x_offset); y_origin = (int)(nav_map.info.height*y_offset); // now that the datastructure is initialized set up the ROS stuff map_pub = nh.advertise<nav_msgs::OccupancyGrid>("/map", 1, true); ros::Subscriber laser_sub = nh.subscribe<sensor_msgs::PointCloud2>("laser/points", 10, &laserCallback); ros::Rate loop_rate(10); while(ros::ok()) { if(map_changed) { nav_map.header.stamp = ros::Time::now(); map_pub.publish(nav_map); map_changed = false; } ros::spinOnce(); loop_rate.sleep(); } delete tf_listener; } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2004 Tobias Koenig <tokoe@kde.org> 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. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <QLayout> #include <QPushButton> #include <QTimer> //Added by qt3to4: #include <QGridLayout> #include <kabc/resource.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kresources/configdialog.h> #include "core.h" #include "resourceselection.h" #include <libkdepim/resourceabc.h> class AddressBookWrapper : public KABC::AddressBook { public: AddressBookWrapper( KABC::AddressBook* ); KRES::Manager<KABC::Resource>* getResourceManager() { return resourceManager(); } }; class ResourceItem : public Q3CheckListItem { public: ResourceItem( K3ListView *parent, KABC::Resource *resource ) : Q3CheckListItem( parent, resource->resourceName(), CheckBox ), mResource( resource ), mChecked( false ), mIsSubresource( false ), mSubItemsCreated( false ), mResourceIdentifier() { setOn( resource->isActive() ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent, const QString& resourceIdent ) : Q3CheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ), mResource( resourceABC ), mChecked( false ), mIsSubresource( true ), mSubItemsCreated( false ), mResourceIdentifier( resourceIdent ) { KPIM::ResourceABC* res = static_cast<KPIM::ResourceABC *>( mResource ); setOn( res->subresourceActive( mResourceIdentifier ) ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } void createSubresourceItems(); void setChecked( bool state ) { mChecked = state; } bool checked() const { return mChecked; } KABC::Resource *resource() const { return mResource; } QString resourceIdentifier() const { return mResourceIdentifier; } bool isSubResource() const { return mIsSubresource; } virtual void stateChange( bool active ); private: KABC::Resource * const mResource; bool mChecked; const bool mIsSubresource; bool mSubItemsCreated; const QString mResourceIdentifier; }; // Comes from korganizer/resourceview.cpp void ResourceItem::createSubresourceItems() { KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource ); QStringList subresources; if ( res ) subresources = res->subresources(); if ( !subresources.isEmpty() ) { setOpen( true ); setExpandable( true ); // This resource has subresources QStringList::ConstIterator it; for ( it = subresources.begin(); it != subresources.end(); ++it ) { (void)new ResourceItem( res, this, *it ); } } mSubItemsCreated = true; } // TODO: connect this to some signalResourceModified // void ResourceItem::setGuiState() // { // if ( mIsSubresource ) // setOn( mResource->subresourceActive( mResourceIdentifier ) ); // else // setOn( mResource->isActive() ); // } void ResourceItem::stateChange( bool active ) { //kDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl; if ( active && !mIsSubresource ) { if ( !mSubItemsCreated ) createSubresourceItems(); } setOpen( active && childCount() > 0 ); } //// ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent ) : KAB::ExtensionWidget( core, parent ), mManager( 0 ) { initGUI(); AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() ); mManager = wrapper->getResourceManager(); connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) ); connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) ); connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) ); connect( mListView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( currentChanged( Q3ListViewItem* ) ) ); QTimer::singleShot( 0, this, SLOT( updateView() ) ); } ResourceSelection::~ResourceSelection() { } QString ResourceSelection::title() const { return i18n( "Address Books" ); } QString ResourceSelection::identifier() const { return "resourceselection"; } void ResourceSelection::add() { QStringList types = mManager->resourceTypeNames(); QStringList descs = mManager->resourceTypeDescriptions(); bool ok = false; QString desc = KInputDialog::getItem( i18n( "Add Address Book" ), i18n( "Please select type of the new address book:" ), descs, 0, false, &ok, this ); if ( !ok ) return; QString type = types[ descs.indexOf( desc ) ]; // Create new resource KABC::Resource *resource = mManager->createResource( type ); if ( !resource ) { KMessageBox::error( this, i18n("<qt>Unable to create an address book of type <b>%1</b>.</qt>", type ) ); return; } resource->setResourceName( i18n( "%1 address book", type ) ); KRES::ConfigDialog dlg( this, QString( "contact" ), resource ); if ( dlg.exec() ) { core()->addressBook()->addResource( resource ); resource->asyncLoad(); mLastResource = resource->identifier(); updateView(); } else { delete resource; resource = 0; } } void ResourceSelection::edit() { ResourceItem *item = selectedItem(); if ( !item ) return; KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() ); if ( dlg.exec() ) { mManager->change( item->resource() ); item->resource()->asyncLoad(); mLastResource = item->resource()->identifier(); updateView(); } } void ResourceSelection::remove() { ResourceItem *item = selectedItem(); if ( !item ) return; int result = KMessageBox::warningContinueCancel( this, i18n( "<qt>Do you really want to remove the address book <b>%1</b>?</qt>" , item->resource()->resourceName() ), "", KGuiItem( i18n( "&Remove" ), "editdelete" ) ); if ( result == KMessageBox::Cancel ) return; mLastResource = item->resource()->identifier(); core()->addressBook()->removeResource( item->resource() ); core()->addressBook()->emitAddressBookChanged(); updateView(); } void ResourceSelection::currentChanged( Q3ListViewItem *item ) { ResourceItem *resItem = static_cast<ResourceItem*>( item ); bool state = (resItem && !resItem->isSubResource() ); mEditButton->setEnabled( state ); mRemoveButton->setEnabled( state ); if ( !resItem ) return; KABC::Resource *resource = resItem->resource(); if ( resItem->checked() != resItem->isOn() ) { resItem->setChecked( resItem->isOn() ); if ( resItem->isSubResource() ) { KPIM::ResourceABC *res = dynamic_cast<KPIM::ResourceABC *>( resource ); res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() ); mManager->change( resource ); } else { resource->setActive( resItem->isOn() ); mManager->change( resource ); if ( resItem->checked() ) { if ( !resource->addressBook() ) resource->setAddressBook( core()->addressBook() ); if ( !resource->isOpen() ) resource->open(); resource->asyncLoad(); } else { resource->close(); } } mLastResource = resource->identifier(); core()->addressBook()->emitAddressBookChanged(); //updateView(); } } void ResourceSelection::updateView() { if ( !mManager ) return; mListView->clear(); KRES::Manager<KABC::Resource>::Iterator it; for ( it = mManager->begin(); it != mManager->end(); ++it ) { new ResourceItem( mListView, *it ); KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it ); if ( resource ) { disconnect( resource, 0, this, 0 ); connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ) ); connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ) ); //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ), // SLOT( closeResource( KPIM::ResourceABC * ) ) ); } } Q3ListViewItemIterator itemIt( mListView ); while ( itemIt.current() ) { ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() ); if ( item->resource()->identifier() == mLastResource ) { mListView->setSelected( item, true ); mListView->ensureItemVisible( item ); break; } ++itemIt; } core()->addressBook()->emitAddressBookChanged(); } // Add a new entry void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; Q3ListViewItem *i = mListView->findItem( resource->resourceName(), 0 ); if ( !i ) // Not found return; ResourceItem *item = static_cast<ResourceItem *>( i ); (void)new ResourceItem( resource, item, subResource ); } // Remove an entry void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; // TODO //delete findItemByIdentifier( resource ); //emitResourcesChanged(); } ResourceItem* ResourceSelection::selectedItem() const { return static_cast<ResourceItem*>( mListView->selectedItem() ); } void ResourceSelection::initGUI() { QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 5 ); layout->setMargin( 2 ); mListView = new K3ListView( this ); mListView->addColumn( i18n( "Address Books" ) ); mListView->setFullWidth( true ); layout->addWidget( mListView, 0, 0, 1, 3 ); mAddButton = new QPushButton( i18n( "Add..." ), this ); mEditButton = new QPushButton( i18n( "Edit..." ), this ); mEditButton->setEnabled( false ); mRemoveButton = new QPushButton( i18n( "Remove" ), this ); mRemoveButton->setEnabled( false ); layout->addWidget( mAddButton, 1, 0 ); layout->addWidget( mEditButton, 1, 1 ); layout->addWidget( mRemoveButton, 1, 2 ); } class ResourceSelectionFactory : public KAB::ExtensionFactory { public: KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent ) { return new ResourceSelection( core, parent ); } QString identifier() const { return "resourceselection"; } }; extern "C" { KDE_EXPORT void *init_libkaddrbk_resourceselection() { return ( new ResourceSelectionFactory ); } } #include "resourceselection.moc" <commit_msg>dynamic_cast without checking for the result doesn't make sense (CID 2070)<commit_after>/* This file is part of KAddressBook. Copyright (c) 2004 Tobias Koenig <tokoe@kde.org> 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. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <QLayout> #include <QPushButton> #include <QTimer> //Added by qt3to4: #include <QGridLayout> #include <kabc/resource.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kresources/configdialog.h> #include "core.h" #include "resourceselection.h" #include <libkdepim/resourceabc.h> class AddressBookWrapper : public KABC::AddressBook { public: AddressBookWrapper( KABC::AddressBook* ); KRES::Manager<KABC::Resource>* getResourceManager() { return resourceManager(); } }; class ResourceItem : public Q3CheckListItem { public: ResourceItem( K3ListView *parent, KABC::Resource *resource ) : Q3CheckListItem( parent, resource->resourceName(), CheckBox ), mResource( resource ), mChecked( false ), mIsSubresource( false ), mSubItemsCreated( false ), mResourceIdentifier() { setOn( resource->isActive() ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent, const QString& resourceIdent ) : Q3CheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ), mResource( resourceABC ), mChecked( false ), mIsSubresource( true ), mSubItemsCreated( false ), mResourceIdentifier( resourceIdent ) { KPIM::ResourceABC* res = static_cast<KPIM::ResourceABC *>( mResource ); setOn( res->subresourceActive( mResourceIdentifier ) ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } void createSubresourceItems(); void setChecked( bool state ) { mChecked = state; } bool checked() const { return mChecked; } KABC::Resource *resource() const { return mResource; } QString resourceIdentifier() const { return mResourceIdentifier; } bool isSubResource() const { return mIsSubresource; } virtual void stateChange( bool active ); private: KABC::Resource * const mResource; bool mChecked; const bool mIsSubresource; bool mSubItemsCreated; const QString mResourceIdentifier; }; // Comes from korganizer/resourceview.cpp void ResourceItem::createSubresourceItems() { KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource ); QStringList subresources; if ( res ) subresources = res->subresources(); if ( !subresources.isEmpty() ) { setOpen( true ); setExpandable( true ); // This resource has subresources QStringList::ConstIterator it; for ( it = subresources.begin(); it != subresources.end(); ++it ) { (void)new ResourceItem( res, this, *it ); } } mSubItemsCreated = true; } // TODO: connect this to some signalResourceModified // void ResourceItem::setGuiState() // { // if ( mIsSubresource ) // setOn( mResource->subresourceActive( mResourceIdentifier ) ); // else // setOn( mResource->isActive() ); // } void ResourceItem::stateChange( bool active ) { //kDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl; if ( active && !mIsSubresource ) { if ( !mSubItemsCreated ) createSubresourceItems(); } setOpen( active && childCount() > 0 ); } //// ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent ) : KAB::ExtensionWidget( core, parent ), mManager( 0 ) { initGUI(); AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() ); mManager = wrapper->getResourceManager(); connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) ); connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) ); connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) ); connect( mListView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( currentChanged( Q3ListViewItem* ) ) ); QTimer::singleShot( 0, this, SLOT( updateView() ) ); } ResourceSelection::~ResourceSelection() { } QString ResourceSelection::title() const { return i18n( "Address Books" ); } QString ResourceSelection::identifier() const { return "resourceselection"; } void ResourceSelection::add() { QStringList types = mManager->resourceTypeNames(); QStringList descs = mManager->resourceTypeDescriptions(); bool ok = false; QString desc = KInputDialog::getItem( i18n( "Add Address Book" ), i18n( "Please select type of the new address book:" ), descs, 0, false, &ok, this ); if ( !ok ) return; QString type = types[ descs.indexOf( desc ) ]; // Create new resource KABC::Resource *resource = mManager->createResource( type ); if ( !resource ) { KMessageBox::error( this, i18n("<qt>Unable to create an address book of type <b>%1</b>.</qt>", type ) ); return; } resource->setResourceName( i18n( "%1 address book", type ) ); KRES::ConfigDialog dlg( this, QString( "contact" ), resource ); if ( dlg.exec() ) { core()->addressBook()->addResource( resource ); resource->asyncLoad(); mLastResource = resource->identifier(); updateView(); } else { delete resource; resource = 0; } } void ResourceSelection::edit() { ResourceItem *item = selectedItem(); if ( !item ) return; KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() ); if ( dlg.exec() ) { mManager->change( item->resource() ); item->resource()->asyncLoad(); mLastResource = item->resource()->identifier(); updateView(); } } void ResourceSelection::remove() { ResourceItem *item = selectedItem(); if ( !item ) return; int result = KMessageBox::warningContinueCancel( this, i18n( "<qt>Do you really want to remove the address book <b>%1</b>?</qt>" , item->resource()->resourceName() ), "", KGuiItem( i18n( "&Remove" ), "editdelete" ) ); if ( result == KMessageBox::Cancel ) return; mLastResource = item->resource()->identifier(); core()->addressBook()->removeResource( item->resource() ); core()->addressBook()->emitAddressBookChanged(); updateView(); } void ResourceSelection::currentChanged( Q3ListViewItem *item ) { ResourceItem *resItem = static_cast<ResourceItem*>( item ); bool state = (resItem && !resItem->isSubResource() ); mEditButton->setEnabled( state ); mRemoveButton->setEnabled( state ); if ( !resItem ) return; KABC::Resource *resource = resItem->resource(); if ( resItem->checked() != resItem->isOn() ) { resItem->setChecked( resItem->isOn() ); if ( resItem->isSubResource() ) { KPIM::ResourceABC *res = static_cast<KPIM::ResourceABC *>( resource ); res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() ); mManager->change( resource ); } else { resource->setActive( resItem->isOn() ); mManager->change( resource ); if ( resItem->checked() ) { if ( !resource->addressBook() ) resource->setAddressBook( core()->addressBook() ); if ( !resource->isOpen() ) resource->open(); resource->asyncLoad(); } else { resource->close(); } } mLastResource = resource->identifier(); core()->addressBook()->emitAddressBookChanged(); //updateView(); } } void ResourceSelection::updateView() { if ( !mManager ) return; mListView->clear(); KRES::Manager<KABC::Resource>::Iterator it; for ( it = mManager->begin(); it != mManager->end(); ++it ) { new ResourceItem( mListView, *it ); KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it ); if ( resource ) { disconnect( resource, 0, this, 0 ); connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ) ); connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ) ); //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ), // SLOT( closeResource( KPIM::ResourceABC * ) ) ); } } Q3ListViewItemIterator itemIt( mListView ); while ( itemIt.current() ) { ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() ); if ( item->resource()->identifier() == mLastResource ) { mListView->setSelected( item, true ); mListView->ensureItemVisible( item ); break; } ++itemIt; } core()->addressBook()->emitAddressBookChanged(); } // Add a new entry void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; Q3ListViewItem *i = mListView->findItem( resource->resourceName(), 0 ); if ( !i ) // Not found return; ResourceItem *item = static_cast<ResourceItem *>( i ); (void)new ResourceItem( resource, item, subResource ); } // Remove an entry void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; // TODO //delete findItemByIdentifier( resource ); //emitResourcesChanged(); } ResourceItem* ResourceSelection::selectedItem() const { return static_cast<ResourceItem*>( mListView->selectedItem() ); } void ResourceSelection::initGUI() { QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 5 ); layout->setMargin( 2 ); mListView = new K3ListView( this ); mListView->addColumn( i18n( "Address Books" ) ); mListView->setFullWidth( true ); layout->addWidget( mListView, 0, 0, 1, 3 ); mAddButton = new QPushButton( i18n( "Add..." ), this ); mEditButton = new QPushButton( i18n( "Edit..." ), this ); mEditButton->setEnabled( false ); mRemoveButton = new QPushButton( i18n( "Remove" ), this ); mRemoveButton->setEnabled( false ); layout->addWidget( mAddButton, 1, 0 ); layout->addWidget( mEditButton, 1, 1 ); layout->addWidget( mRemoveButton, 1, 2 ); } class ResourceSelectionFactory : public KAB::ExtensionFactory { public: KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent ) { return new ResourceSelection( core, parent ); } QString identifier() const { return "resourceselection"; } }; extern "C" { KDE_EXPORT void *init_libkaddrbk_resourceselection() { return ( new ResourceSelectionFactory ); } } #include "resourceselection.moc" <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001, 2004 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007-2008 Dominik Haumann <dhaumann kde org> Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com> Copyright (C) 2008 Eduardo Robles Elvira <edulix@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 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 "katefinddialog.h" #include "katefindinfiles.h" #include "kateresultview.h" #include "katefindoptions.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <kdebug.h> #include <QClipboard> #include <QRegExp> #include <QShowEvent> #include <QLineEdit> #include <kacceleratormanager.h> #include <kconfig.h> #include <kiconloader.h> #include <klocale.h> #include <kmessagebox.h> #include <kurlcompletion.h> KateFindDialog::KateFindDialog(Kate::MainWindow *mw, KateFindInFilesView *view) : KDialog(mw->window()), m_mw (mw), m_view(view) , m_useId(-1) { setCaption(i18n("Find in Files")); setButtons(Close | User1); setButtonGuiItem(User1, KStandardGuiItem::find()); setDefaultButton(User1); QWidget* widget = new QWidget(this); setupUi(widget); setMainWidget(widget); // if possible, ui properties are set in the .ui-file // set sync icon btnSync->setIcon(KIcon("view-refresh")); // get url-requester's combo box and sanely initialize KComboBox* cmbUrl = cmbDir->comboBox(); cmbUrl->setDuplicatesEnabled(false); cmbUrl->setEditable(true); cmbDir->setMode( KFile::Directory | KFile::LocalOnly ); KUrlCompletion* cmpl = new KUrlCompletion(KUrlCompletion::DirCompletion); cmbUrl->setCompletionObject( cmpl ); cmbUrl->setAutoDeleteCompletionObject( true ); updateItems(); syncDir(); // auto-accels KAcceleratorManager::manage( this ); lblPattern->setWhatsThis( i18n("<p>Enter the expression you want to search for here.</p>" "<p>If 'regular expression' is unchecked, any non-space letters in your " "expression will be escaped with a backslash character.</p>" "<p>Possible meta characters are:<br />" "<b>.</b> - Matches any character<br />" "<b>^</b> - Matches the beginning of a line<br />" "<b>$</b> - Matches the end of a line<br />" "<b>\\&lt;</b> - Matches the beginning of a word<br />" "<b>\\&gt;</b> - Matches the end of a word</p>" "<p>The following repetition operators exist:<br />" "<b>?</b> - The preceding item is matched at most once<br />" "<b>*</b> - The preceding item is matched zero or more times<br />" "<b>+</b> - The preceding item is matched one or more times<br />" "<b>{<i>n</i>}</b> - The preceding item is matched exactly <i>n</i> times<br />" "<b>{<i>n</i>,}</b> - The preceding item is matched <i>n</i> or more times<br />" "<b>{,<i>n</i>}</b> - The preceding item is matched at most <i>n</i> times<br />" "<b>{<i>n</i>,<i>m</i>}</b> - The preceding item is matched at least <i>n</i>, " "but at most <i>m</i> times.</p>" "<p>Furthermore, backreferences to bracketed subexpressions are available " "via the notation <code>\\#</code>.</p>" "<p>See the grep(1) documentation for the full documentation.</p>" )); lblFiles->setWhatsThis( i18n("Enter the file name pattern of the files to search here.\n" "You may give several patterns separated by commas.")); lblFolder->setWhatsThis( i18n("Enter the folder which contains the files in which you want to search.")); chkRecursive->setWhatsThis( i18n("Check this box to search in all subfolders.")); chkCaseSensitive->setWhatsThis( i18n("If this option is enabled (the default), the search will be case sensitive.")); chkFollowSymlinks->setWhatsThis( i18n("If this option is enabled, the search will follow symlinks to directories. This can lead to infinite recursion if cyclical symlinks exist.")); connect( this, SIGNAL(user1Clicked()), SLOT(slotSearch()) ); connect( cmbPattern->lineEdit(), SIGNAL(textChanged ( const QString & )), SLOT( patternTextChanged( const QString & ))); connect( btnSync, SIGNAL(clicked()), this, SLOT(syncDir())); patternTextChanged( cmbPattern->lineEdit()->text()); resize(500, 350); } KateFindDialog::~KateFindDialog() { } void KateFindDialog::patternTextChanged( const QString & text) { enableButton(User1, !text.isEmpty()); } void KateFindDialog::slotSearch() { // no pattern set... if ( cmbPattern->currentText().isEmpty() ) { cmbPattern->setFocus(); return; } // dir does not exist... if ( cmbDir->url().isEmpty() || ! QDir(cmbDir->url().toLocalFile ()).exists() ) { cmbDir->setFocus(); KMessageBox::information( this, i18n( "You must enter an existing local folder in the 'Folder' entry."), i18n("Invalid Folder"), "Kate grep tool: invalid folder" ); return; } // regexps QRegExp reg (cmbPattern->currentText(), chkCaseSensitive->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive); QList<QRegExp> liste; liste << reg; KateResultView* view = m_view->toolViewFromId(m_useId); if (!view) { view = new KateResultView(m_mw, m_view); m_view->addResultView(view); } updateConfig(); view->makeVisible(); view->startSearch(KateFindInFilesOptions::self(), liste, cmbDir->url().toLocalFile(), cmbFilter->currentText()); hide(); } void KateFindDialog::updateConfig() { // update last pattern KateFindInFilesOptions::self().addSearchItem(cmbPattern->currentText()); KateFindInFilesOptions::self().addSearchPath(cmbDir->url().url()); KateFindInFilesOptions::self().addSearchFilter(cmbFilter->currentText()); KateFindInFilesOptions::self().setRecursive(chkRecursive->isChecked()); KateFindInFilesOptions::self().setCaseSensitive(chkCaseSensitive->isChecked()); KateFindInFilesOptions::self().setRegExp(chkRegExp->isChecked()); KateFindInFilesOptions::self().setFollowDirectorySymlinks(chkFollowSymlinks->isChecked()); } void KateFindDialog::updateItems() { cmbPattern->clear(); cmbDir->clear(); cmbFilter->clear(); cmbPattern->insertItems(0, KateFindInFilesOptions::self().searchItems()); cmbDir->comboBox()->insertItems(0, KateFindInFilesOptions::self().searchPaths()); cmbFilter->insertItems(0, KateFindInFilesOptions::self().searchFilters()); cmbPattern->setCurrentIndex(0); cmbDir->comboBox()->setCurrentIndex(0); cmbFilter->setCurrentIndex(0); chkRecursive->setChecked(KateFindInFilesOptions::self().recursive()); chkCaseSensitive->setChecked(KateFindInFilesOptions::self().caseSensitive()); chkRegExp->setChecked(KateFindInFilesOptions::self().regExp()); chkFollowSymlinks->setChecked(KateFindInFilesOptions::self().followDirectorySymlinks()); } void KateFindDialog::setPattern(const QList<QRegExp>& pattern) { if (pattern.size()) cmbPattern->setEditText(pattern[0].pattern()); } void KateFindDialog::setUrl(const QString& url) { cmbDir->setUrl(url); } void KateFindDialog::setFilter(const QString& filter) { cmbFilter->setEditText(filter); } void KateFindDialog::setOptions(const KateFindInFilesOptions& options) { chkRecursive->setChecked(options.recursive()); chkCaseSensitive->setChecked(options.caseSensitive()); chkRegExp->setChecked(options.regExp()); chkFollowSymlinks->setChecked(options.followDirectorySymlinks()); } void KateFindDialog::syncDir() { // sync url-requester with active view's path KUrl url = m_mw->activeView()->document()->url(); if (url.isLocalFile()) cmbDir->setUrl(url.directory()); } void KateFindDialog::showEvent(QShowEvent* event) { if (event->spontaneous()) return; cmbPattern->setFocus(); if (!cmbDir->url().isEmpty()) return; syncDir(); } void KateFindDialog::useResultView(int id) { m_useId = id; } #include "katefinddialog.moc" // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>fix regexp option, now actually has some effect<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001, 2004 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007-2008 Dominik Haumann <dhaumann kde org> Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com> Copyright (C) 2008 Eduardo Robles Elvira <edulix@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 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 "katefinddialog.h" #include "katefindinfiles.h" #include "kateresultview.h" #include "katefindoptions.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <kdebug.h> #include <QClipboard> #include <QRegExp> #include <QShowEvent> #include <QLineEdit> #include <kacceleratormanager.h> #include <kconfig.h> #include <kiconloader.h> #include <klocale.h> #include <kmessagebox.h> #include <kurlcompletion.h> KateFindDialog::KateFindDialog(Kate::MainWindow *mw, KateFindInFilesView *view) : KDialog(mw->window()), m_mw (mw), m_view(view) , m_useId(-1) { setCaption(i18n("Find in Files")); setButtons(Close | User1); setButtonGuiItem(User1, KStandardGuiItem::find()); setDefaultButton(User1); QWidget* widget = new QWidget(this); setupUi(widget); setMainWidget(widget); // if possible, ui properties are set in the .ui-file // set sync icon btnSync->setIcon(KIcon("view-refresh")); // get url-requester's combo box and sanely initialize KComboBox* cmbUrl = cmbDir->comboBox(); cmbUrl->setDuplicatesEnabled(false); cmbUrl->setEditable(true); cmbDir->setMode( KFile::Directory | KFile::LocalOnly ); KUrlCompletion* cmpl = new KUrlCompletion(KUrlCompletion::DirCompletion); cmbUrl->setCompletionObject( cmpl ); cmbUrl->setAutoDeleteCompletionObject( true ); updateItems(); syncDir(); // auto-accels KAcceleratorManager::manage( this ); lblPattern->setWhatsThis( i18n("<p>Enter the expression you want to search for here.</p>" "<p>If 'regular expression' is unchecked, any non-space letters in your " "expression will be escaped with a backslash character.</p>" "<p>Possible meta characters are:<br />" "<b>.</b> - Matches any character<br />" "<b>^</b> - Matches the beginning of a line<br />" "<b>$</b> - Matches the end of a line<br />" "<b>\\&lt;</b> - Matches the beginning of a word<br />" "<b>\\&gt;</b> - Matches the end of a word</p>" "<p>The following repetition operators exist:<br />" "<b>?</b> - The preceding item is matched at most once<br />" "<b>*</b> - The preceding item is matched zero or more times<br />" "<b>+</b> - The preceding item is matched one or more times<br />" "<b>{<i>n</i>}</b> - The preceding item is matched exactly <i>n</i> times<br />" "<b>{<i>n</i>,}</b> - The preceding item is matched <i>n</i> or more times<br />" "<b>{,<i>n</i>}</b> - The preceding item is matched at most <i>n</i> times<br />" "<b>{<i>n</i>,<i>m</i>}</b> - The preceding item is matched at least <i>n</i>, " "but at most <i>m</i> times.</p>" "<p>Furthermore, backreferences to bracketed subexpressions are available " "via the notation <code>\\#</code>.</p>" "<p>See the grep(1) documentation for the full documentation.</p>" )); lblFiles->setWhatsThis( i18n("Enter the file name pattern of the files to search here.\n" "You may give several patterns separated by commas.")); lblFolder->setWhatsThis( i18n("Enter the folder which contains the files in which you want to search.")); chkRecursive->setWhatsThis( i18n("Check this box to search in all subfolders.")); chkCaseSensitive->setWhatsThis( i18n("If this option is enabled (the default), the search will be case sensitive.")); chkFollowSymlinks->setWhatsThis( i18n("If this option is enabled, the search will follow symlinks to directories. This can lead to infinite recursion if cyclical symlinks exist.")); connect( this, SIGNAL(user1Clicked()), SLOT(slotSearch()) ); connect( cmbPattern->lineEdit(), SIGNAL(textChanged ( const QString & )), SLOT( patternTextChanged( const QString & ))); connect( btnSync, SIGNAL(clicked()), this, SLOT(syncDir())); patternTextChanged( cmbPattern->lineEdit()->text()); resize(500, 350); } KateFindDialog::~KateFindDialog() { } void KateFindDialog::patternTextChanged( const QString & text) { enableButton(User1, !text.isEmpty()); } void KateFindDialog::slotSearch() { // no pattern set... if ( cmbPattern->currentText().isEmpty() ) { cmbPattern->setFocus(); return; } // dir does not exist... if ( cmbDir->url().isEmpty() || ! QDir(cmbDir->url().toLocalFile ()).exists() ) { cmbDir->setFocus(); KMessageBox::information( this, i18n( "You must enter an existing local folder in the 'Folder' entry."), i18n("Invalid Folder"), "Kate grep tool: invalid folder" ); return; } // regexps QRegExp reg (cmbPattern->currentText() , chkCaseSensitive->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive , chkRegExp->isChecked() ? QRegExp::RegExp : QRegExp::FixedString); QList<QRegExp> liste; liste << reg; KateResultView* view = m_view->toolViewFromId(m_useId); if (!view) { view = new KateResultView(m_mw, m_view); m_view->addResultView(view); } updateConfig(); view->makeVisible(); view->startSearch(KateFindInFilesOptions::self(), liste, cmbDir->url().toLocalFile(), cmbFilter->currentText()); hide(); } void KateFindDialog::updateConfig() { // update last pattern KateFindInFilesOptions::self().addSearchItem(cmbPattern->currentText()); KateFindInFilesOptions::self().addSearchPath(cmbDir->url().url()); KateFindInFilesOptions::self().addSearchFilter(cmbFilter->currentText()); KateFindInFilesOptions::self().setRecursive(chkRecursive->isChecked()); KateFindInFilesOptions::self().setCaseSensitive(chkCaseSensitive->isChecked()); KateFindInFilesOptions::self().setRegExp(chkRegExp->isChecked()); KateFindInFilesOptions::self().setFollowDirectorySymlinks(chkFollowSymlinks->isChecked()); } void KateFindDialog::updateItems() { cmbPattern->clear(); cmbDir->clear(); cmbFilter->clear(); cmbPattern->insertItems(0, KateFindInFilesOptions::self().searchItems()); cmbDir->comboBox()->insertItems(0, KateFindInFilesOptions::self().searchPaths()); cmbFilter->insertItems(0, KateFindInFilesOptions::self().searchFilters()); cmbPattern->setCurrentIndex(0); cmbDir->comboBox()->setCurrentIndex(0); cmbFilter->setCurrentIndex(0); chkRecursive->setChecked(KateFindInFilesOptions::self().recursive()); chkCaseSensitive->setChecked(KateFindInFilesOptions::self().caseSensitive()); chkRegExp->setChecked(KateFindInFilesOptions::self().regExp()); chkFollowSymlinks->setChecked(KateFindInFilesOptions::self().followDirectorySymlinks()); } void KateFindDialog::setPattern(const QList<QRegExp>& pattern) { if (pattern.size()) cmbPattern->setEditText(pattern[0].pattern()); } void KateFindDialog::setUrl(const QString& url) { cmbDir->setUrl(url); } void KateFindDialog::setFilter(const QString& filter) { cmbFilter->setEditText(filter); } void KateFindDialog::setOptions(const KateFindInFilesOptions& options) { chkRecursive->setChecked(options.recursive()); chkCaseSensitive->setChecked(options.caseSensitive()); chkRegExp->setChecked(options.regExp()); chkFollowSymlinks->setChecked(options.followDirectorySymlinks()); } void KateFindDialog::syncDir() { // sync url-requester with active view's path KUrl url = m_mw->activeView()->document()->url(); if (url.isLocalFile()) cmbDir->setUrl(url.directory()); } void KateFindDialog::showEvent(QShowEvent* event) { if (event->spontaneous()) return; cmbPattern->setFocus(); if (!cmbDir->url().isEmpty()) return; syncDir(); } void KateFindDialog::useResultView(int id) { m_useId = id; } #include "katefinddialog.moc" // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/* * perspective.cpp * * Created on: 2016年12月23日 * Author: zhuqian */ #include "raiden.h" #include "perspective.h" #include "sampling.h" #include "paramset.h" #include "film.h" PerspectiveCamera::PerspectiveCamera(const Transform& c2w, const Bound2f& screenWindow, Float shutterOpen, Float shutterEnd, Float lensr, Float focald, Float fov,Film * f, const Medium* medium) : ProjectiveCamera(c2w, Perspective(fov, 1e-3f, 1000.0f)/*c2s*/, screenWindow, shutterOpen, shutterEnd, lensr, focald,f,medium) { //获得光栅化空间下,相机空间对应的差分 _dxCamera = _rasterToCamera(Vector3f(1, 0, 0)) - _rasterToCamera(Vector3f(0, 0, 0)); _dyCamera = _rasterToCamera(Vector3f(0, 1, 0)) - _rasterToCamera(Vector3f(0, 0, 0)); } Float PerspectiveCamera::GenerateRay(const CameraSample &sample, Ray *ray) const { Point3f pRas = Point3f(sample.pFilm.x, sample.pFilm.y, 0.0f); Point3f pCam = _rasterToCamera(pRas); //计算相机空间下的image panel样本值 *ray = Ray(Point3f(0,0,0), Normalize(Vector3f(pCam))); if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算焦距平面交点 //其实这的z就是1 Float ft = _focalDistance / ray->d.z; Point3f pFocus = (*ray)(ft); //原点设置成来自镜面 ray->o = Point3f(lens.x, lens.y, 0); ray->d = Normalize(pFocus - ray->o); } ray->time = Lerp(sample.time, shutterOpen, shutterEnd); Info(medium); ray->medium = medium; *ray = cameraToWorld(*ray); return 1.0f; } Float PerspectiveCamera::GenerateRayDifferential(const CameraSample &sample, RayDifferential *ray) const { Point3f pRas = Point3f(sample.pFilm.x, sample.pFilm.y, 0.0f); Point3f pCam = _rasterToCamera(pRas); //计算相机空间下的image panel样本值 *ray = RayDifferential(Point3f(0,0,0), Normalize(Vector3f(pCam))); if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算焦距平面交点 //其实这的z就是1 Float ft = _focalDistance / ray->d.z; Point3f pFocus = (*ray)(ft); //原点设置成来自镜面 ray->o = Point3f(lens.x, lens.y, 0); ray->d = Normalize(pFocus - ray->o); } //处理微分信息 if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算x射线 Vector3f dx = Normalize(Vector3f(pCam) + _dxCamera); Float ft = _focalDistance / dx.z; Point3f pFocusX = Point3f(0, 0, 0) + (ft * dx); ray->ox = Point3f(lens.x, lens.y, 0); ray->dx = Normalize(pFocusX - ray->ox); //计算y射线 Vector3f dy = Normalize(Vector3f(pCam) + _dyCamera); ft = _focalDistance / dy.z; Point3f pFocusY = Point3f(0, 0, 0) + (ft * dy); ray->oy = Point3f(lens.x, lens.y, 0); ray->dy = Normalize(pFocusY - ray->oy); } else { //镜片为奇点的情况 ray->ox=ray->oy=ray->o; ray->dx = Normalize(Vector3f(pCam)+_dxCamera); ray->dy = Normalize(Vector3f(pCam)+_dyCamera); } ray->hasDifferential = true; ray->time = Lerp(sample.time, shutterOpen, shutterEnd); ray->medium = medium; *ray = cameraToWorld(*ray); return 1.0; } PerspectiveCamera *CreatePerspectiveCamera(const ParamSet &params, const Transform &cam2world, Film *film, const Medium *medium) { // Extract common camera parameters from _ParamSet_ Float shutteropen = params.FindOneFloat("shutteropen", 0.f); Float shutterclose = params.FindOneFloat("shutterclose", 1.f); if (shutterclose < shutteropen) { std::swap(shutterclose, shutteropen); } Float lensradius = params.FindOneFloat("lensradius", 0.f); Float focaldistance = params.FindOneFloat("focaldistance", 1e6); Float frame = params.FindOneFloat("frameaspectratio",Float(film->fullResolution.x) / Float(film->fullResolution.y)); Bound2f screen; if (frame > 1.f) { screen.minPoint.x = -frame; screen.maxPoint.x = frame; screen.minPoint.y = -1.0f; screen.maxPoint.y = 1.0f; } else { screen.minPoint.x = -1.0f; screen.maxPoint.x = 1.0f; screen.minPoint.y = -1.0f / frame; screen.maxPoint.y = 1.0f / frame; } int swi; const Float *sw = params.FindFloat("screenwindow", &swi); if (sw) { if (swi == 4) { screen.minPoint.x = sw[0]; screen.maxPoint.x = sw[1]; screen.minPoint.y = sw[2]; screen.maxPoint.y = sw[3]; } else Error("\"screenwindow\" should have four values"); } Float fov = params.FindOneFloat("fov", 90.0); Float halffov = params.FindOneFloat("halffov", -1.0f); if (halffov > 0.0f){ fov = 2.0f * halffov; } return new PerspectiveCamera(cam2world, screen, shutteropen, shutterclose, lensradius, focaldistance, fov,film, medium); } <commit_msg>修正错把空间点当成向量来操作,导致差分计算有误的BUG<commit_after>/* * perspective.cpp * * Created on: 2016年12月23日 * Author: zhuqian */ #include "raiden.h" #include "perspective.h" #include "sampling.h" #include "paramset.h" #include "film.h" PerspectiveCamera::PerspectiveCamera(const Transform& c2w, const Bound2f& screenWindow, Float shutterOpen, Float shutterEnd, Float lensr, Float focald, Float fov,Film * f, const Medium* medium) : ProjectiveCamera(c2w, Perspective(fov, 1e-3f, 1000.0f)/*c2s*/, screenWindow, shutterOpen, shutterEnd, lensr, focald,f,medium) { //获得光栅化空间下,相机空间对应的差分 _dxCamera = _rasterToCamera(Point3f(1, 0, 0)) - _rasterToCamera(Point3f(0, 0, 0)); _dyCamera = _rasterToCamera(Point3f(0, 1, 0)) - _rasterToCamera(Point3f(0, 0, 0)); } Float PerspectiveCamera::GenerateRay(const CameraSample &sample, Ray *ray) const { Point3f pRas = Point3f(sample.pFilm.x, sample.pFilm.y, 0.0f); Point3f pCam = _rasterToCamera(pRas); //计算相机空间下的image panel样本值 *ray = Ray(Point3f(0,0,0), Normalize(Vector3f(pCam))); if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算焦距平面交点 //其实这的z就是1 Float ft = _focalDistance / ray->d.z; Point3f pFocus = (*ray)(ft); //原点设置成来自镜面 ray->o = Point3f(lens.x, lens.y, 0); ray->d = Normalize(pFocus - ray->o); } ray->time = Lerp(sample.time, shutterOpen, shutterEnd); Info(medium); ray->medium = medium; *ray = cameraToWorld(*ray); return 1.0f; } Float PerspectiveCamera::GenerateRayDifferential(const CameraSample &sample, RayDifferential *ray) const { Point3f pRas = Point3f(sample.pFilm.x, sample.pFilm.y, 0.0f); Point3f pCam = _rasterToCamera(pRas); //计算相机空间下的image panel样本值 *ray = RayDifferential(Point3f(0,0,0), Normalize(Vector3f(pCam))); if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算焦距平面交点 //其实这的z就是1 Float ft = _focalDistance / ray->d.z; Point3f pFocus = (*ray)(ft); //原点设置成来自镜面 ray->o = Point3f(lens.x, lens.y, 0); ray->d = Normalize(pFocus - ray->o); } //处理微分信息 if (_lensRadius > 0.0f) { Point2f lens = ConcentricSampleDisk(sample.pLen) * _lensRadius; //采样Lens //计算x射线 Vector3f dx = Normalize(Vector3f(pCam) + _dxCamera); Float ft = _focalDistance / dx.z; Point3f pFocusX = Point3f(0, 0, 0) + (ft * dx); ray->ox = Point3f(lens.x, lens.y, 0); ray->dx = Normalize(pFocusX - ray->ox); //计算y射线 Vector3f dy = Normalize(Vector3f(pCam) + _dyCamera); ft = _focalDistance / dy.z; Point3f pFocusY = Point3f(0, 0, 0) + (ft * dy); ray->oy = Point3f(lens.x, lens.y, 0); ray->dy = Normalize(pFocusY - ray->oy); } else { //镜片为奇点的情况 ray->ox=ray->oy=ray->o; ray->dx = Normalize(Vector3f(pCam)+_dxCamera); ray->dy = Normalize(Vector3f(pCam)+_dyCamera); } ray->hasDifferential = true; ray->time = Lerp(sample.time, shutterOpen, shutterEnd); ray->medium = medium; *ray = cameraToWorld(*ray); return 1.0; } PerspectiveCamera *CreatePerspectiveCamera(const ParamSet &params, const Transform &cam2world, Film *film, const Medium *medium) { // Extract common camera parameters from _ParamSet_ Float shutteropen = params.FindOneFloat("shutteropen", 0.f); Float shutterclose = params.FindOneFloat("shutterclose", 1.f); if (shutterclose < shutteropen) { std::swap(shutterclose, shutteropen); } Float lensradius = params.FindOneFloat("lensradius", 0.f); Float focaldistance = params.FindOneFloat("focaldistance", 1e6); Float frame = params.FindOneFloat("frameaspectratio",Float(film->fullResolution.x) / Float(film->fullResolution.y)); Bound2f screen; if (frame > 1.f) { screen.minPoint.x = -frame; screen.maxPoint.x = frame; screen.minPoint.y = -1.0f; screen.maxPoint.y = 1.0f; } else { screen.minPoint.x = -1.0f; screen.maxPoint.x = 1.0f; screen.minPoint.y = -1.0f / frame; screen.maxPoint.y = 1.0f / frame; } int swi; const Float *sw = params.FindFloat("screenwindow", &swi); if (sw) { if (swi == 4) { screen.minPoint.x = sw[0]; screen.maxPoint.x = sw[1]; screen.minPoint.y = sw[2]; screen.maxPoint.y = sw[3]; } else Error("\"screenwindow\" should have four values"); } Float fov = params.FindOneFloat("fov", 90.0); Float halffov = params.FindOneFloat("halffov", -1.0f); if (halffov > 0.0f){ fov = 2.0f * halffov; } return new PerspectiveCamera(cam2world, screen, shutteropen, shutterclose, lensradius, focaldistance, fov,film, medium); } <|endoftext|>
<commit_before><commit_msg>fix travis<commit_after>float sum(float a, float b) { return a+b; } <|endoftext|>
<commit_before>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2014, Cauldron Development LLC Copyright (c) 2003-2014, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "JSONAPI.h" #include <cbang/String.h> #include <cbang/log/Logger.h> #include <cbang/json/JSON.h> #include <cbang/json/List.h> #include <cbang/http/WebContext.h> #include <cbang/http/Connection.h> #include <cbang/http/StatusCode.h> using namespace cb; using namespace cb::JSAPI; using namespace std; void JSONAPI::add(const string &cmd, const SmartPointer<Handler> &handler) { if (!api.insert(api_t::value_type(cmd, handler)).second) THROWS("'" << root << cmd << "' already exists in JSON API"); } bool JSONAPI::handlePage(HTTP::WebContext &ctx, ostream &stream, const URI &uri) { if (!String::startsWith(uri.getPath(), root)) return false; string cmd = uri.getPath().substr(root.length()); // Look up command api_t::const_iterator it = api.find(cmd); if (it == api.end()) return false; ctx.setDynamic(); // Don't cache HTTP::Connection &con = ctx.getConnection(); bool jsonp = !jsonpCB.empty() && uri.has(jsonpCB); if (jsonp) { con.getResponse().setContentType("application/javascript"); con << uri.get(jsonpCB) << '('; } else con.getResponse().setContentType("application/json"); JSON::Writer writer(con, 0, !uri.has("pretty"), uri.has("python_mode") ? JSON::Writer::PYTHON_MODE : JSON::Writer::JSON_MODE); try { // Parse JSON data JSON::ValuePtr msg; if (con.getRequest().hasContentType() && String::startsWith(con.getRequest().getContentType(), "application/json")) { MemoryBuffer &payload = con.getPayload(); if (payload.getFill()) msg = JSON::Reader(payload).parse(); } else if (!uri.empty()) { msg = new JSON::Dict; for (URI::const_iterator it = uri.begin(); it != uri.end(); it++) msg->insert(it->first, it->second); } // Dispatch API command if (msg.isNull()) LOG_DEBUG(5, "JSONAPI Call: " << cmd << "()"); else LOG_DEBUG(5, "JSONAPI Call: " << cmd << '(' << *msg << ')'); it->second->handle(ctx, cmd, msg, writer); // Make sure JSON stream is complete writer.close(); } catch (const Exception &e) { LOG_DEBUG(5, e); // Clear possibly partial or invalid response con.clearResponseBuffer(); // jsonp header if (jsonp) con << uri.get(jsonpCB) << '('; // Send error message JSON::Writer writer(con, 0, true); writer.beginList(); writer.append("error"); writer.append(e.getMessage()); writer.endList(); writer.close(); } if (jsonp) con << ");"; return true; } <commit_msg>Print full error in JSON API<commit_after>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2014, Cauldron Development LLC Copyright (c) 2003-2014, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "JSONAPI.h" #include <cbang/String.h> #include <cbang/log/Logger.h> #include <cbang/json/JSON.h> #include <cbang/json/List.h> #include <cbang/http/WebContext.h> #include <cbang/http/Connection.h> #include <cbang/http/StatusCode.h> using namespace cb; using namespace cb::JSAPI; using namespace std; void JSONAPI::add(const string &cmd, const SmartPointer<Handler> &handler) { if (!api.insert(api_t::value_type(cmd, handler)).second) THROWS("'" << root << cmd << "' already exists in JSON API"); } bool JSONAPI::handlePage(HTTP::WebContext &ctx, ostream &stream, const URI &uri) { if (!String::startsWith(uri.getPath(), root)) return false; string cmd = uri.getPath().substr(root.length()); // Look up command api_t::const_iterator it = api.find(cmd); if (it == api.end()) return false; ctx.setDynamic(); // Don't cache HTTP::Connection &con = ctx.getConnection(); bool jsonp = !jsonpCB.empty() && uri.has(jsonpCB); if (jsonp) { con.getResponse().setContentType("application/javascript"); con << uri.get(jsonpCB) << '('; } else con.getResponse().setContentType("application/json"); JSON::Writer writer(con, 0, !uri.has("pretty"), uri.has("python_mode") ? JSON::Writer::PYTHON_MODE : JSON::Writer::JSON_MODE); try { // Parse JSON data JSON::ValuePtr msg; if (con.getRequest().hasContentType() && String::startsWith(con.getRequest().getContentType(), "application/json")) { MemoryBuffer &payload = con.getPayload(); if (payload.getFill()) msg = JSON::Reader(payload).parse(); } else if (!uri.empty()) { msg = new JSON::Dict; for (URI::const_iterator it = uri.begin(); it != uri.end(); it++) msg->insert(it->first, it->second); } // Dispatch API command if (msg.isNull()) LOG_DEBUG(5, "JSONAPI Call: " << cmd << "()"); else LOG_DEBUG(5, "JSONAPI Call: " << cmd << '(' << *msg << ')'); it->second->handle(ctx, cmd, msg, writer); // Make sure JSON stream is complete writer.close(); } catch (const Exception &e) { LOG_ERROR(e); // Clear possibly partial or invalid response con.clearResponseBuffer(); // jsonp header if (jsonp) con << uri.get(jsonpCB) << '('; // Send error message JSON::Writer writer(con, 0, true); writer.beginList(); writer.append("error"); writer.append(e.getMessage()); writer.endList(); writer.close(); } if (jsonp) con << ");"; return true; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // imgui-d3d11.cc // Dear ImGui integration sample with D3D11 backend. //------------------------------------------------------------------------------ #include "d3d11entry.h" #define SOKOL_IMPL #define SOKOL_D3D11 #define SOKOL_D3D11_SHADER_COMPILER #define SOKOL_LOG(s) OutputDebugStringA(s) #include "sokol_gfx.h" #include "sokol_time.h" #include "imgui.h" static const int Width = 1024; static const int Height = 768; static const int MaxVertices = (1<<16); static const int MaxIndices = MaxVertices * 3; static uint64_t last_time = 0; static bool show_test_window = true; static bool show_another_window = false; static sg_pipeline pip; static sg_bindings bind; static sg_pass_action pass_action; typedef struct { ImVec2 disp_size; } vs_params_t; static void imgui_draw_cb(ImDrawData*); int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { // setup d3d11 app wrapper, sokol_gfx, sokol_time d3d11_init(Width, Height, 1, L"Sokol Dear ImGui D3D11"); sg_desc desc = { }; desc.d3d11_device = d3d11_device(); desc.d3d11_device_context = d3d11_device_context(); desc.d3d11_render_target_view_cb = d3d11_render_target_view; desc.d3d11_depth_stencil_view_cb = d3d11_depth_stencil_view; sg_setup(&desc); stm_setup(); // input forwarding d3d11_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); d3d11_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); d3d11_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); d3d11_mouse_wheel([](float v) { ImGui::GetIO().MouseWheel = v; }); d3d11_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); d3d11_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); d3d11_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); // setup Dear Imgui ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.RenderDrawListsFn = imgui_draw_cb; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = VK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; io.KeyMap[ImGuiKey_Home] = VK_HOME; io.KeyMap[ImGuiKey_End] = VK_END; io.KeyMap[ImGuiKey_Delete] = VK_DELETE; io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; // dynamic vertex- and index-buffers for imgui-generated geometry sg_buffer_desc vbuf_desc = { }; vbuf_desc.usage = SG_USAGE_STREAM; vbuf_desc.size = MaxVertices * sizeof(ImDrawVert); bind.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { }; ibuf_desc.type = SG_BUFFERTYPE_INDEXBUFFER; ibuf_desc.usage = SG_USAGE_STREAM; ibuf_desc.size = MaxIndices * sizeof(ImDrawIdx); bind.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for imgui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { }; img_desc.width = font_width; img_desc.height = font_height; img_desc.pixel_format = SG_PIXELFORMAT_RGBA8; img_desc.wrap_u = SG_WRAP_CLAMP_TO_EDGE; img_desc.wrap_v = SG_WRAP_CLAMP_TO_EDGE; img_desc.content.subimage[0][0].ptr = font_pixels; img_desc.content.subimage[0][0].size = font_width * font_height * 4; bind.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui rendering sg_shader_desc shd_desc = { }; auto& ub = shd_desc.vs.uniform_blocks[0]; ub.size = sizeof(vs_params_t); shd_desc.vs.source = "cbuffer params {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos: POSITION;\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" "};\n" "struct vs_out {\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" " float4 pos: SV_Position;\n" "};\n" "vs_out main(vs_in inp) {\n" " vs_out outp;\n" " outp.pos = float4(((inp.pos/disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " outp.uv = inp.uv;\n" " outp.color = inp.color;\n" " return outp;\n" "}\n"; shd_desc.fs.images[0].type = SG_IMAGETYPE_2D; shd_desc.fs.source = "Texture2D<float4> tex: register(t0);\n" "sampler smp: register(s0);\n" "float4 main(float2 uv: TEXCOORD0, float4 color: COLOR0): SV_Target0 {\n" " return tex.Sample(smp, uv) * color;\n" "}\n"; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { }; pip_desc.layout.buffers[0].stride = sizeof(ImDrawVert); auto& attrs = pip_desc.layout.attrs; attrs[0].sem_name="POSITION"; attrs[0].offset=offsetof(ImDrawVert, pos); attrs[0].format=SG_VERTEXFORMAT_FLOAT2; attrs[1].sem_name="TEXCOORD"; attrs[1].offset=offsetof(ImDrawVert, uv); attrs[1].format=SG_VERTEXFORMAT_FLOAT2; attrs[2].sem_name="COLOR"; attrs[2].offset=offsetof(ImDrawVert, col); attrs[2].format=SG_VERTEXFORMAT_UBYTE4N; pip_desc.shader = shd; pip_desc.index_type = SG_INDEXTYPE_UINT16; pip_desc.blend.enabled = true; pip_desc.blend.src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA; pip_desc.blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; pip_desc.blend.color_write_mask = SG_COLORMASK_RGB; pip = sg_make_pipeline(&pip_desc); // initial clear color pass_action.colors[0].action = SG_ACTION_CLEAR; pass_action.colors[0].val[0] = 0.0f; pass_action.colors[0].val[1] = 0.5f; pass_action.colors[0].val[2] = 0.7f; pass_action.colors[0].val[3] = 1.0f; // draw loop while (d3d11_process_events()) { const int cur_width = d3d11_width(); const int cur_height = d3d11_height(); // this is standard ImGui demo code ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(float(cur_width), float(cur_height)); io.DeltaTime = (float) stm_sec(stm_laptime(&last_time)); ImGui::NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", &pass_action.colors[0].val[0]); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(); } // the sokol_gfx draw pass sg_begin_default_pass(&pass_action, cur_width, cur_height); ImGui::Render(); sg_end_pass(); sg_commit(); d3d11_present(); } ImGui::DestroyContext(); sg_shutdown(); d3d11_shutdown(); } // imgui draw callback void imgui_draw_cb(ImDrawData* draw_data) { assert(draw_data); if (draw_data->CmdListsCount == 0) { return; } // render the command list vs_params_t vs_params; vs_params.disp_size.x = ImGui::GetIO().DisplaySize.x; vs_params.disp_size.y = ImGui::GetIO().DisplaySize.y; sg_apply_pipeline(pip); sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); for (int cl_index = 0; cl_index < draw_data->CmdListsCount; cl_index++) { const ImDrawList* cl = draw_data->CmdLists[cl_index]; // append vertices and indices to buffers, record start offsets in bindings struct const int vtx_size = cl->VtxBuffer.size() * sizeof(ImDrawVert); const int idx_size = cl->IdxBuffer.size() * sizeof(ImDrawIdx); const int vb_offset = sg_append_buffer(bind.vertex_buffers[0], &cl->VtxBuffer.front(), vtx_size); const int ib_offset = sg_append_buffer(bind.index_buffer, &cl->IdxBuffer.front(), idx_size); /* don't render anything if the buffer is in overflow state (this is also checked internally in sokol_gfx, draw calls that attempt from overflowed buffers will be silently dropped) */ if (sg_query_buffer_overflow(bind.vertex_buffers[0]) || sg_query_buffer_overflow(bind.index_buffer)) { continue; } bind.vertex_buffer_offsets[0] = vb_offset; bind.index_buffer_offset = ib_offset; sg_apply_bindings(&bind); int base_element = 0; for (const ImDrawCmd& pcmd : cl->CmdBuffer) { if (pcmd.UserCallback) { pcmd.UserCallback(cl, &pcmd); } else { const int scissor_x = (int) (pcmd.ClipRect.x); const int scissor_y = (int) (pcmd.ClipRect.y); const int scissor_w = (int) (pcmd.ClipRect.z - pcmd.ClipRect.x); const int scissor_h = (int) (pcmd.ClipRect.w - pcmd.ClipRect.y); sg_apply_scissor_rect(scissor_x, scissor_y, scissor_w, scissor_h, true); sg_draw(base_element, pcmd.ElemCount, 1); } base_element += pcmd.ElemCount; } } } <commit_msg>remove the ImGui draw callback from the D3D11 ImGui sample<commit_after>//------------------------------------------------------------------------------ // imgui-d3d11.cc // Dear ImGui integration sample with D3D11 backend. //------------------------------------------------------------------------------ #include "d3d11entry.h" #define SOKOL_IMPL #define SOKOL_D3D11 #define SOKOL_D3D11_SHADER_COMPILER #define SOKOL_LOG(s) OutputDebugStringA(s) #include "sokol_gfx.h" #include "sokol_time.h" #include "imgui.h" static const int Width = 1024; static const int Height = 768; static const int MaxVertices = (1<<16); static const int MaxIndices = MaxVertices * 3; static uint64_t last_time = 0; static bool show_test_window = true; static bool show_another_window = false; static sg_pipeline pip; static sg_bindings bind; static sg_pass_action pass_action; typedef struct { ImVec2 disp_size; } vs_params_t; static void draw_imgui(ImDrawData*); int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { // setup d3d11 app wrapper, sokol_gfx, sokol_time d3d11_init(Width, Height, 1, L"Sokol Dear ImGui D3D11"); sg_desc desc = { }; desc.d3d11_device = d3d11_device(); desc.d3d11_device_context = d3d11_device_context(); desc.d3d11_render_target_view_cb = d3d11_render_target_view; desc.d3d11_depth_stencil_view_cb = d3d11_depth_stencil_view; sg_setup(&desc); stm_setup(); // input forwarding d3d11_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); d3d11_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); d3d11_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); d3d11_mouse_wheel([](float v) { ImGui::GetIO().MouseWheel = v; }); d3d11_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); d3d11_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); d3d11_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); // setup Dear Imgui ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = VK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; io.KeyMap[ImGuiKey_Home] = VK_HOME; io.KeyMap[ImGuiKey_End] = VK_END; io.KeyMap[ImGuiKey_Delete] = VK_DELETE; io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; // dynamic vertex- and index-buffers for imgui-generated geometry sg_buffer_desc vbuf_desc = { }; vbuf_desc.usage = SG_USAGE_STREAM; vbuf_desc.size = MaxVertices * sizeof(ImDrawVert); bind.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { }; ibuf_desc.type = SG_BUFFERTYPE_INDEXBUFFER; ibuf_desc.usage = SG_USAGE_STREAM; ibuf_desc.size = MaxIndices * sizeof(ImDrawIdx); bind.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for imgui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { }; img_desc.width = font_width; img_desc.height = font_height; img_desc.pixel_format = SG_PIXELFORMAT_RGBA8; img_desc.wrap_u = SG_WRAP_CLAMP_TO_EDGE; img_desc.wrap_v = SG_WRAP_CLAMP_TO_EDGE; img_desc.content.subimage[0][0].ptr = font_pixels; img_desc.content.subimage[0][0].size = font_width * font_height * 4; bind.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui rendering sg_shader_desc shd_desc = { }; auto& ub = shd_desc.vs.uniform_blocks[0]; ub.size = sizeof(vs_params_t); shd_desc.vs.source = "cbuffer params {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos: POSITION;\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" "};\n" "struct vs_out {\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" " float4 pos: SV_Position;\n" "};\n" "vs_out main(vs_in inp) {\n" " vs_out outp;\n" " outp.pos = float4(((inp.pos/disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " outp.uv = inp.uv;\n" " outp.color = inp.color;\n" " return outp;\n" "}\n"; shd_desc.fs.images[0].type = SG_IMAGETYPE_2D; shd_desc.fs.source = "Texture2D<float4> tex: register(t0);\n" "sampler smp: register(s0);\n" "float4 main(float2 uv: TEXCOORD0, float4 color: COLOR0): SV_Target0 {\n" " return tex.Sample(smp, uv) * color;\n" "}\n"; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { }; pip_desc.layout.buffers[0].stride = sizeof(ImDrawVert); auto& attrs = pip_desc.layout.attrs; attrs[0].sem_name="POSITION"; attrs[0].offset=offsetof(ImDrawVert, pos); attrs[0].format=SG_VERTEXFORMAT_FLOAT2; attrs[1].sem_name="TEXCOORD"; attrs[1].offset=offsetof(ImDrawVert, uv); attrs[1].format=SG_VERTEXFORMAT_FLOAT2; attrs[2].sem_name="COLOR"; attrs[2].offset=offsetof(ImDrawVert, col); attrs[2].format=SG_VERTEXFORMAT_UBYTE4N; pip_desc.shader = shd; pip_desc.index_type = SG_INDEXTYPE_UINT16; pip_desc.blend.enabled = true; pip_desc.blend.src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA; pip_desc.blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; pip_desc.blend.color_write_mask = SG_COLORMASK_RGB; pip = sg_make_pipeline(&pip_desc); // initial clear color pass_action.colors[0].action = SG_ACTION_CLEAR; pass_action.colors[0].val[0] = 0.0f; pass_action.colors[0].val[1] = 0.5f; pass_action.colors[0].val[2] = 0.7f; pass_action.colors[0].val[3] = 1.0f; // draw loop while (d3d11_process_events()) { const int cur_width = d3d11_width(); const int cur_height = d3d11_height(); // this is standard ImGui demo code ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(float(cur_width), float(cur_height)); io.DeltaTime = (float) stm_sec(stm_laptime(&last_time)); ImGui::NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", &pass_action.colors[0].val[0]); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(); } // the sokol_gfx draw pass sg_begin_default_pass(&pass_action, cur_width, cur_height); ImGui::Render(); draw_imgui(ImGui::GetDrawData()); sg_end_pass(); sg_commit(); d3d11_present(); } ImGui::DestroyContext(); sg_shutdown(); d3d11_shutdown(); } // render ImGui draw lists through sokol-gfx void draw_imgui(ImDrawData* draw_data) { assert(draw_data); if (draw_data->CmdListsCount == 0) { return; } // render the command list vs_params_t vs_params; vs_params.disp_size.x = ImGui::GetIO().DisplaySize.x; vs_params.disp_size.y = ImGui::GetIO().DisplaySize.y; sg_apply_pipeline(pip); sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); for (int cl_index = 0; cl_index < draw_data->CmdListsCount; cl_index++) { const ImDrawList* cl = draw_data->CmdLists[cl_index]; // append vertices and indices to buffers, record start offsets in bindings struct const int vtx_size = cl->VtxBuffer.size() * sizeof(ImDrawVert); const int idx_size = cl->IdxBuffer.size() * sizeof(ImDrawIdx); const int vb_offset = sg_append_buffer(bind.vertex_buffers[0], &cl->VtxBuffer.front(), vtx_size); const int ib_offset = sg_append_buffer(bind.index_buffer, &cl->IdxBuffer.front(), idx_size); /* don't render anything if the buffer is in overflow state (this is also checked internally in sokol_gfx, draw calls that attempt from overflowed buffers will be silently dropped) */ if (sg_query_buffer_overflow(bind.vertex_buffers[0]) || sg_query_buffer_overflow(bind.index_buffer)) { continue; } bind.vertex_buffer_offsets[0] = vb_offset; bind.index_buffer_offset = ib_offset; sg_apply_bindings(&bind); int base_element = 0; for (const ImDrawCmd& pcmd : cl->CmdBuffer) { if (pcmd.UserCallback) { pcmd.UserCallback(cl, &pcmd); } else { const int scissor_x = (int) (pcmd.ClipRect.x); const int scissor_y = (int) (pcmd.ClipRect.y); const int scissor_w = (int) (pcmd.ClipRect.z - pcmd.ClipRect.x); const int scissor_h = (int) (pcmd.ClipRect.w - pcmd.ClipRect.y); sg_apply_scissor_rect(scissor_x, scissor_y, scissor_w, scissor_h, true); sg_draw(base_element, pcmd.ElemCount, 1); } base_element += pcmd.ElemCount; } } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX メイン @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cmath> #include "main.hpp" #include "rx/rx63x/system.hpp" #include "rx/rx63x/port.hpp" #include "rx/rx63x/mpc.hpp" #include "rx/cmt_io.hpp" #include "rx/sci_io.hpp" #include "rx/gpt_io.hpp" #include "rx/adc_io.hpp" #include "rx/chout.hpp" #include "inv_monitor.hpp" namespace root { device::cmt_io<device::CMT0> cmt_; device::sci_io<device::SCI1, 256, 256> sci_; device::gpt_io<device::GPT0> gpt_; device::adc_io<device::S12AD> adc_; utils::chout chout_; utils::inv_monitor monitor_; } //-----------------------------------------------------------------// /*! @brief SCI 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void sci_putch(char ch) { root::sci_.putch(ch); } //-----------------------------------------------------------------// /*! @brief SCI 文字列出力 @param[in] str 文字列 */ //-----------------------------------------------------------------// void sci_puts(const char *str) { root::sci_.puts(str); } //-----------------------------------------------------------------// /*! @brief SCI 文字入力 @return 文字コード */ //-----------------------------------------------------------------// char sci_getch(void) { return root::sci_.getch(); } //-----------------------------------------------------------------// /*! @brief SCI 文字入力数を取得 @return 入力文字数 */ //-----------------------------------------------------------------// uint32_t sci_length(void) { return root::sci_.length(); } //-----------------------------------------------------------------// /*! @brief 10ms 単位タイマー */ //-----------------------------------------------------------------// void delay_10ms(uint32_t n) { while(n > 0) { root::cmt_.sync(); --n; } } void prn_voltage_(const char* info, int32_t v) { int32_t vv = v * 15 * 100 / 4096; int32_t mod = vv % 100; if(mod < 0) mod = -mod; root::chout_.suppress_char(' '); root::chout_.set_length(0); root::chout_ << info << (vv / 100) << '.'; root::chout_.suppress_char('0'); root::chout_.set_length(2); root::chout_ << mod << utils::chout::endl; } void prn_value_(const char* info, int32_t v) { root::chout_.suppress_char(' '); root::chout_.set_length(0); root::chout_ << info << v << utils::chout::endl; } static volatile uint8_t dummy_; static void wait_() { // とりあえず無駄ループ for(uint32_t i = 0; i < 5000; ++i) { i += dummy_ & 0; } } int main(int argc, char** argv); int main(int argc, char** argv) { using namespace root; device::SYSTEM::PRCR = 0xa503; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR.MSTS = 0b01101; // 131072 サイクル待ち device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 dummy_ = device::SYSTEM::MOSCCR.MOSTP(); device::SYSTEM::MOFCR.MOFXIN = 1; // メインクロック強制発振 dummy_ = device::SYSTEM::MOFCR.MOFXIN(); wait_(); device::SYSTEM::PLLCR.STC = 0xf; // PLL 16 倍(192MHz) device::SYSTEM::PLLWTCR.PSTS = 0b01010; // 131072 サイクル待ち device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 wait_(); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(3) // 1/8 (192/8=24) | device::SYSTEM::SCKCR.ICK.b(1) // 1/2 (192/2=96) | device::SYSTEM::SCKCR.BCK.b(2) // 1/4 (192/4=48) | device::SYSTEM::SCKCR.PCKA.b(1) // 1/2 (192/2=96) | device::SYSTEM::SCKCR.PCKB.b(2) // 1/4 (192/4=48) | device::SYSTEM::SCKCR.PCKC.b(2) // 1/4 (192/8=48) | device::SYSTEM::SCKCR.PCKD.b(2); // 1/4 (192/8=48) device::SYSTEM::SCKCR3.CKSEL = 4; ///< PLL 回路選択 // Signal LED 出力設定 device::PORTB::PDR.B7 = 1; // PORTB:B7 output device::PORTB::PODR.B7 = 1; // LED Off // SCI1 の初期化(PD5:RXD1:input, PD3:TXD1:output) device::PORTD::PDR.B3 = 1; device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::PD3PFS.PSEL = 0b01010; // TXD1 設定 device::MPC::PD5PFS.PSEL = 0b01010; // RXD1 設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 device::PORTD::PMR.B3 = 1; device::PORTD::PMR.B5 = 1; static const uint8_t sci_irq_level = 1; sci_.initialize(sci_irq_level); sci_.start(115200); // GPT0 設定 (GTIOC0A: P71:38, PD7:12)(GTIOC0B: P74:35, PD6:13) device::PORT7::PDR.B1 = 1; // output device::SYSTEM::MSTPCRA.MSTPA7 = 0; // GPT0..3 モジュール有効 device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::P71PFS.PSEL = 0b0110; // GTIOC0A 設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 device::PORT7::PMR.B1 = 1; gpt_.start(); // PWM start gpt_.set_r(512 - 1); gpt_.set_a(256); // S12AD 設定 P40(56), P41(55), P42(54) device::SYSTEM::MSTPCRA.MSTPA17 = 0; // S12AD モジュール有効 device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::P40PFS.ASEL = 1; // アナログ入力設定 device::MPC::P41PFS.ASEL = 1; // アナログ入力設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 // タイマー設定 cmt_.set_clock(F_PCKB); uint8_t cmt_irq_level = 3; cmt_.initialize(93750, cmt_irq_level); cmt_.sync(); monitor_.initialize(); /// device::SYSTEM::PRCR = 0xa500; ///< クロック、低消費電力、関係書き込み禁止 for(int i = 0; i < 10; ++i) { adc_.start(0b00000111); cmt_.sync(); adc_.sync(); int32_t v = static_cast<int32_t>(adc_.get(0)); prn_value_("Ch0: ", v); } uint32_t cnt = 0; uint32_t led = 0; int32_t ds = 0; int32_t ref = 300; int32_t val = 0; int32_t low_limit = 10; // 0.23V at 12V input int32_t high_limit = 500; // 11.72V at 12V input int32_t cpv = low_limit; bool up = true; while(1) { adc_.start(0b00000111); cmt_.sync(); // A/D 変換開始 adc_.sync(); device::PORTB::PODR.B7 = 0; // LED On int32_t ref = static_cast<int32_t>(adc_.get(0)); // 指令電圧 int32_t out = static_cast<int32_t>(adc_.get(1)); // 出力電圧 int32_t inp = static_cast<int32_t>(adc_.get(2)); // 入力電圧 // int32_t gain = static_cast<int32_t>(adc_.get(0)); int32_t gain = 130; // 三角波 #if 0 if(up) { ref += 1; } else { ref -= 1; } if(ref > 1700) { up = false; ref = 1700; } else if(ref < 200) { up = true; ref = 200; } #endif int32_t dif = ref - out; // 誤差 // PWM の制御量に対するスレッショルド int32_t d = dif * gain / inp; val += d; cpv = val / 8; // 出力リミッター if(cpv < low_limit) cpv = low_limit; else if(cpv > high_limit) cpv = high_limit; gpt_.set_a(cpv); uint16_t ofs = (512 - cpv) / 4; gpt_.set_ad_a(cpv + ofs); // A/D 変換開始タイミング device::PORTB::PODR.B7 = 1; // LED Off #if 0 monitor_.service(); ++cnt; if(cnt >= 1000) { cnt = 0; prn_voltage_("Inp: ", inp); prn_voltage_("Ref: ", ref); prn_voltage_("Dif: ", dif); prn_voltage_("Out: ", out); prn_value_("PWM: ", cpv); } #endif #if 0 ++led; if(led >= 700) led = 0; if(led < 350) { device::PORTB::PODR.B7 = 1; // LED Off } else { device::PORTB::PODR.B7 = 0; // LED On } #endif } } <commit_msg>update comment<commit_after>//=====================================================================// /*! @file @brief RX メイン @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cmath> #include "main.hpp" #include "rx/rx63x/system.hpp" #include "rx/rx63x/port.hpp" #include "rx/rx63x/mpc.hpp" #include "rx/cmt_io.hpp" #include "rx/sci_io.hpp" #include "rx/gpt_io.hpp" #include "rx/adc_io.hpp" #include "rx/chout.hpp" #include "inv_monitor.hpp" namespace root { device::cmt_io<device::CMT0> cmt_; device::sci_io<device::SCI1, 256, 256> sci_; device::gpt_io<device::GPT0> gpt_; device::adc_io<device::S12AD> adc_; utils::chout chout_; utils::inv_monitor monitor_; } //-----------------------------------------------------------------// /*! @brief SCI 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void sci_putch(char ch) { root::sci_.putch(ch); } //-----------------------------------------------------------------// /*! @brief SCI 文字列出力 @param[in] str 文字列 */ //-----------------------------------------------------------------// void sci_puts(const char *str) { root::sci_.puts(str); } //-----------------------------------------------------------------// /*! @brief SCI 文字入力 @return 文字コード */ //-----------------------------------------------------------------// char sci_getch(void) { return root::sci_.getch(); } //-----------------------------------------------------------------// /*! @brief SCI 文字入力数を取得 @return 入力文字数 */ //-----------------------------------------------------------------// uint32_t sci_length(void) { return root::sci_.length(); } //-----------------------------------------------------------------// /*! @brief 10ms 単位タイマー */ //-----------------------------------------------------------------// void delay_10ms(uint32_t n) { while(n > 0) { root::cmt_.sync(); --n; } } void prn_voltage_(const char* info, int32_t v) { int32_t vv = v * 15 * 100 / 4096; int32_t mod = vv % 100; if(mod < 0) mod = -mod; root::chout_.suppress_char(' '); root::chout_.set_length(0); root::chout_ << info << (vv / 100) << '.'; root::chout_.suppress_char('0'); root::chout_.set_length(2); root::chout_ << mod << utils::chout::endl; } void prn_value_(const char* info, int32_t v) { root::chout_.suppress_char(' '); root::chout_.set_length(0); root::chout_ << info << v << utils::chout::endl; } static volatile uint8_t dummy_; static void wait_() { // とりあえず無駄ループ for(uint32_t i = 0; i < 5000; ++i) { i += dummy_ & 0; } } int main(int argc, char** argv); int main(int argc, char** argv) { using namespace root; device::SYSTEM::PRCR = 0xa503; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR.MSTS = 0b01101; // 131072 サイクル待ち device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 dummy_ = device::SYSTEM::MOSCCR.MOSTP(); device::SYSTEM::MOFCR.MOFXIN = 1; // メインクロック強制発振 dummy_ = device::SYSTEM::MOFCR.MOFXIN(); wait_(); device::SYSTEM::PLLCR.STC = 0xf; // PLL 16 倍(192MHz) device::SYSTEM::PLLWTCR.PSTS = 0b01010; // 131072 サイクル待ち device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 wait_(); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(3) // 1/8 (192/8=24) | device::SYSTEM::SCKCR.ICK.b(1) // 1/2 (192/2=96) | device::SYSTEM::SCKCR.BCK.b(2) // 1/4 (192/4=48) | device::SYSTEM::SCKCR.PCKA.b(1) // 1/2 (192/2=96) | device::SYSTEM::SCKCR.PCKB.b(2) // 1/4 (192/4=48) | device::SYSTEM::SCKCR.PCKC.b(2) // 1/4 (192/8=48) | device::SYSTEM::SCKCR.PCKD.b(2); // 1/4 (192/8=48) device::SYSTEM::SCKCR3.CKSEL = 4; ///< PLL 回路選択 // Signal LED 出力設定 device::PORTB::PDR.B7 = 1; // PORTB:B7 output device::PORTB::PODR.B7 = 1; // LED Off // SCI1 の初期化(PD5:RXD1:input, PD3:TXD1:output) device::PORTD::PDR.B3 = 1; device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::PD3PFS.PSEL = 0b01010; // TXD1 設定 device::MPC::PD5PFS.PSEL = 0b01010; // RXD1 設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 device::PORTD::PMR.B3 = 1; device::PORTD::PMR.B5 = 1; static const uint8_t sci_irq_level = 1; sci_.initialize(sci_irq_level); sci_.start(115200); // GPT0 設定 (GTIOC0A: P71:38, PD7:12)(GTIOC0B: P74:35, PD6:13) device::PORT7::PDR.B1 = 1; // output device::SYSTEM::MSTPCRA.MSTPA7 = 0; // GPT0..3 モジュール有効 device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::P71PFS.PSEL = 0b0110; // GTIOC0A 設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 device::PORT7::PMR.B1 = 1; gpt_.start(); // PWM start gpt_.set_r(512 - 1); gpt_.set_a(256); // S12AD 設定 P40(56), P41(55), P42(54) device::SYSTEM::MSTPCRA.MSTPA17 = 0; // S12AD モジュール有効 device::MPC::PWPR.B0WI = 0; // PWPR 書き込み許可 device::MPC::PWPR.PFSWE = 1; // PxxPFS 書き込み許可 device::MPC::P40PFS.ASEL = 1; // アナログ入力設定 device::MPC::P41PFS.ASEL = 1; // アナログ入力設定 device::MPC::PWPR = device::MPC::PWPR.B0WI.b(); // MPC 書き込み禁止 // タイマー設定 cmt_.set_clock(F_PCKB); uint8_t cmt_irq_level = 3; cmt_.initialize(93750, cmt_irq_level); cmt_.sync(); monitor_.initialize(); /// device::SYSTEM::PRCR = 0xa500; ///< クロック、低消費電力、関係書き込み禁止 for(int i = 0; i < 10; ++i) { adc_.start(0b00000111); cmt_.sync(); adc_.sync(); int32_t v = static_cast<int32_t>(adc_.get(0)); prn_value_("Ch0: ", v); } uint32_t cnt = 0; uint32_t led = 0; int32_t ds = 0; int32_t ref = 300; int32_t val = 0; int32_t low_limit = 10; // 0.23V at 12V input int32_t high_limit = 500; // 11.72V at 12V input int32_t cpv = low_limit; bool up = true; while(1) { adc_.start(0b00000111); cmt_.sync(); // A/D 変換開始 adc_.sync(); device::PORTB::PODR.B7 = 0; // LED On int32_t ref = static_cast<int32_t>(adc_.get(0)); // 指令電圧 int32_t out = static_cast<int32_t>(adc_.get(1)); // 出力電圧 int32_t inp = static_cast<int32_t>(adc_.get(2)); // 入力電圧 // int32_t gain = static_cast<int32_t>(adc_.get(0)); int32_t gain = 130; // 三角波 #if 0 if(up) { ref += 1; } else { ref -= 1; } if(ref > 1700) { up = false; ref = 1700; } else if(ref < 200) { up = true; ref = 200; } #endif int32_t dif = ref - out; // 誤差 // PWM の制御量に対するスレッショルド int32_t d = dif * gain / inp; val += d; cpv = val / 8; // 出力リミッター if(cpv < low_limit) cpv = low_limit; else if(cpv > high_limit) cpv = high_limit; gpt_.set_a(cpv); uint16_t ofs = (512 - cpv) / 4; gpt_.set_ad_a(cpv + ofs); // A/D 変換開始タイミング device::PORTB::PODR.B7 = 1; // LED Off #if 0 monitor_.service(); ++cnt; if(cnt >= 1000) { cnt = 0; prn_voltage_("Inp: ", inp); prn_voltage_("Ref: ", ref); prn_voltage_("Dif: ", dif); prn_voltage_("Out: ", out); prn_value_("PWM: ", cpv); } #endif #if 0 ++led; if(led >= 700) led = 0; if(led < 350) { device::PORTB::PODR.B7 = 1; // LED Off } else { device::PORTB::PODR.B7 = 0; // LED On } #endif } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014—2016 David Wicks, sansumbrella.com * 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. * * 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 * HOLDER 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. */ #pragma once #include <vector> #include "Phrase.hpp" #include "UnitBezier.h" #include "TimeType.h" namespace choreograph { class Curve { public: enum Type { Bezier, Hold, Linear }; float solve(float t) const; void setType(Type type) { _type = type; } void hold() { _type = Hold; } BezierInterpolant& bezier() { _type = Bezier; return _bezier; } private: Type _type = Linear; BezierInterpolant _bezier; }; float Curve::solve(float t) const { switch (_type) { case Bezier: return _bezier.solve(t); break; case Hold: return 0.0f; break; case Linear: return t; break; default: return t; break; } } /// /// Simple channel concept with bezier interpolation between keys. /// Goals: /// - Easy serialization /// - Easy to create graphical manipulation tools. /// - Support direct manipulation of animation data. /// - Avoid deeply nested information. Flat hierarchy. /// - Flexible enough to create an AfterEffects-style timeline. /// /// Good for animating single values, like floats or quaternions. /// For vector types, use a channel per component (and maybe add a group type to associate them). /// Grouping type could be a manipulator/animator type class that reads/writes multiple channels. /// template <typename T> class Channel { public: struct Key { Key(T value, Time time): value(value), time(time) {} T value; Time time; }; Channel() = default; /// Return the value of the channel at a given time. T value(Time at_time) const; /// Return the interpolated value between two keys. /// If you keep track of keys yourself, this is faster. T interpolatedValue(size_t curve_index, Time at_time) const; /// Returns the index of the starting key for the current time. /// The curve lies between two keys. size_t index(Time at_time) const; size_t lastIndex() const { return _keys.empty() ? 0 : _keys.size() - 1; } /// Append a key to the list of keys, positioned at \offset time after the previous key. Channel& appendKeyAfter(T value, Time offset) { if (! _keys.empty()) { _curves.emplace_back(); } _keys.emplace_back(value, duration() + offset); return *this; } /// Insert a key at the given time. Channel& insertKey(T value, Time at_time); Time duration() const { return _keys.empty() ? 0 : _keys.back().time; } const std::vector<Key>& keys() const { return _keys; } const std::vector<Curve>& curves() const { return _curves; } private: std::vector<Key> _keys; // may make polymorphic in future (like phrases are). Basically just an ease fn. // Compare std::function<float (float)> for max flexibility against custom class. std::vector<Curve> _curves; }; #pragma mark - Channel Template Implementation template <typename T> size_t Channel<T>::index(Time at_time) const { if( at_time <= 0 ) { return 0; } else if ( at_time >= this->duration() ) { return lastIndex(); } for (auto i = 0; i < _keys.size() - 1; i += 1) { auto &a = _keys[i], &b = _keys[i + 1]; if (a.time <= at_time && b.time >= at_time) { return i; } } return lastIndex(); } template <typename T> T Channel<T>::value(Time at_time) const { if (at_time >= duration()) { return _keys.back().value; } else if (at_time <= 0.0) { return _keys.front().value; } return interpolatedValue(index(at_time), at_time); } template <typename T> T Channel<T>::interpolatedValue(size_t curve_index, Time at_time) const { auto &a = _keys[curve_index]; auto &b = _keys[curve_index + 1]; auto &c = _curves[curve_index]; auto x = (at_time - a.time) / (b.time - a.time); auto t = c.solve(x); return lerpT(a.value, b.value, t); } template <typename T> Channel<T>& Channel<T>::insertKey(T value, Time at_time) { if (_keys.empty()) { _keys.emplace_back(value, at_time); return *this; } auto i = index(at_time); _curves.insert(_curves.begin() + i, {}); _keys.insert(_keys.begin() + i + 1, {value, at_time}); return *this; } } // namepsace choreograph <commit_msg>Expose mutable contents.<commit_after>/* * Copyright (c) 2014—2016 David Wicks, sansumbrella.com * 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. * * 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 * HOLDER 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. */ #pragma once #include <vector> #include "Phrase.hpp" #include "UnitBezier.h" #include "TimeType.h" namespace choreograph { class Curve { public: enum Type { Bezier, Hold, Linear }; float solve(float t) const; void setType(Type type) { _type = type; } void hold() { _type = Hold; } BezierInterpolant& bezier() { _type = Bezier; return _bezier; } private: Type _type = Linear; BezierInterpolant _bezier; }; float Curve::solve(float t) const { switch (_type) { case Bezier: return _bezier.solve(t); break; case Hold: return 0.0f; break; case Linear: return t; break; default: return t; break; } } /// /// Simple channel concept with bezier interpolation between keys. /// Goals: /// - Easy serialization /// - Easy to create graphical manipulation tools. /// - Support direct manipulation of animation data. /// - Avoid deeply nested information. Flat hierarchy. /// - Flexible enough to create an AfterEffects-style timeline. /// /// Good for animating single values, like floats or quaternions. /// For vector types, use a channel per component (and maybe add a group type to associate them). /// Grouping type could be a manipulator/animator type class that reads/writes multiple channels. /// template <typename T> class Channel { public: struct Key { Key(T value, Time time): value(value), time(time) {} T value; Time time; }; Channel() = default; /// Return the value of the channel at a given time. T value(Time at_time) const; /// Return the interpolated value between two keys. /// If you keep track of keys yourself, this is faster. T interpolatedValue(size_t curve_index, Time at_time) const; /// Returns the index of the starting key for the current time. /// The curve lies between two keys. size_t index(Time at_time) const; size_t lastIndex() const { return _keys.empty() ? 0 : _keys.size() - 1; } /// Append a key to the list of keys, positioned at \offset time after the previous key. Channel& appendKeyAfter(T value, Time offset) { if (! _keys.empty()) { _curves.emplace_back(); } _keys.emplace_back(value, duration() + offset); return *this; } /// Insert a key at the given time. Channel& insertKey(T value, Time at_time); Time duration() const { return _keys.empty() ? 0 : _keys.back().time; } const std::vector<Key>& keys() const { return _keys; } const std::vector<Curve>& curves() const { return _curves; } std::vector<Key>& mutableKeys() { return _keys; } std::vector<Curve>& mutableCurves() { return _curves; } private: std::vector<Key> _keys; // may make polymorphic in future (like phrases are). Basically just an ease fn. // Compare std::function<float (float)> for max flexibility against custom class. std::vector<Curve> _curves; }; #pragma mark - Channel Template Implementation template <typename T> size_t Channel<T>::index(Time at_time) const { if( at_time <= 0 ) { return 0; } else if ( at_time >= this->duration() ) { return lastIndex(); } for (auto i = 0; i < _keys.size() - 1; i += 1) { auto &a = _keys[i], &b = _keys[i + 1]; if (a.time <= at_time && b.time >= at_time) { return i; } } return lastIndex(); } template <typename T> T Channel<T>::value(Time at_time) const { if (at_time >= duration()) { return _keys.back().value; } else if (at_time <= 0.0) { return _keys.front().value; } return interpolatedValue(index(at_time), at_time); } template <typename T> T Channel<T>::interpolatedValue(size_t curve_index, Time at_time) const { auto &a = _keys[curve_index]; auto &b = _keys[curve_index + 1]; auto &c = _curves[curve_index]; auto x = (at_time - a.time) / (b.time - a.time); auto t = c.solve(x); return lerpT(a.value, b.value, t); } template <typename T> Channel<T>& Channel<T>::insertKey(T value, Time at_time) { if (_keys.empty()) { _keys.emplace_back(value, at_time); return *this; } auto i = index(at_time); _curves.insert(_curves.begin() + i, {}); _keys.insert(_keys.begin() + i + 1, {value, at_time}); return *this; } } // namepsace choreograph <|endoftext|>
<commit_before>/********************************************************************* # Copyright (c) 2013-2015, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the Rethink Robotics 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. *********************************************************************/ /** * \author Hariharasudan Malaichamee * \desc Includes the action listener events for the QT controls */ #include <QtGui> #include <QMessageBox> #include <iostream> #include <baxter_sim_io/baxter_io.hpp> namespace baxter_sim_io { using namespace Qt; void BaxterIO::setstyle(std::string pressed, std::string released, QPushButton& button) { QPixmap pix(QString::fromUtf8(released.c_str())); button.setMask(pix.mask()); button.setStyleSheet("QPushButton{background-image: url("+QString::fromUtf8(released.c_str())+");\n" "background-position: center;\n" "background-color: transparent;\n" "background-repeat: none;\n" "border: none;}\n" "QPushButton:pressed{background-image: url("+QString::fromUtf8(pressed.c_str())+");}"); } BaxterIO::BaxterIO(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc, argv), ui(new Ui::BaxterIO) { ui->setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class. std::string cancel_r=":/new/prefix/nav_cancel_r.png"; std::string cancel_p=":/new/prefix/nav_cancel_p.png"; std::string ok_r=":/new/prefix/nav_ok_r.png"; std::string ok_p=":/new/prefix/nav_ok_p.png"; std::string show_r=":/new/prefix/nav_show_r.png"; std::string show_p=":/new/prefix/nav_show_p.png"; std::string cuff_grasp_r=":/new/prefix/cuff_grasp_r.png"; std::string cuff_grasp_p=":/new/prefix/cuff_grasp_p.png"; std::string cuff_ok_r=":/new/prefix/cuff_ok_r.png"; std::string cuff_ok_p=":/new/prefix/cuff_ok_p.png"; std::string cuff_squeeze_r=":/new/prefix/cuff_squeeze_r.png"; std::string cuff_squeeze_p=":/new/prefix/cuff_squeeze_p.png"; //Configure the stylesheet for all the Qwidgets //left arm setstyle(cancel_p,cancel_r,*(ui->left_arm_cancel)); setstyle(ok_p,ok_r,*(ui->left_arm_ok)); setstyle(show_p,show_r,*(ui->left_arm_show)); //left shoulder setstyle(cancel_p,cancel_r,*(ui->left_shoulder_cancel)); setstyle(ok_p,ok_r,*(ui->left_shoulder_ok)); setstyle(show_p,show_r,*(ui->left_shoulder_show)); //left cuff setstyle(cuff_grasp_p,cuff_grasp_r,*(ui->left_cuff_grasp)); setstyle(cuff_ok_p,cuff_ok_r,*(ui->left_cuff_ok)); setstyle(cuff_squeeze_p,cuff_squeeze_r,*(ui->left_cuff_squeeze)); //right arm setstyle(cancel_p,cancel_r,*(ui->right_arm_cancel)); setstyle(ok_p,ok_r,*(ui->right_arm_ok)); setstyle(show_p,show_r,*(ui->right_arm_show)); //right shoulder setstyle(cancel_p,cancel_r,*(ui->right_shoulder_cancel)); setstyle(ok_p,ok_r,*(ui->right_shoulder_ok)); setstyle(show_p,show_r,*(ui->right_shoulder_show)); //right cuff setstyle(cuff_grasp_p,cuff_grasp_r,*(ui->right_cuff_grasp)); setstyle(cuff_ok_p,cuff_ok_r,*(ui->right_cuff_ok)); setstyle(cuff_squeeze_p,cuff_squeeze_r,*(ui->right_cuff_squeeze)); } BaxterIO::~BaxterIO() { } void BaxterIO::on_left_arm_ok_pressed() { QNode::left_arm_nav.buttons[0] = true; } void BaxterIO::on_left_arm_ok_released() { QNode::left_arm_nav.buttons[0] = false; } void BaxterIO::on_left_arm_cancel_pressed() { QNode::left_arm_nav.buttons[1] = true; } void BaxterIO::on_left_arm_cancel_released() { QNode::left_arm_nav.buttons[1] = false; } void BaxterIO::on_left_arm_dial_sliderMoved(int position) { QNode::left_arm_nav.wheel = position; } void BaxterIO::on_left_arm_show_pressed() { QNode::left_arm_nav.buttons[2] = true; } void BaxterIO::on_left_arm_show_released() { QNode::left_arm_nav.buttons[2] = false; } void BaxterIO::on_left_cuff_squeeze_pressed() { QNode::left_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_squeeze_released() { QNode::left_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_cuff_ok_pressed() { QNode::left_cuff_ok.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_ok_released() { QNode::left_cuff_ok.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_cuff_grasp_pressed() { QNode::left_cuff_grasp.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_grasp_released() { QNode::left_cuff_grasp.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_shoulder_ok_pressed() { QNode::left_shoulder_nav.buttons[0] = true; } void BaxterIO::on_left_shoulder_ok_released() { QNode::left_shoulder_nav.buttons[0] = false; } void BaxterIO::on_left_shoulder_cancel_pressed() { QNode::left_shoulder_nav.buttons[1] = true; } void BaxterIO::on_left_shoulder_cancel_released() { QNode::left_shoulder_nav.buttons[1] = false; } void BaxterIO::on_left_shoulder_show_pressed() { QNode::left_shoulder_nav.buttons[2] = true; } void BaxterIO::on_left_shoulder_show_released() { QNode::left_shoulder_nav.buttons[2] = false; } void BaxterIO::on_left_shoulder_dial_sliderMoved(int position) { QNode::left_shoulder_nav.wheel = position; } void BaxterIO::on_right_shoulder_ok_pressed() { QNode::right_shoulder_nav.buttons[0] = true; } void BaxterIO::on_right_shoulder_ok_released() { QNode::right_shoulder_nav.buttons[0] = false; } void BaxterIO::on_right_shoulder_cancel_pressed() { QNode::right_shoulder_nav.buttons[1] = true; } void BaxterIO::on_right_shoulder_cancel_released() { QNode::right_shoulder_nav.buttons[1] = false; } void BaxterIO::on_right_shoulder_dial_sliderMoved(int position) { QNode::right_shoulder_nav.wheel = position; } void BaxterIO::on_right_shoulder_show_pressed() { QNode::right_shoulder_nav.buttons[2] = true; } void BaxterIO::on_right_shoulder_show_released() { QNode::right_shoulder_nav.buttons[2] = false; } void BaxterIO::on_right_arm_ok_pressed() { QNode::right_arm_nav.buttons[0] = true; } void BaxterIO::on_right_arm_ok_released() { QNode::right_arm_nav.buttons[0] = false; } void BaxterIO::on_right_arm_cancel_pressed() { QNode::right_arm_nav.buttons[1] = true; } void BaxterIO::on_right_arm_cancel_released() { QNode::right_arm_nav.buttons[1] = false; } void BaxterIO::on_right_arm_dial_sliderMoved(int position) { QNode::right_arm_nav.wheel = position; } void BaxterIO::on_right_arm_show_pressed() { QNode::right_arm_nav.buttons[2] = true; } void BaxterIO::on_right_arm_show_released() { QNode::right_arm_nav.buttons[2] = false; } void BaxterIO::on_right_cuff_squeeze_pressed() { QNode::right_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_squeeze_released() { QNode::right_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_cuff_ok_pressed() { QNode::right_cuff_ok.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_ok_released() { QNode::right_cuff_ok.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_cuff_grasp_pressed() { QNode::right_cuff_grasp.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_grasp_released() { QNode::right_cuff_grasp.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_shoulder_pressed() { QNode::left_shoulder.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_shoulder_released() { QNode::left_shoulder.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_shoulder_pressed() { QNode::right_shoulder.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_shoulder_released() { QNode::right_shoulder.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } } // namespace baxter_sim_io <commit_msg>Deleted allocated UI object in baxter_sim_io<commit_after>/********************************************************************* # Copyright (c) 2013-2015, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the Rethink Robotics 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. *********************************************************************/ /** * \author Hariharasudan Malaichamee * \desc Includes the action listener events for the QT controls */ #include <QtGui> #include <QMessageBox> #include <iostream> #include <baxter_sim_io/baxter_io.hpp> namespace baxter_sim_io { using namespace Qt; void BaxterIO::setstyle(std::string pressed, std::string released, QPushButton& button) { QPixmap pix(QString::fromUtf8(released.c_str())); button.setMask(pix.mask()); button.setStyleSheet("QPushButton{background-image: url("+QString::fromUtf8(released.c_str())+");\n" "background-position: center;\n" "background-color: transparent;\n" "background-repeat: none;\n" "border: none;}\n" "QPushButton:pressed{background-image: url("+QString::fromUtf8(pressed.c_str())+");}"); } BaxterIO::BaxterIO(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc, argv), ui(new Ui::BaxterIO) { ui->setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class. std::string cancel_r=":/new/prefix/nav_cancel_r.png"; std::string cancel_p=":/new/prefix/nav_cancel_p.png"; std::string ok_r=":/new/prefix/nav_ok_r.png"; std::string ok_p=":/new/prefix/nav_ok_p.png"; std::string show_r=":/new/prefix/nav_show_r.png"; std::string show_p=":/new/prefix/nav_show_p.png"; std::string cuff_grasp_r=":/new/prefix/cuff_grasp_r.png"; std::string cuff_grasp_p=":/new/prefix/cuff_grasp_p.png"; std::string cuff_ok_r=":/new/prefix/cuff_ok_r.png"; std::string cuff_ok_p=":/new/prefix/cuff_ok_p.png"; std::string cuff_squeeze_r=":/new/prefix/cuff_squeeze_r.png"; std::string cuff_squeeze_p=":/new/prefix/cuff_squeeze_p.png"; //Configure the stylesheet for all the Qwidgets //left arm setstyle(cancel_p,cancel_r,*(ui->left_arm_cancel)); setstyle(ok_p,ok_r,*(ui->left_arm_ok)); setstyle(show_p,show_r,*(ui->left_arm_show)); //left shoulder setstyle(cancel_p,cancel_r,*(ui->left_shoulder_cancel)); setstyle(ok_p,ok_r,*(ui->left_shoulder_ok)); setstyle(show_p,show_r,*(ui->left_shoulder_show)); //left cuff setstyle(cuff_grasp_p,cuff_grasp_r,*(ui->left_cuff_grasp)); setstyle(cuff_ok_p,cuff_ok_r,*(ui->left_cuff_ok)); setstyle(cuff_squeeze_p,cuff_squeeze_r,*(ui->left_cuff_squeeze)); //right arm setstyle(cancel_p,cancel_r,*(ui->right_arm_cancel)); setstyle(ok_p,ok_r,*(ui->right_arm_ok)); setstyle(show_p,show_r,*(ui->right_arm_show)); //right shoulder setstyle(cancel_p,cancel_r,*(ui->right_shoulder_cancel)); setstyle(ok_p,ok_r,*(ui->right_shoulder_ok)); setstyle(show_p,show_r,*(ui->right_shoulder_show)); //right cuff setstyle(cuff_grasp_p,cuff_grasp_r,*(ui->right_cuff_grasp)); setstyle(cuff_ok_p,cuff_ok_r,*(ui->right_cuff_ok)); setstyle(cuff_squeeze_p,cuff_squeeze_r,*(ui->right_cuff_squeeze)); } BaxterIO::~BaxterIO() { delete ui; } void BaxterIO::on_left_arm_ok_pressed() { QNode::left_arm_nav.buttons[0] = true; } void BaxterIO::on_left_arm_ok_released() { QNode::left_arm_nav.buttons[0] = false; } void BaxterIO::on_left_arm_cancel_pressed() { QNode::left_arm_nav.buttons[1] = true; } void BaxterIO::on_left_arm_cancel_released() { QNode::left_arm_nav.buttons[1] = false; } void BaxterIO::on_left_arm_dial_sliderMoved(int position) { QNode::left_arm_nav.wheel = position; } void BaxterIO::on_left_arm_show_pressed() { QNode::left_arm_nav.buttons[2] = true; } void BaxterIO::on_left_arm_show_released() { QNode::left_arm_nav.buttons[2] = false; } void BaxterIO::on_left_cuff_squeeze_pressed() { QNode::left_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_squeeze_released() { QNode::left_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_cuff_ok_pressed() { QNode::left_cuff_ok.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_ok_released() { QNode::left_cuff_ok.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_cuff_grasp_pressed() { QNode::left_cuff_grasp.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_cuff_grasp_released() { QNode::left_cuff_grasp.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_shoulder_ok_pressed() { QNode::left_shoulder_nav.buttons[0] = true; } void BaxterIO::on_left_shoulder_ok_released() { QNode::left_shoulder_nav.buttons[0] = false; } void BaxterIO::on_left_shoulder_cancel_pressed() { QNode::left_shoulder_nav.buttons[1] = true; } void BaxterIO::on_left_shoulder_cancel_released() { QNode::left_shoulder_nav.buttons[1] = false; } void BaxterIO::on_left_shoulder_show_pressed() { QNode::left_shoulder_nav.buttons[2] = true; } void BaxterIO::on_left_shoulder_show_released() { QNode::left_shoulder_nav.buttons[2] = false; } void BaxterIO::on_left_shoulder_dial_sliderMoved(int position) { QNode::left_shoulder_nav.wheel = position; } void BaxterIO::on_right_shoulder_ok_pressed() { QNode::right_shoulder_nav.buttons[0] = true; } void BaxterIO::on_right_shoulder_ok_released() { QNode::right_shoulder_nav.buttons[0] = false; } void BaxterIO::on_right_shoulder_cancel_pressed() { QNode::right_shoulder_nav.buttons[1] = true; } void BaxterIO::on_right_shoulder_cancel_released() { QNode::right_shoulder_nav.buttons[1] = false; } void BaxterIO::on_right_shoulder_dial_sliderMoved(int position) { QNode::right_shoulder_nav.wheel = position; } void BaxterIO::on_right_shoulder_show_pressed() { QNode::right_shoulder_nav.buttons[2] = true; } void BaxterIO::on_right_shoulder_show_released() { QNode::right_shoulder_nav.buttons[2] = false; } void BaxterIO::on_right_arm_ok_pressed() { QNode::right_arm_nav.buttons[0] = true; } void BaxterIO::on_right_arm_ok_released() { QNode::right_arm_nav.buttons[0] = false; } void BaxterIO::on_right_arm_cancel_pressed() { QNode::right_arm_nav.buttons[1] = true; } void BaxterIO::on_right_arm_cancel_released() { QNode::right_arm_nav.buttons[1] = false; } void BaxterIO::on_right_arm_dial_sliderMoved(int position) { QNode::right_arm_nav.wheel = position; } void BaxterIO::on_right_arm_show_pressed() { QNode::right_arm_nav.buttons[2] = true; } void BaxterIO::on_right_arm_show_released() { QNode::right_arm_nav.buttons[2] = false; } void BaxterIO::on_right_cuff_squeeze_pressed() { QNode::right_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_squeeze_released() { QNode::right_cuff_squeeze.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_cuff_ok_pressed() { QNode::right_cuff_ok.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_ok_released() { QNode::right_cuff_ok.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_cuff_grasp_pressed() { QNode::right_cuff_grasp.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_cuff_grasp_released() { QNode::right_cuff_grasp.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_left_shoulder_pressed() { QNode::left_shoulder.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_left_shoulder_released() { QNode::left_shoulder.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } void BaxterIO::on_right_shoulder_pressed() { QNode::right_shoulder.state = baxter_core_msgs::DigitalIOState::PRESSED; } void BaxterIO::on_right_shoulder_released() { QNode::right_shoulder.state = baxter_core_msgs::DigitalIOState::UNPRESSED; } } // namespace baxter_sim_io <|endoftext|>
<commit_before>/* This file is part of the Cagibi daemon, part of the KDE project. Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 "upnpproxy.h" // program #include "upnpproxydbusadaptor.h" #include "ssdpwatcher.h" #include "rootdevice.h" #include "device.h" namespace Cagibi { static void fillMap( DeviceTypeMap& map, const Device& device ) { map.insert( device.udn(), device.type() ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMap( map, subDevice ); } static void fillMapByType( DeviceTypeMap& map, const Device& device, const QString& type = QString() ) { const QString deviceType = device.type(); if( deviceType == type ) map.insert( device.udn(), deviceType ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMapByType( map, subDevice, type ); } static const Device* find( const Device& device, const QString& udn ) { const Device* result = 0; if( device.udn() == udn ) result = &device; else { foreach( const Cagibi::Device& subDevice, device.devices() ) { result = find( subDevice, udn ); if( result ) break; } } return result; } UPnPProxy::UPnPProxy( QObject* parent ) : QObject( parent ), mSsdpWatcher( new SSDPWatcher(this) ) { new UPnPProxyDBusAdaptor( this ); QDBusConnection sessionBus = QDBusConnection::sessionBus(); sessionBus.registerService( QString::fromLatin1("org.kde.Cagibi") ); sessionBus.registerObject( QString::fromLatin1("/"), this ); connect( mSsdpWatcher, SIGNAL(deviceDiscovered( Cagibi::RootDevice* )), SLOT(onDeviceDiscovered( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(deviceRemoved( Cagibi::RootDevice* )), SLOT(onDeviceRemoved( Cagibi::RootDevice* )) ); mSsdpWatcher->discover(); } DeviceTypeMap UPnPProxy::allDevices() const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMap( result, device ); } return result; } DeviceTypeMap UPnPProxy::devicesByParent( const QString& udn ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { foreach( const Cagibi::Device& subDevice, device.devices() ) result.insert( subDevice.udn(), subDevice.type() ); break; } } return result; } DeviceTypeMap UPnPProxy::devicesByType( const QString& type ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMapByType( result, device, type ); } return result; } Device UPnPProxy::deviceDetails( const QString& udn ) const { Device result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { result = *match; break; } } return result; } void UPnPProxy::onDeviceDiscovered( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); emit devicesAdded( devices ); } void UPnPProxy::onDeviceRemoved( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); emit devicesRemoved( devices ); } UPnPProxy::~UPnPProxy() { } } <commit_msg>removed: unneeded default empty type parameter for fillMapByType()<commit_after>/* This file is part of the Cagibi daemon, part of the KDE project. Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 "upnpproxy.h" // program #include "upnpproxydbusadaptor.h" #include "ssdpwatcher.h" #include "rootdevice.h" #include "device.h" #include <QtCore/QDebug> namespace Cagibi { static void fillMap( DeviceTypeMap& map, const Device& device ) { map.insert( device.udn(), device.type() ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMap( map, subDevice ); } static void fillMapByType( DeviceTypeMap& map, const Device& device, const QString& type ) { const QString deviceType = device.type(); if( deviceType == type ) map.insert( device.udn(), deviceType ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMapByType( map, subDevice, type ); } static const Device* find( const Device& device, const QString& udn ) { const Device* result = 0; if( device.udn() == udn ) result = &device; else { foreach( const Cagibi::Device& subDevice, device.devices() ) { result = find( subDevice, udn ); if( result ) break; } } return result; } UPnPProxy::UPnPProxy( QObject* parent ) : QObject( parent ), mSsdpWatcher( new SSDPWatcher(this) ) { new UPnPProxyDBusAdaptor( this ); QDBusConnection sessionBus = QDBusConnection::sessionBus(); sessionBus.registerService( QString::fromLatin1("org.kde.Cagibi") ); sessionBus.registerObject( QString::fromLatin1("/"), this ); connect( mSsdpWatcher, SIGNAL(deviceDiscovered( Cagibi::RootDevice* )), SLOT(onDeviceDiscovered( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(deviceRemoved( Cagibi::RootDevice* )), SLOT(onDeviceRemoved( Cagibi::RootDevice* )) ); mSsdpWatcher->discover(); } DeviceTypeMap UPnPProxy::allDevices() const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMap( result, device ); } return result; } DeviceTypeMap UPnPProxy::devicesByParent( const QString& udn ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { foreach( const Cagibi::Device& subDevice, device.devices() ) result.insert( subDevice.udn(), subDevice.type() ); break; } } return result; } DeviceTypeMap UPnPProxy::devicesByType( const QString& type ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMapByType( result, device, type ); } return result; } Device UPnPProxy::deviceDetails( const QString& udn ) const { Device result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { result = *match; break; } } return result; } void UPnPProxy::onDeviceDiscovered( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); emit devicesAdded( devices ); } void UPnPProxy::onDeviceRemoved( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); emit devicesRemoved( devices ); } UPnPProxy::~UPnPProxy() { } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <iostream> #include <chrono> #include <random> #include "etl/etl.hpp" #define CPM_NO_RANDOMIZATION //Randomly initialize only once #define CPM_AUTO_STEPS //Enable steps estimation system #define CPM_STEP_ESTIMATION_MIN 0.05 //Run during 0.05 seconds for estimating steps #define CPM_RUNTIME_TARGET 1.0 //Run each test during 1.0 seconds #include "cpm/cpm.hpp" #ifdef ETL_VECTORIZE_IMPL #ifdef __SSE3__ #define TEST_SSE #endif #ifdef __AVX__ #define TEST_AVX #endif #endif #ifdef ETL_MKL_MODE #define TEST_MKL #endif #ifdef ETL_CUBLAS_MODE #define TEST_CUBLAS #endif #ifdef ETL_CUFFT_MODE #define TEST_CUFFT #endif #ifdef ETL_BLAS_MODE #define TEST_BLAS #endif #ifdef ETL_BENCH_STRASSEN #define TEST_STRASSEN #endif #ifdef ETL_BENCH_MMUL_CONV #define TEST_MMUL_CONV #endif using smat_cm = etl::dyn_matrix_cm<float>; using dmat_cm = etl::dyn_matrix_cm<double>; using cmat_cm = etl::dyn_matrix_cm<std::complex<float>>; using zmat_cm = etl::dyn_matrix_cm<std::complex<double>>; using dvec = etl::dyn_vector<double>; using dmat = etl::dyn_matrix<double>; using dmat2 = etl::dyn_matrix<double, 2>; using dmat3 = etl::dyn_matrix<double, 3>; using dmat4 = etl::dyn_matrix<double, 4>; using svec = etl::dyn_vector<float>; using smat = etl::dyn_matrix<float>; using cvec = etl::dyn_vector<std::complex<float>>; using cmat = etl::dyn_matrix<std::complex<float>>; using zvec = etl::dyn_vector<std::complex<double>>; using zmat = etl::dyn_matrix<std::complex<double>>; using mat_policy = VALUES_POLICY(10, 25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000,3000,4000); using mat_policy_2d = NARY_POLICY(mat_policy, mat_policy); using conv_1d_large_policy = NARY_POLICY(VALUES_POLICY(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), VALUES_POLICY(500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000)); using conv_2d_large_policy = NARY_POLICY(VALUES_POLICY(100, 105, 110, 115, 120, 125, 130, 135, 140), VALUES_POLICY(50, 50, 55, 55, 60, 60, 65, 65, 70)); using fft_1d_policy = VALUES_POLICY(10, 100, 1000, 10000, 100000, 500000); using fft_1d_policy_2 = VALUES_POLICY(16, 64, 256, 1024, 16384, 131072, 1048576, 2097152); using fft_1d_many_policy = VALUES_POLICY(10, 50, 100, 500, 1000, 5000, 10000); using fft_2d_policy = NARY_POLICY( VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048), VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048)); using sigmoid_policy = VALUES_POLICY(250, 500, 750, 1000, 1250, 1500, 1750, 2000); using small_square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500), VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500)); using square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000), VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)); using gemv_policy = NARY_POLICY( VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000), VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000)); using trans_sub_policy = VALUES_POLICY(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000); using trans_policy = NARY_POLICY( VALUES_POLICY(100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000), VALUES_POLICY(100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000, 1100)); #ifdef TEST_SSE #define SSE_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define SSE_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_AVX #define AVX_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define AVX_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_MKL #define MKL_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define MKL_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_BLAS #define BLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define BLAS_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_CUBLAS #define CUBLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define CUBLAS_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_CUFFT #define CUFFT_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define CUFFT_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_MMUL_CONV #define MC_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define MC_SECTION_FUNCTOR(name, ...) #endif <commit_msg>Save some time<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <iostream> #include <chrono> #include <random> #include "etl/etl.hpp" #define CPM_NO_RANDOMIZATION //Randomly initialize only once #define CPM_AUTO_STEPS //Enable steps estimation system #define CPM_STEP_ESTIMATION_MIN 0.05 //Run during 0.05 seconds for estimating steps #define CPM_RUNTIME_TARGET 0.9 //Run each test during 0.9 seconds #include "cpm/cpm.hpp" #ifdef ETL_VECTORIZE_IMPL #ifdef __SSE3__ #define TEST_SSE #endif #ifdef __AVX__ #define TEST_AVX #endif #endif #ifdef ETL_MKL_MODE #define TEST_MKL #endif #ifdef ETL_CUBLAS_MODE #define TEST_CUBLAS #endif #ifdef ETL_CUFFT_MODE #define TEST_CUFFT #endif #ifdef ETL_BLAS_MODE #define TEST_BLAS #endif #ifdef ETL_BENCH_STRASSEN #define TEST_STRASSEN #endif #ifdef ETL_BENCH_MMUL_CONV #define TEST_MMUL_CONV #endif using smat_cm = etl::dyn_matrix_cm<float>; using dmat_cm = etl::dyn_matrix_cm<double>; using cmat_cm = etl::dyn_matrix_cm<std::complex<float>>; using zmat_cm = etl::dyn_matrix_cm<std::complex<double>>; using dvec = etl::dyn_vector<double>; using dmat = etl::dyn_matrix<double>; using dmat2 = etl::dyn_matrix<double, 2>; using dmat3 = etl::dyn_matrix<double, 3>; using dmat4 = etl::dyn_matrix<double, 4>; using svec = etl::dyn_vector<float>; using smat = etl::dyn_matrix<float>; using cvec = etl::dyn_vector<std::complex<float>>; using cmat = etl::dyn_matrix<std::complex<float>>; using zvec = etl::dyn_vector<std::complex<double>>; using zmat = etl::dyn_matrix<std::complex<double>>; using mat_policy = VALUES_POLICY(10, 25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000,3000,4000); using mat_policy_2d = NARY_POLICY(mat_policy, mat_policy); using conv_1d_large_policy = NARY_POLICY(VALUES_POLICY(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), VALUES_POLICY(500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000)); using conv_2d_large_policy = NARY_POLICY(VALUES_POLICY(100, 105, 110, 115, 120, 125, 130, 135, 140), VALUES_POLICY(50, 50, 55, 55, 60, 60, 65, 65, 70)); using fft_1d_policy = VALUES_POLICY(10, 100, 1000, 10000, 100000, 500000); using fft_1d_policy_2 = VALUES_POLICY(16, 64, 256, 1024, 16384, 131072, 1048576, 2097152); using fft_1d_many_policy = VALUES_POLICY(10, 50, 100, 500, 1000, 5000, 10000); using fft_2d_policy = NARY_POLICY( VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048), VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048)); using sigmoid_policy = VALUES_POLICY(250, 500, 750, 1000, 1250, 1500, 1750, 2000); using small_square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500), VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500)); using square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000), VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)); using gemv_policy = NARY_POLICY( VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000), VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000)); using trans_sub_policy = VALUES_POLICY(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000); using trans_policy = NARY_POLICY( VALUES_POLICY(100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000), VALUES_POLICY(100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000, 1100)); #ifdef TEST_SSE #define SSE_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define SSE_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_AVX #define AVX_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define AVX_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_MKL #define MKL_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define MKL_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_BLAS #define BLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define BLAS_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_CUBLAS #define CUBLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define CUBLAS_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_CUFFT #define CUFFT_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define CUFFT_SECTION_FUNCTOR(name, ...) #endif #ifdef TEST_MMUL_CONV #define MC_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__) #else #define MC_SECTION_FUNCTOR(name, ...) #endif <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) FFLAS-FFPACK * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr> * * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== *. */ #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <vector> #include <string> using namespace std; #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/args-parser.h" #include "givaro/modular-integer.h" #include "fflas-ffpack/paladin/parallel.h" #ifdef BENCH_FLINT #define __GMP_BITS_PER_MP_LIMB 64 extern "C" { #include "flint/longlong.h" #include "flint/long_extras.h" #include "flint/fmpz_mat.h" #include "flint/fmpz.h" #include "flint/flint.h" } template<typename T> void write_matrix(Givaro::Integer p, size_t m, size_t n, T* C, size_t ldc){ size_t www=(p.bitsize()*log(2.))/log(10.); for (size_t i=0;i<m;++i){ cout<<"[ "; cout.width(www+1); cout<<std::right<<C[i*ldc]; for (size_t j=1;j<n;++j){ cout<<" "; cout.width(www); cout<<std::right<<C[i*ldc+j]; } cout<<"]"<<endl; } cout<<endl; } #endif int main(int argc, char** argv){ srand((int)time(NULL)); srand48(time(NULL)); static size_t iters = 3 ; static Givaro::Integer q = -1 ; static unsigned long b = 512 ; static size_t m = 512 ; static size_t k = 512 ; static size_t n = 512 ; static int nbw = -1 ; static Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b }, { 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m }, { 'k', "-k K", "Set the dimension k of the matrix.", TYPE_INT , &k }, { 'n', "-n N", "Set the dimension n of the matrix.", TYPE_INT , &n }, { 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); size_t seed= time(NULL); typedef Givaro::Modular<Givaro::Integer> Field; Givaro::Integer p; FFLAS::Timer chrono, TimFreivalds; double time=0.,timev=0.; #ifdef BENCH_FLINT double timeFlint=0.; #endif for (size_t loop=0;loop<iters;loop++){ Givaro::Integer::random_exact_2exp(p, b); Givaro::IntPrimeDom IPD; IPD.nextprimein(p); Field F(p); size_t lda,ldb,ldc; lda=k; ldb=n; ldc=n; typename Field::RandIter Rand(F,seed); Field::Element_ptr A,B,C; A= FFLAS::fflas_new(F,m,lda); B= FFLAS::fflas_new(F,k,ldb); C= FFLAS::fflas_new(F,m,ldc); // for (size_t i=0;i<m;++i) // for (size_t j=0;j<k;++j) // Rand.random(A[i*lda+j]); // for (size_t i=0;i<k;++i) // for (size_t j=0;j<n;++j) // Rand.random(B[i*ldb+j]); // for (size_t i=0;i<m;++i) // for (size_t j=0;j<n;++j) // Rand.random(C[i*ldc+j]); PAR_BLOCK { FFLAS::pfrand(F,Rand, m,k,A,m/size_t(MAX_THREADS)); } PAR_BLOCK { FFLAS::pfrand(F,Rand, k,n,B,k/MAX_THREADS); } PAR_BLOCK { FFLAS::pfzero(F, m,n,C,m/MAX_THREADS); } Givaro::Integer alpha,beta; alpha=1; beta=0; #ifdef BENCH_FLINT // FLINT MUL // fmpz_t modp,tmp; fmpz_init(modp); fmpz_init(tmp); fmpz_set_mpz(modp, *(reinterpret_cast<const mpz_t*>(&p))); fmpz_mat_t AA,BB,CC,DD; fmpz_mat_init (AA, m, k); fmpz_mat_init (BB, k, n); fmpz_mat_init (CC, m, n); fmpz_mat_init (DD, m, n); fmpz_t aalpha, bbeta; fmpz_set_mpz(aalpha,*(reinterpret_cast<const mpz_t*>(&alpha))); fmpz_set_mpz(bbeta,*(reinterpret_cast<const mpz_t*>(&beta))); for (size_t i=0;i<m;++i) for (size_t j=0;j<k;++j) fmpz_set_mpz(fmpz_mat_entry(AA,i,j),*(reinterpret_cast<const mpz_t*>(A+i*lda+j))); for (size_t i=0;i<k;++i) for (size_t j=0;j<n;++j) fmpz_set_mpz(fmpz_mat_entry(BB,i,j),*(reinterpret_cast<const mpz_t*>(B+i*ldb+j))); for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) fmpz_set_mpz(fmpz_mat_entry(CC,i,j),*(reinterpret_cast<const mpz_t*>(C+i*ldc+j))); chrono.clear();chrono.start(); // DD= A.B fmpz_mat_mul(DD,AA,BB); // CC = beta.C fmpz_mat_scalar_mul_fmpz(CC,CC,bbeta); // CC = CC + DD.alpha fmpz_mat_scalar_addmul_fmpz(CC,DD,aalpha); // CC = CC mod p for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) fmpz_mod(fmpz_mat_entry(CC,i,j),fmpz_mat_entry(CC,i,j),modp); chrono.stop(); timeFlint+=chrono.usertime(); fmpz_mat_clear(AA); fmpz_mat_clear(BB); #endif //END FLINT CODE // using FFLAS::CuttingStrategy::Recursive; using FFLAS::StrategyParameter::TwoDAdaptive; // RNS MUL_LA chrono.clear();chrono.start(); PAR_BLOCK{ FFLAS::fgemm(F,FFLAS::FflasNoTrans,FFLAS::FflasNoTrans,m,n,k,alpha,A,lda,B,ldb,beta,C,ldc, SPLITTER(MAX_THREADS,Recursive,TwoDAdaptive) ); } chrono.stop(); time+=chrono.usertime(); // TimFreivalds.start(); // bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n); // TimFreivalds.stop(); // timev+=TimFreivalds.usertime(); // if (!pass) std::cout<<"FAILED"<<std::endl; FFLAS::fflas_delete(A); FFLAS::fflas_delete(B); FFLAS::fflas_delete(C); } double Gflops=(2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / chrono.realtime() * double(iters); // Gflops*=p.bitsize()/16.; cout<<"Time: "<<time<<" Gflops: "<<Gflops<<" | perword: "<< (Gflops*p.bitsize())/64. ; FFLAS::writeCommandString(std::cout << '|' << p << " (" << p.bitsize()<<")|", as) << std::endl; #ifdef BENCH_FLINT cout<<"Time FLINT: "<<timeFlint<<endl; #endif return 0; } <commit_msg>remove unused variable warning<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) FFLAS-FFPACK * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr> * * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== *. */ #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <vector> #include <string> using namespace std; #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/args-parser.h" #include "givaro/modular-integer.h" #include "fflas-ffpack/paladin/parallel.h" #ifdef BENCH_FLINT #define __GMP_BITS_PER_MP_LIMB 64 extern "C" { #include "flint/longlong.h" #include "flint/long_extras.h" #include "flint/fmpz_mat.h" #include "flint/fmpz.h" #include "flint/flint.h" } template<typename T> void write_matrix(Givaro::Integer p, size_t m, size_t n, T* C, size_t ldc){ size_t www=(p.bitsize()*log(2.))/log(10.); for (size_t i=0;i<m;++i){ cout<<"[ "; cout.width(www+1); cout<<std::right<<C[i*ldc]; for (size_t j=1;j<n;++j){ cout<<" "; cout.width(www); cout<<std::right<<C[i*ldc+j]; } cout<<"]"<<endl; } cout<<endl; } #endif int main(int argc, char** argv){ srand((int)time(NULL)); srand48(time(NULL)); static size_t iters = 3 ; static Givaro::Integer q = -1 ; static unsigned long b = 512 ; static size_t m = 512 ; static size_t k = 512 ; static size_t n = 512 ; static int nbw = -1 ; static Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b }, { 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m }, { 'k', "-k K", "Set the dimension k of the matrix.", TYPE_INT , &k }, { 'n', "-n N", "Set the dimension n of the matrix.", TYPE_INT , &n }, { 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); size_t seed= time(NULL); typedef Givaro::Modular<Givaro::Integer> Field; Givaro::Integer p; FFLAS::Timer chrono, TimFreivalds; double time=0.; #ifdef BENCH_FLINT double timeFlint=0.; #endif for (size_t loop=0;loop<iters;loop++){ Givaro::Integer::random_exact_2exp(p, b); Givaro::IntPrimeDom IPD; IPD.nextprimein(p); Field F(p); size_t lda,ldb,ldc; lda=k; ldb=n; ldc=n; typename Field::RandIter Rand(F,seed); Field::Element_ptr A,B,C; A= FFLAS::fflas_new(F,m,lda); B= FFLAS::fflas_new(F,k,ldb); C= FFLAS::fflas_new(F,m,ldc); // for (size_t i=0;i<m;++i) // for (size_t j=0;j<k;++j) // Rand.random(A[i*lda+j]); // for (size_t i=0;i<k;++i) // for (size_t j=0;j<n;++j) // Rand.random(B[i*ldb+j]); // for (size_t i=0;i<m;++i) // for (size_t j=0;j<n;++j) // Rand.random(C[i*ldc+j]); PAR_BLOCK { FFLAS::pfrand(F,Rand, m,k,A,m/size_t(MAX_THREADS)); } PAR_BLOCK { FFLAS::pfrand(F,Rand, k,n,B,k/MAX_THREADS); } PAR_BLOCK { FFLAS::pfzero(F, m,n,C,m/MAX_THREADS); } Givaro::Integer alpha,beta; alpha=1; beta=0; #ifdef BENCH_FLINT // FLINT MUL // fmpz_t modp,tmp; fmpz_init(modp); fmpz_init(tmp); fmpz_set_mpz(modp, *(reinterpret_cast<const mpz_t*>(&p))); fmpz_mat_t AA,BB,CC,DD; fmpz_mat_init (AA, m, k); fmpz_mat_init (BB, k, n); fmpz_mat_init (CC, m, n); fmpz_mat_init (DD, m, n); fmpz_t aalpha, bbeta; fmpz_set_mpz(aalpha,*(reinterpret_cast<const mpz_t*>(&alpha))); fmpz_set_mpz(bbeta,*(reinterpret_cast<const mpz_t*>(&beta))); for (size_t i=0;i<m;++i) for (size_t j=0;j<k;++j) fmpz_set_mpz(fmpz_mat_entry(AA,i,j),*(reinterpret_cast<const mpz_t*>(A+i*lda+j))); for (size_t i=0;i<k;++i) for (size_t j=0;j<n;++j) fmpz_set_mpz(fmpz_mat_entry(BB,i,j),*(reinterpret_cast<const mpz_t*>(B+i*ldb+j))); for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) fmpz_set_mpz(fmpz_mat_entry(CC,i,j),*(reinterpret_cast<const mpz_t*>(C+i*ldc+j))); chrono.clear();chrono.start(); // DD= A.B fmpz_mat_mul(DD,AA,BB); // CC = beta.C fmpz_mat_scalar_mul_fmpz(CC,CC,bbeta); // CC = CC + DD.alpha fmpz_mat_scalar_addmul_fmpz(CC,DD,aalpha); // CC = CC mod p for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) fmpz_mod(fmpz_mat_entry(CC,i,j),fmpz_mat_entry(CC,i,j),modp); chrono.stop(); timeFlint+=chrono.usertime(); fmpz_mat_clear(AA); fmpz_mat_clear(BB); #endif //END FLINT CODE // using FFLAS::CuttingStrategy::Recursive; using FFLAS::StrategyParameter::TwoDAdaptive; // RNS MUL_LA chrono.clear();chrono.start(); PAR_BLOCK{ FFLAS::fgemm(F,FFLAS::FflasNoTrans,FFLAS::FflasNoTrans,m,n,k,alpha,A,lda,B,ldb,beta,C,ldc, SPLITTER(MAX_THREADS,Recursive,TwoDAdaptive) ); } chrono.stop(); time+=chrono.usertime(); // TimFreivalds.start(); // bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n); // TimFreivalds.stop(); // timev+=TimFreivalds.usertime(); // if (!pass) std::cout<<"FAILED"<<std::endl; FFLAS::fflas_delete(A); FFLAS::fflas_delete(B); FFLAS::fflas_delete(C); } double Gflops=(2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / chrono.realtime() * double(iters); // Gflops*=p.bitsize()/16.; cout<<"Time: "<<time<<" Gflops: "<<Gflops<<" | perword: "<< (Gflops*p.bitsize())/64. ; FFLAS::writeCommandString(std::cout << '|' << p << " (" << p.bitsize()<<")|", as) << std::endl; #ifdef BENCH_FLINT cout<<"Time FLINT: "<<timeFlint<<endl; #endif return 0; } <|endoftext|>
<commit_before>/** * @file */ #include "bi/io/cpp/CppClassGenerator.hpp" #include "bi/io/cpp/CppResumeGenerator.hpp" #include "bi/visitor/Gatherer.hpp" #include "bi/primitive/encode.hpp" bi::CppClassGenerator::CppClassGenerator(std::ostream& base, const int level, const bool header, const bool generic, const Class* currentClass) : CppBaseGenerator(base, level, header, generic), currentClass(currentClass) { // } void bi::CppClassGenerator::visit(const Class* o) { if (!o->isAlias() && !o->braces->isEmpty()) { currentClass = o; auto base = dynamic_cast<const NamedType*>(o->base); Gatherer<MemberFunction> memberFunctions; Gatherer<MemberFiber> memberFibers; Gatherer<MemberVariable> memberVariables; o->accept(&memberFunctions); o->accept(&memberFibers); o->accept(&memberVariables); if (header) { genTemplateParams(o); genSourceLine(o->loc); start("class " << o->name); if (o->has(FINAL)) { middle(" final"); } middle(" : public "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(" {"); line("public:"); in(); genSourceLine(o->loc); start("using class_type_ = " << o->name); genTemplateArgs(o); finish(';'); genSourceLine(o->loc); line("using this_type_ = class_type_;"); genSourceLine(o->loc); start("using super_type_ = "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(";\n"); /* using declarations for member functions and fibers in base classes * that are overridden */ std::set<std::string> names; for (auto f : memberFunctions) { auto name = f->name->str(); if (o->scope->overrides(name)) { names.insert(name); } } for (auto f : memberFibers) { auto name = f->name->str(); if (o->scope->overrides(name)) { names.insert(name); } } genSourceLine(o->loc); line("using super_type_::operator=;"); for (auto name : names) { genSourceLine(o->loc); line("using super_type_::" << internalise(name) << ';'); } line(""); } /* boilerplate */ if (header) { if (o->has(ABSTRACT)) { start("LIBBIRCH_ABSTRACT_CLASS"); } else { start("LIBBIRCH_CLASS"); } middle('(' << o->name << ", "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(')'); start("LIBBIRCH_MEMBERS("); for (auto iter = memberVariables.begin(); iter != memberVariables.end(); ++iter) { if (iter != memberVariables.begin()) { middle(", "); } middle((*iter)->name); } finish(")\n"); } /* constructor */ if (!header) { genTemplateParams(o); genSourceLine(o->loc); start("bi::type::" << o->name); genTemplateArgs(o); middle("::"); } else { genSourceLine(o->loc); start(""); } middle(o->name << '(' << o->params << ')'); if (header) { finish(";\n"); } else { finish(" :"); in(); in(); genSourceLine(o->loc); start("super_type_(" << o->args << ')'); ++inConstructor; for (auto o : memberVariables) { finish(','); genSourceLine(o->loc); start(o->name << '('); if (!o->value->isEmpty()) { middle(o->value); } else if (!o->brackets->isEmpty()) { middle("libbirch::make_shape(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } } else if (!o->args->isEmpty()) { middle(o->args); } middle(')'); } --inConstructor; out(); out(); finish(" {"); in(); line("//"); out(); line("}\n"); } /* member variables and functions */ *this << o->braces->strip(); /* end class */ if (header) { out(); line("};\n"); } /* C linkage function */ if (!o->has(ABSTRACT) && !o->isGeneric() && o->params->isEmpty()) { genSourceLine(o->loc); if (header) { start("extern \"C\" bi::type::" << o->name << "* "); finish("make_" << o->name << "_();"); } else { start("bi::type::" << o->name << "* "); finish("bi::type::make_" << o->name << "_() {"); in(); genSourceLine(o->loc); line("return new bi::type::" << o->name << "();"); genSourceLine(o->loc); out(); line("}"); } line(""); } } } void bi::CppClassGenerator::visit(const MemberVariable* o) { if (header) { line(o->type << ' ' << o->name << ';'); } } void bi::CppClassGenerator::visit(const MemberFunction* o) { if ((generic || !o->isGeneric()) && (!o->braces->isEmpty() || (header && o->has(ABSTRACT)))) { start(""); if (header) { genTemplateParams(o); genSourceLine(o->loc); if (o->typeParams->isEmpty()) { middle("virtual "); } } else { genTemplateParams(currentClass); genTemplateParams(o); genSourceLine(o->loc); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle(o->name << '(' << o->params << ')'); if (header) { if (o->has(FINAL)) { middle(" final"); } else if (o->has(OVERRIDE)) { middle(" override"); } else if (o->has(ABSTRACT)) { middle(" = 0"); } finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const MemberFiber* o) { if ((generic || !o->isGeneric()) && (!o->braces->isEmpty() || (header && o->has(ABSTRACT)))) { /* initialization function */ if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start(""); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle(o->name << '(' << o->params << ')'); if (header) { if (o->has(FINAL)) { middle(" final"); } else if (o->has(OVERRIDE)) { middle(" override"); } else if (o->has(ABSTRACT)) { middle(" = 0"); } finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); genTraceLine(o->loc); line("yield_" << currentClass->name << '_' << o->name << '_' << o->number << "_0_();"); out(); line("}\n"); } /* start function */ CppResumeGenerator auxResume(currentClass, o, base, level, header); auxResume << o->start; /* resume functions */ Gatherer<Yield> yields; o->accept(&yields); for (auto yield : yields) { if (yield->resume) { CppResumeGenerator auxResume(currentClass, o, base, level, header); auxResume << yield->resume; } } } } void bi::CppClassGenerator::visit(const AssignmentOperator* o) { if (!o->braces->isEmpty()) { if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start("bi::type::"); } middle(currentClass->name); genTemplateArgs(currentClass); middle("& "); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle("operator=(" << o->single << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<assignment>", o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); genSourceLine(o->loc); line("return *this;"); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const ConversionOperator* o) { if (!o->braces->isEmpty()) { if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle("operator " << o->returnType << "()"); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<conversion>", o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } <commit_msg>Fixed C++ code generation for generic member functions declared final.<commit_after>/** * @file */ #include "bi/io/cpp/CppClassGenerator.hpp" #include "bi/io/cpp/CppResumeGenerator.hpp" #include "bi/visitor/Gatherer.hpp" #include "bi/primitive/encode.hpp" bi::CppClassGenerator::CppClassGenerator(std::ostream& base, const int level, const bool header, const bool generic, const Class* currentClass) : CppBaseGenerator(base, level, header, generic), currentClass(currentClass) { // } void bi::CppClassGenerator::visit(const Class* o) { if (!o->isAlias() && !o->braces->isEmpty()) { currentClass = o; auto base = dynamic_cast<const NamedType*>(o->base); Gatherer<MemberFunction> memberFunctions; Gatherer<MemberFiber> memberFibers; Gatherer<MemberVariable> memberVariables; o->accept(&memberFunctions); o->accept(&memberFibers); o->accept(&memberVariables); if (header) { genTemplateParams(o); genSourceLine(o->loc); start("class " << o->name); if (o->has(FINAL)) { middle(" final"); } middle(" : public "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(" {"); line("public:"); in(); genSourceLine(o->loc); start("using class_type_ = " << o->name); genTemplateArgs(o); finish(';'); genSourceLine(o->loc); line("using this_type_ = class_type_;"); genSourceLine(o->loc); start("using super_type_ = "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(";\n"); /* using declarations for member functions and fibers in base classes * that are overridden */ std::set<std::string> names; for (auto f : memberFunctions) { auto name = f->name->str(); if (o->scope->overrides(name)) { names.insert(name); } } for (auto f : memberFibers) { auto name = f->name->str(); if (o->scope->overrides(name)) { names.insert(name); } } genSourceLine(o->loc); line("using super_type_::operator=;"); for (auto name : names) { genSourceLine(o->loc); line("using super_type_::" << internalise(name) << ';'); } line(""); } /* boilerplate */ if (header) { if (o->has(ABSTRACT)) { start("LIBBIRCH_ABSTRACT_CLASS"); } else { start("LIBBIRCH_CLASS"); } middle('(' << o->name << ", "); if (base) { middle(base->name); if (!base->typeArgs->isEmpty()) { middle('<' << base->typeArgs << '>'); } } else { middle("libbirch::Any"); } finish(')'); start("LIBBIRCH_MEMBERS("); for (auto iter = memberVariables.begin(); iter != memberVariables.end(); ++iter) { if (iter != memberVariables.begin()) { middle(", "); } middle((*iter)->name); } finish(")\n"); } /* constructor */ if (!header) { genTemplateParams(o); genSourceLine(o->loc); start("bi::type::" << o->name); genTemplateArgs(o); middle("::"); } else { genSourceLine(o->loc); start(""); } middle(o->name << '(' << o->params << ')'); if (header) { finish(";\n"); } else { finish(" :"); in(); in(); genSourceLine(o->loc); start("super_type_(" << o->args << ')'); ++inConstructor; for (auto o : memberVariables) { finish(','); genSourceLine(o->loc); start(o->name << '('); if (!o->value->isEmpty()) { middle(o->value); } else if (!o->brackets->isEmpty()) { middle("libbirch::make_shape(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } } else if (!o->args->isEmpty()) { middle(o->args); } middle(')'); } --inConstructor; out(); out(); finish(" {"); in(); line("//"); out(); line("}\n"); } /* member variables and functions */ *this << o->braces->strip(); /* end class */ if (header) { out(); line("};\n"); } /* C linkage function */ if (!o->has(ABSTRACT) && !o->isGeneric() && o->params->isEmpty()) { genSourceLine(o->loc); if (header) { start("extern \"C\" bi::type::" << o->name << "* "); finish("make_" << o->name << "_();"); } else { start("bi::type::" << o->name << "* "); finish("bi::type::make_" << o->name << "_() {"); in(); genSourceLine(o->loc); line("return new bi::type::" << o->name << "();"); genSourceLine(o->loc); out(); line("}"); } line(""); } } } void bi::CppClassGenerator::visit(const MemberVariable* o) { if (header) { line(o->type << ' ' << o->name << ';'); } } void bi::CppClassGenerator::visit(const MemberFunction* o) { if ((generic || !o->isGeneric()) && (!o->braces->isEmpty() || (header && o->has(ABSTRACT)))) { start(""); if (header) { genTemplateParams(o); genSourceLine(o->loc); if (o->typeParams->isEmpty()) { middle("virtual "); } } else { genTemplateParams(currentClass); genTemplateParams(o); genSourceLine(o->loc); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle(o->name << '(' << o->params << ')'); if (header) { if (o->has(FINAL) && !o->isGeneric()) { middle(" final"); } else if (o->has(OVERRIDE)) { middle(" override"); } else if (o->has(ABSTRACT)) { middle(" = 0"); } finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const MemberFiber* o) { if ((generic || !o->isGeneric()) && (!o->braces->isEmpty() || (header && o->has(ABSTRACT)))) { /* initialization function */ if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start(""); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle(o->name << '(' << o->params << ')'); if (header) { if (o->has(FINAL) && !o->isGeneric()) { middle(" final"); } else if (o->has(OVERRIDE)) { middle(" override"); } else if (o->has(ABSTRACT)) { middle(" = 0"); } finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); genTraceLine(o->loc); line("yield_" << currentClass->name << '_' << o->name << '_' << o->number << "_0_();"); out(); line("}\n"); } /* start function */ CppResumeGenerator auxResume(currentClass, o, base, level, header); auxResume << o->start; /* resume functions */ Gatherer<Yield> yields; o->accept(&yields); for (auto yield : yields) { if (yield->resume) { CppResumeGenerator auxResume(currentClass, o, base, level, header); auxResume << yield->resume; } } } } void bi::CppClassGenerator::visit(const AssignmentOperator* o) { if (!o->braces->isEmpty()) { if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start("bi::type::"); } middle(currentClass->name); genTemplateArgs(currentClass); middle("& "); if (!header) { middle("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle("operator=(" << o->single << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<assignment>", o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); genSourceLine(o->loc); line("return *this;"); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const ConversionOperator* o) { if (!o->braces->isEmpty()) { if (header) { genSourceLine(o->loc); start("virtual "); } else { genTemplateParams(currentClass); genSourceLine(o->loc); start("bi::type::" << currentClass->name); genTemplateArgs(currentClass); middle("::"); } middle("operator " << o->returnType << "()"); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<conversion>", o->loc); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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/>. */ #pragma warning(push) // choorucode.com/2010/08/30/visual-c-c4996-warning-on-copy-with-array-parameters #pragma warning(disable: 4996) #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/test/unit_test.hpp> #pragma warning(pop) #include <bitcoin/bitcoin.hpp> #include "script_json/vectors.hpp" using namespace bc; bool is_number(const std::string& token) { if (boost::all(token, boost::is_digit())) return true; // Now check for negative numbers if (!boost::starts_with(token, "-")) return false; std::string numeric_part(token.begin() + 1, token.end()); return boost::all(numeric_part, boost::is_digit()); } bool is_hex_data(const std::string& token) { if (!boost::starts_with(token, "0x")) return false; std::string hex_part(token.begin() + 2, token.end()); return boost::all(hex_part, [](char c) { return std::isxdigit(c); }); } bool is_quoted_string(const std::string& token) { if (token.size() < 2) return false; return boost::starts_with(token, "'") && boost::ends_with(token, "'"); } opcode token_to_opcode(const std::string& token) { std::string lower_token = token; boost::algorithm::to_lower(lower_token); return string_to_opcode(lower_token); } bool is_opcode(const std::string& token) { return token_to_opcode(token) != opcode::bad_operation; } bool is_opx(int64_t value) { return value == -1 || (1 <= value && value <= 16); } void push_literal(data_chunk& raw_script, int64_t value) { BITCOIN_ASSERT(is_opx(value)); switch (value) { case -1: raw_script.push_back(static_cast<uint8_t>(opcode::negative_1)); return; #define PUSH_X(n) \ case n: \ raw_script.push_back(static_cast<uint8_t>(opcode::op_##n)); \ return; PUSH_X(1); PUSH_X(2); PUSH_X(3); PUSH_X(4); PUSH_X(5); PUSH_X(6); PUSH_X(7); PUSH_X(8); PUSH_X(9); PUSH_X(10); PUSH_X(11); PUSH_X(12); PUSH_X(13); PUSH_X(14); PUSH_X(15); PUSH_X(16); } } void push_data(data_chunk& raw_script, const data_chunk& data) { operation op; // pushdata1 = 76 if (data.empty()) op.code = opcode::zero; else if (data.size() < 76) op.code = opcode::special; else if (data.size() <= 0xff) op.code = opcode::pushdata1; else if (data.size() <= 0xffff) op.code = opcode::pushdata2; else { BITCOIN_ASSERT(data.size() <= 0xffffffff); op.code = opcode::pushdata4; } op.data = data; script_type tmp_script; tmp_script.push_operation(op); extend_data(raw_script, save_script(tmp_script)); } bool parse_token(data_chunk& raw_script, std::string token) { boost::algorithm::trim(token); // skip this if (token.empty()) return true; static data_chunk hex_raw; if (token == "ENDING" || !is_hex_data(token)) { if (!hex_raw.empty()) { extend_data(raw_script, hex_raw); hex_raw.resize(0); } } if (token == "ENDING") { // Do nothing... } else if (is_number(token)) { int64_t value = boost::lexical_cast<int64_t>(token); if (is_opx(value)) push_literal(raw_script, value); else { script_number bignum(value); push_data(raw_script, bignum.data()); } } else if (is_hex_data(token)) { std::string hex_part(token.begin() + 2, token.end()); data_chunk raw_data = decode_hex(hex_part); extend_data(hex_raw, raw_data); } else if (is_quoted_string(token)) { data_chunk inner_value(token.begin() + 1, token.end() - 1); push_data(raw_script, inner_value); } else if (is_opcode(token)) { opcode tokenized_opcode = token_to_opcode(token); raw_script.push_back(static_cast<uint8_t>(tokenized_opcode)); } else { log_error() << "Token parsing failed with: " << token; return false; } return true; } bool parse(script_type& result_script, std::string format) { boost::algorithm::trim(format); if (format.empty()) return true; std::vector<std::string> tokens; boost::split(tokens, format, boost::is_any_of(" ")); data_chunk raw_script; for (const auto& token: tokens) if (!parse_token(raw_script, token)) return false; parse_token(raw_script, "ENDING"); try { result_script = parse_script(raw_script); } catch (end_of_stream) { return false; } if (result_script.operations().empty()) return false; return true; } bool run_script(const script_test& test) { script_type input, output; if (!parse(input, test.input)) return false; if (!parse(output, test.output)) return false; transaction_type tx; //log_debug() << test.input << " -> " << input; //log_debug() << test.output << " -> " << output; return output.run(input, tx, 0); } void ignore_output(log_level, const std::string&, const std::string&) { } BOOST_AUTO_TEST_SUITE(script_tests) BOOST_AUTO_TEST_CASE(script_json_valid) { for (const script_test& test: valid_scripts) { BOOST_REQUIRE(run_script(test)); } } BOOST_AUTO_TEST_CASE(script_json_invalid) { // Shut up! log_fatal().set_output_function(ignore_output); for (const script_test& test: invalid_scripts) { BOOST_REQUIRE(!run_script(test)); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Conditionally include warning suppression pragmas (VC builds only).<commit_after>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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/>. */ #ifdef _MSC_VER #pragma warning(push) // choorucode.com/2010/08/30/visual-c-c4996-warning-on-copy-with-array-parameters #pragma warning(disable: 4996) #endif #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/test/unit_test.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <bitcoin/bitcoin.hpp> #include "script_json/vectors.hpp" using namespace bc; bool is_number(const std::string& token) { if (boost::all(token, boost::is_digit())) return true; // Now check for negative numbers if (!boost::starts_with(token, "-")) return false; std::string numeric_part(token.begin() + 1, token.end()); return boost::all(numeric_part, boost::is_digit()); } bool is_hex_data(const std::string& token) { if (!boost::starts_with(token, "0x")) return false; std::string hex_part(token.begin() + 2, token.end()); return boost::all(hex_part, [](char c) { return std::isxdigit(c); }); } bool is_quoted_string(const std::string& token) { if (token.size() < 2) return false; return boost::starts_with(token, "'") && boost::ends_with(token, "'"); } opcode token_to_opcode(const std::string& token) { std::string lower_token = token; boost::algorithm::to_lower(lower_token); return string_to_opcode(lower_token); } bool is_opcode(const std::string& token) { return token_to_opcode(token) != opcode::bad_operation; } bool is_opx(int64_t value) { return value == -1 || (1 <= value && value <= 16); } void push_literal(data_chunk& raw_script, int64_t value) { BITCOIN_ASSERT(is_opx(value)); switch (value) { case -1: raw_script.push_back(static_cast<uint8_t>(opcode::negative_1)); return; #define PUSH_X(n) \ case n: \ raw_script.push_back(static_cast<uint8_t>(opcode::op_##n)); \ return; PUSH_X(1); PUSH_X(2); PUSH_X(3); PUSH_X(4); PUSH_X(5); PUSH_X(6); PUSH_X(7); PUSH_X(8); PUSH_X(9); PUSH_X(10); PUSH_X(11); PUSH_X(12); PUSH_X(13); PUSH_X(14); PUSH_X(15); PUSH_X(16); } } void push_data(data_chunk& raw_script, const data_chunk& data) { operation op; // pushdata1 = 76 if (data.empty()) op.code = opcode::zero; else if (data.size() < 76) op.code = opcode::special; else if (data.size() <= 0xff) op.code = opcode::pushdata1; else if (data.size() <= 0xffff) op.code = opcode::pushdata2; else { BITCOIN_ASSERT(data.size() <= 0xffffffff); op.code = opcode::pushdata4; } op.data = data; script_type tmp_script; tmp_script.push_operation(op); extend_data(raw_script, save_script(tmp_script)); } bool parse_token(data_chunk& raw_script, std::string token) { boost::algorithm::trim(token); // skip this if (token.empty()) return true; static data_chunk hex_raw; if (token == "ENDING" || !is_hex_data(token)) { if (!hex_raw.empty()) { extend_data(raw_script, hex_raw); hex_raw.resize(0); } } if (token == "ENDING") { // Do nothing... } else if (is_number(token)) { int64_t value = boost::lexical_cast<int64_t>(token); if (is_opx(value)) push_literal(raw_script, value); else { script_number bignum(value); push_data(raw_script, bignum.data()); } } else if (is_hex_data(token)) { std::string hex_part(token.begin() + 2, token.end()); data_chunk raw_data = decode_hex(hex_part); extend_data(hex_raw, raw_data); } else if (is_quoted_string(token)) { data_chunk inner_value(token.begin() + 1, token.end() - 1); push_data(raw_script, inner_value); } else if (is_opcode(token)) { opcode tokenized_opcode = token_to_opcode(token); raw_script.push_back(static_cast<uint8_t>(tokenized_opcode)); } else { log_error() << "Token parsing failed with: " << token; return false; } return true; } bool parse(script_type& result_script, std::string format) { boost::algorithm::trim(format); if (format.empty()) return true; std::vector<std::string> tokens; boost::split(tokens, format, boost::is_any_of(" ")); data_chunk raw_script; for (const auto& token: tokens) if (!parse_token(raw_script, token)) return false; parse_token(raw_script, "ENDING"); try { result_script = parse_script(raw_script); } catch (end_of_stream) { return false; } if (result_script.operations().empty()) return false; return true; } bool run_script(const script_test& test) { script_type input, output; if (!parse(input, test.input)) return false; if (!parse(output, test.output)) return false; transaction_type tx; //log_debug() << test.input << " -> " << input; //log_debug() << test.output << " -> " << output; return output.run(input, tx, 0); } void ignore_output(log_level, const std::string&, const std::string&) { } BOOST_AUTO_TEST_SUITE(script_tests) BOOST_AUTO_TEST_CASE(script_json_valid) { for (const script_test& test: valid_scripts) { BOOST_REQUIRE(run_script(test)); } } BOOST_AUTO_TEST_CASE(script_json_invalid) { // Shut up! log_fatal().set_output_function(ignore_output); for (const script_test& test: invalid_scripts) { BOOST_REQUIRE(!run_script(test)); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/*********************************************************************** test/string.cpp - Tests the behavior of mysqlpp::String, particularly its data conversion methods. Copyright (c) 2007-2008 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <mysql++.h> #include <iostream> // Does an equality comparison on the value, forcing the string to // convert itself to T on the way. Note that we do this test in terms // of greater and less than to avoid pedantic GCC warnings for the // floating point type tests. template <typename T> static bool test_equality(const mysqlpp::String& s, T value) { T converted = s.conv(value); if ((value < converted) || (value > converted)) { std::cerr << "Type conversion to " << typeid(T).name() << " failed: \"" << s << "\" != \"" << value << "\"." << std::endl; return false; } else { return true; } } // Check that we can convert strings with decimals in them to native // floating-point values, regardless of locale. static bool test_float_conversion() { // This stuff should just work if (!test_equality(mysqlpp::String("123.00"), 123)) return false; if (!test_equality(mysqlpp::String("123."), 123)) return false; // This is trickier: MySQL ignores the system locale when it comes // to decimal separators, always using '.', so ensure the conversion // stuff in MySQL++ does the right thing regardless. Test against // this system's current locale, an arbitrary European one where ',' // is the decimal separator, and the "C" locale where it's '.'. if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale old_locale = std::locale::global(std::locale::classic()); if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale::global(std::locale("de_DE")); if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale::global(old_locale); // Check that we choke on silly float-like values try { if (test_equality(mysqlpp::String("621.20.0"), 621.2)) { std::cerr << "Quasi-FP with two decimal points " "converting without error!" << std::endl; } return false; } catch (const mysqlpp::BadConversion&) { return true; } } // Tries to convert the given string to an int. Returns false if we got // a BadConversion exception and didn't expect it, or didn't get one we // expected. Returns false on all other exceptions regardless. static bool test_int_conversion(const mysqlpp::String& s, bool throw_expected) { // Try the conversion bool conv_threw = false; try { int converted = s; (void)converted; // pedantic warning squisher } catch (const mysqlpp::BadConversion&) { conv_threw = true; } catch (const std::exception& e) { std::cerr << "Unexpected " << typeid(e).name() << " exception in test_int_conv: " << e.what() << std::endl; return false; } catch (...) { std::cerr << "Like, totally bogus exception in test_int_conv, " "man!" << std::endl; return false; } // Did it do what we expected? if (throw_expected == conv_threw) { return true; } else { std::cerr << "Conversion of \"" << s << "\" to int " << (conv_threw ? "did not " : "") << "throw; did " << (throw_expected ? "not " : "") << "expect it to." << std::endl; return false; } } // Ensures that the program's locale doesn't affect our floating-point // conversions. ('.' vs. ',' stuff.) static bool test_locale() { return true; } // Ensures numeric conversions of many different types get handled // correctly. static bool test_numeric(const mysqlpp::String& s, int value) { return test_equality(s, static_cast<signed char>(value)) && test_equality(s, static_cast<unsigned char>(value)) && test_equality(s, static_cast<signed short>(value)) && test_equality(s, static_cast<unsigned short>(value)) && test_equality(s, static_cast<signed int>(value)) && test_equality(s, static_cast<unsigned int>(value)) && test_equality(s, static_cast<signed long>(value)) && test_equality(s, static_cast<unsigned long>(value)) && #if !defined(NO_LONG_LONGS) test_equality(s, static_cast<mysqlpp::longlong>(value)) && test_equality(s, static_cast<mysqlpp::ulonglong>(value)) && #endif test_equality(s, static_cast<float>(value)) && test_equality(s, static_cast<double>(value)); } static bool test_quote_q(const mysqlpp::String& s, bool expected) { if (s.quote_q() == expected) { return true; } else { std::cerr << s.type().name() << " should" << (expected ? "" : " NOT") << " be quoted." << std::endl; return false; } } int main(int, char* argv[]) { try { int failures = 0; mysqlpp::String empty; mysqlpp::String zero("0"); mysqlpp::String nonzero("42"); failures += test_equality(empty, mysqlpp::Date()) == false; failures += test_equality(empty, mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false; failures += test_equality(empty, mysqlpp::Time()) == false; failures += test_equality(empty, false) == false; failures += test_equality(nonzero, true) == false; failures += test_numeric(empty, 0) == false; failures += test_numeric(zero, 0) == false; failures += test_numeric(nonzero, 42) == false; failures += test_quote_q(empty, true) == false; failures += test_quote_q(mysqlpp::String("1", typeid(int)), false) == false; failures += test_locale() == false; failures += test_float_conversion() == false; failures += test_float_conversion() == false; return failures; } catch (mysqlpp::Exception& e) { std::cerr << "Unexpected MySQL++ exception caught in " << argv[0] << ": " << e.what() << std::endl; return 1; } catch (std::exception& e) { std::cerr << "Unexpected C++ exception caught in " << argv[0] << ": " << e.what() << std::endl; return 1; } } <commit_msg>Wrote a test case for test/string.cpp that wasn't getting called. (Ooopsie.) Made up several ways to call it, so now we know string to int conversions are working.<commit_after>/*********************************************************************** test/string.cpp - Tests the behavior of mysqlpp::String, particularly its data conversion methods. Copyright (c) 2007-2008 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <mysql++.h> #include <iostream> // Does an equality comparison on the value, forcing the string to // convert itself to T on the way. Note that we do this test in terms // of greater and less than to avoid pedantic GCC warnings for the // floating point type tests. template <typename T> static bool test_equality(const mysqlpp::String& s, T value) { T converted = s.conv(value); if ((value < converted) || (value > converted)) { std::cerr << "Type conversion to " << typeid(T).name() << " failed: \"" << s << "\" != \"" << value << "\"." << std::endl; return false; } else { return true; } } // Check that we can convert strings with decimals in them to native // floating-point values, regardless of locale. static bool test_float_conversion() { // This stuff should just work if (!test_equality(mysqlpp::String("123.00"), 123)) return false; if (!test_equality(mysqlpp::String("123."), 123)) return false; // This is trickier: MySQL ignores the system locale when it comes // to decimal separators, always using '.', so ensure the conversion // stuff in MySQL++ does the right thing regardless. Test against // this system's current locale, an arbitrary European one where ',' // is the decimal separator, and the "C" locale where it's '.'. if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale old_locale = std::locale::global(std::locale::classic()); if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale::global(std::locale("de_DE")); if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false; std::locale::global(old_locale); // Check that we choke on silly float-like values try { if (test_equality(mysqlpp::String("621.20.0"), 621.2)) { std::cerr << "Quasi-FP with two decimal points " "converting without error!" << std::endl; } return false; } catch (const mysqlpp::BadConversion&) { return true; } } // Tries to convert the given string to an int. Returns false if we got // a BadConversion exception and didn't expect it, or didn't get one we // expected. Returns false on all other exceptions regardless. static bool test_int_conversion(const mysqlpp::String& s, bool throw_expected) { // Try the conversion bool conv_threw = false; try { int converted = s; (void)converted; // pedantic warning squisher } catch (const mysqlpp::BadConversion&) { conv_threw = true; } catch (const std::exception& e) { std::cerr << "Unexpected " << typeid(e).name() << " exception in test_int_conv: " << e.what() << std::endl; return false; } catch (...) { std::cerr << "Like, totally bogus exception in test_int_conv, " "man!" << std::endl; return false; } // Did it do what we expected? if (throw_expected == conv_threw) { return true; } else { std::cerr << "Conversion of \"" << s << "\" to int " << (conv_threw ? "did not throw" : "threw") << "; " << (throw_expected ? "did not expect" : "expected") << " it to." << std::endl; return false; } } // Ensures that the program's locale doesn't affect our floating-point // conversions. ('.' vs. ',' stuff.) static bool test_locale() { return true; } // Ensures numeric conversions of many different types get handled // correctly. static bool test_numeric(const mysqlpp::String& s, int value) { return test_equality(s, static_cast<signed char>(value)) && test_equality(s, static_cast<unsigned char>(value)) && test_equality(s, static_cast<signed short>(value)) && test_equality(s, static_cast<unsigned short>(value)) && test_equality(s, static_cast<signed int>(value)) && test_equality(s, static_cast<unsigned int>(value)) && test_equality(s, static_cast<signed long>(value)) && test_equality(s, static_cast<unsigned long>(value)) && #if !defined(NO_LONG_LONGS) test_equality(s, static_cast<mysqlpp::longlong>(value)) && test_equality(s, static_cast<mysqlpp::ulonglong>(value)) && #endif test_equality(s, static_cast<float>(value)) && test_equality(s, static_cast<double>(value)); } static bool test_quote_q(const mysqlpp::String& s, bool expected) { if (s.quote_q() == expected) { return true; } else { std::cerr << s.type().name() << " should" << (expected ? "" : " NOT") << " be quoted." << std::endl; return false; } } int main(int, char* argv[]) { try { int failures = 0; mysqlpp::String empty; mysqlpp::String zero("0"); mysqlpp::String nonzero("42"); mysqlpp::String intable1("42."); mysqlpp::String intable2("42.0"); mysqlpp::String nonint("42.1"); failures += test_equality(empty, mysqlpp::Date()) == false; failures += test_equality(empty, mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false; failures += test_equality(empty, mysqlpp::Time()) == false; failures += test_equality(empty, false) == false; failures += test_equality(nonzero, true) == false; failures += test_numeric(empty, 0) == false; failures += test_numeric(zero, 0) == false; failures += test_numeric(nonzero, 42) == false; failures += test_quote_q(empty, true) == false; failures += test_quote_q(mysqlpp::String("1", typeid(int)), false) == false; failures += test_locale() == false; failures += test_float_conversion() == false; failures += test_float_conversion() == false; failures += test_int_conversion(empty, false) == false; failures += test_int_conversion(zero, false) == false; failures += test_int_conversion(nonzero, false) == false; failures += test_int_conversion(intable1, false) == false; failures += test_int_conversion(intable2, false) == false; failures += test_int_conversion(nonint, true) == false; return failures; } catch (mysqlpp::Exception& e) { std::cerr << "Unexpected MySQL++ exception caught in " << argv[0] << ": " << e.what() << std::endl; return 1; } catch (std::exception& e) { std::cerr << "Unexpected C++ exception caught in " << argv[0] << ": " << e.what() << std::endl; return 1; } } <|endoftext|>
<commit_before>#include "Math/Polynomial.h" #include "Math/Derivator.h" #include "Math/IFunction.h" #include "Math/Functor.h" #include "Math/WrappedFunction.h" #include "Math/WrappedParamFunction.h" #include <iostream> #include <vector> #include <cassert> #include <cmath> #ifdef HAVE_ROOTLIBS #include "TStopwatch.h" #include "TF1.h" #include "Math/WrappedTF1.h" #include "Math/WrappedMultiTF1.h" #include "Math/DistFunc.h" #endif const double ERRORLIMIT = 1E-5; typedef double ( * FP ) ( double, void * ); typedef double ( * FP2 ) ( double ); double myfunc ( double x, void * ) { return std::pow( x, 1.5); } double myfunc2 ( double x) { return std::pow( x, 1.5); } int testDerivation() { int status = 0; // Derivative of an IGenFunction // Works when compiled c++, compiled ACLiC, interpreted by CINT ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2); std::vector<double> p(3); p[0] = 2; p[1] = 3; p[2] = 4; f1->SetParameters(&p[0]); ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1); double step = 1E-8; double x0 = 2; der->SetFunction(*f1); double result = der->Eval(x0); std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl; std::cout << "Return code: " << der->Status() << std::endl; std::cout << "Result: " << result << " +/- " << der->Error() << std::endl; std::cout << "Exact result: " << f1->Derivative(x0) << std::endl; std::cout << "EvalForward: " << der->EvalForward(*f1, x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;; status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT; // Derivative of a free function // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT FP f2 = &myfunc; der->SetFunction(f2); std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl; std::cout << "EvalCentral: " << der->EvalCentral(x0) << std::endl; std::cout << "EvalForward: " << der->EvalForward(x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl; std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl; status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; // Derivative of a free function wrapped in an IGenFunction // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2); std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl; std::cout << "EvalCentral: " << der->Eval( *f3, x0) << std::endl; der->SetFunction(*f3); std::cout << "EvalForward: " << der->EvalForward(x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl; std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl; status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; // tets case when an empty Derivator is used ROOT::Math::Derivator der2; std::cout << "Tes a derivator without a function" << std::endl; std::cout << der2.Eval(1.0) << std::endl; // Derivative of a multidim TF1 function // #ifdef LATER // TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10); // // find gradient at x={1,1} // double vx[2] = {1.,2.}; // ROOT::Math::WrappedTF1 fx(*f2d); // std::cout << "Derivative of a f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl; // std::cout << "df/dx = " << der->EvalCentral(fx,1.) << std::endl; // WrappedFunc fy(*f2d,0,vx); // std::cout << "df/dy = " << der->EvalCentral(fy,2.) << std::endl; // #endif return status; } #ifdef HAVE_ROOTLIBS void testDerivPerf() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances....\n\n"; ROOT::Math::Polynomial f1(2); double p[3] = {2,3,4}; f1.SetParameters(p); TStopwatch timer; int n = 1000000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; ROOT::Math::Derivator der(f1); for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= der.EvalCentral(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { ROOT::Math::Derivator der2(f1); double x = x1 + dx*i; s1+= der2.EvalForward(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); TF1 f2("pol","pol2",0,10); f2.SetParameters(p); timer.Start(); double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= f2.Derivative(x); } timer.Stop(); std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s2 << std::endl; std::cout.precision(pr); } double userFunc(const double *x, const double *y) { return std::exp(-x[0]); } double userFunc1(double x) { return userFunc(&x, 0); } double userFunc2(const double * x) { return userFunc(x, 0); } void testDerivPerfUser() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances - using a User function\n\n"; ROOT::Math::WrappedFunction<> f1(userFunc1); TStopwatch timer; int n = 1000000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; ROOT::Math::Derivator der(f1); for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= der.EvalCentral(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { ROOT::Math::Derivator der2(f1); double x = x1 + dx*i; s1+= der2.EvalForward(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); TF1 f2("uf",userFunc,0,10,0); timer.Start(); double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= f2.Derivative(x); } timer.Stop(); std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s2 << std::endl; std::cout.precision(pr); //typedef double( * FN ) (const double *, const double * ); ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1); timer.Start(); s1 = 0; double xx[1]; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f3,xx,0); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } double gausFunc( const double * x, const double * p) { return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] ); } void testDerivPerfParam() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances - using a Gaussian Param function\n\n"; //TF1 gaus("gaus","gaus",-10,10); TF1 gaus("gaus",gausFunc,-10,10,3); double params[3] = {10,1.,1.}; gaus.SetParameters(params); ROOT::Math::WrappedTF1 f1(gaus); TStopwatch timer; int n = 300000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; // param derivatives s1 += ROOT::Math::Derivator::Eval(f1,x,params,0); s1 += ROOT::Math::Derivator::Eval(f1,x,params,1); s1 += ROOT::Math::Derivator::Eval(f1,x,params,2); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3); double xx[1]; timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0); s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1); s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); // test that func parameters have not been changed assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15); assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15); assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15); timer.Start(); s1 = 0; double g[3]; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; gaus.GradientPar(xx,g,1E-8); s1 += g[0]; s1 += g[1]; s1 += g[2]; } timer.Stop(); std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } #endif int main() { int status = 0; status += testDerivation(); #ifdef HAVE_ROOTLIBS testDerivPerf(); testDerivPerfUser(); testDerivPerfParam(); #endif return status; } <commit_msg>Fix a warning<commit_after>#include "Math/Polynomial.h" #include "Math/Derivator.h" #include "Math/IFunction.h" #include "Math/Functor.h" #include "Math/WrappedFunction.h" #include "Math/WrappedParamFunction.h" #include <iostream> #include <vector> #include <cassert> #include <cmath> #ifdef HAVE_ROOTLIBS #include "TStopwatch.h" #include "TF1.h" #include "Math/WrappedTF1.h" #include "Math/WrappedMultiTF1.h" #include "Math/DistFunc.h" #endif const double ERRORLIMIT = 1E-5; typedef double ( * FP ) ( double, void * ); typedef double ( * FP2 ) ( double ); double myfunc ( double x, void * ) { return std::pow( x, 1.5); } double myfunc2 ( double x) { return std::pow( x, 1.5); } int testDerivation() { int status = 0; // Derivative of an IGenFunction // Works when compiled c++, compiled ACLiC, interpreted by CINT ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2); std::vector<double> p(3); p[0] = 2; p[1] = 3; p[2] = 4; f1->SetParameters(&p[0]); ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1); double step = 1E-8; double x0 = 2; der->SetFunction(*f1); double result = der->Eval(x0); std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl; std::cout << "Return code: " << der->Status() << std::endl; std::cout << "Result: " << result << " +/- " << der->Error() << std::endl; std::cout << "Exact result: " << f1->Derivative(x0) << std::endl; std::cout << "EvalForward: " << der->EvalForward(*f1, x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;; status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT; // Derivative of a free function // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT FP f2 = &myfunc; der->SetFunction(f2); std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl; std::cout << "EvalCentral: " << der->EvalCentral(x0) << std::endl; std::cout << "EvalForward: " << der->EvalForward(x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl; std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl; status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; // Derivative of a free function wrapped in an IGenFunction // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2); std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl; std::cout << "EvalCentral: " << der->Eval( *f3, x0) << std::endl; der->SetFunction(*f3); std::cout << "EvalForward: " << der->EvalForward(x0) << std::endl; std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl; std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl; status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT; // tets case when an empty Derivator is used ROOT::Math::Derivator der2; std::cout << "Tes a derivator without a function" << std::endl; std::cout << der2.Eval(1.0) << std::endl; // Derivative of a multidim TF1 function // #ifdef LATER // TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10); // // find gradient at x={1,1} // double vx[2] = {1.,2.}; // ROOT::Math::WrappedTF1 fx(*f2d); // std::cout << "Derivative of a f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl; // std::cout << "df/dx = " << der->EvalCentral(fx,1.) << std::endl; // WrappedFunc fy(*f2d,0,vx); // std::cout << "df/dy = " << der->EvalCentral(fy,2.) << std::endl; // #endif return status; } #ifdef HAVE_ROOTLIBS void testDerivPerf() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances....\n\n"; ROOT::Math::Polynomial f1(2); double p[3] = {2,3,4}; f1.SetParameters(p); TStopwatch timer; int n = 1000000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; ROOT::Math::Derivator der(f1); for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= der.EvalCentral(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { ROOT::Math::Derivator der2(f1); double x = x1 + dx*i; s1+= der2.EvalForward(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); TF1 f2("pol","pol2",0,10); f2.SetParameters(p); timer.Start(); double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= f2.Derivative(x); } timer.Stop(); std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s2 << std::endl; std::cout.precision(pr); } double userFunc(const double *x, const double *) { return std::exp(-x[0]); } double userFunc1(double x) { return userFunc(&x, 0); } double userFunc2(const double * x) { return userFunc(x, 0); } void testDerivPerfUser() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances - using a User function\n\n"; ROOT::Math::WrappedFunction<> f1(userFunc1); TStopwatch timer; int n = 1000000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; ROOT::Math::Derivator der(f1); for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= der.EvalCentral(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { ROOT::Math::Derivator der2(f1); double x = x1 + dx*i; s1+= der2.EvalForward(x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); TF1 f2("uf",userFunc,0,10,0); timer.Start(); double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= f2.Derivative(x); } timer.Stop(); std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s2 << std::endl; std::cout.precision(pr); //typedef double( * FN ) (const double *, const double * ); ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1); timer.Start(); s1 = 0; double xx[1]; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; s1+= ROOT::Math::Derivator::Eval(f3,xx,0); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } double gausFunc( const double * x, const double * p) { return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] ); } void testDerivPerfParam() { std::cout << "\n\n***************************************************************\n"; std::cout << "Test derivation performances - using a Gaussian Param function\n\n"; //TF1 gaus("gaus","gaus",-10,10); TF1 gaus("gaus",gausFunc,-10,10,3); double params[3] = {10,1.,1.}; gaus.SetParameters(params); ROOT::Math::WrappedTF1 f1(gaus); TStopwatch timer; int n = 300000; double x1 = 0; double x2 = 10; double dx = (x2-x1)/double(n); timer.Start(); double s1 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; // param derivatives s1 += ROOT::Math::Derivator::Eval(f1,x,params,0); s1 += ROOT::Math::Derivator::Eval(f1,x,params,1); s1 += ROOT::Math::Derivator::Eval(f1,x,params,2); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3); double xx[1]; timer.Start(); s1 = 0; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0); s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1); s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2); } timer.Stop(); std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); // test that func parameters have not been changed assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15); assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15); assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15); timer.Start(); s1 = 0; double g[3]; for (int i = 0; i < n; ++i) { xx[0] = x1 + dx*i; gaus.GradientPar(xx,g,1E-8); s1 += g[0]; s1 += g[1]; s1 += g[2]; } timer.Stop(); std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } #endif int main() { int status = 0; status += testDerivation(); #ifdef HAVE_ROOTLIBS testDerivPerf(); testDerivPerfUser(); testDerivPerfParam(); #endif return status; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <Context.h> #include <Filter.h> #include <sstream> #include <algorithm> #include <i18n.h> #include <util.h> #include <text.h> #include <CmdContext.h> #include <CmdConfig.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdContext::CmdContext () { _keyword = "context"; _usage = "task context [<name> | subcommand]"; _description = STRING_CMD_CONTEXT_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdContext::execute (std::string& output) { int rc = 0; std::stringstream out; // Get the non-attribute, non-fancy command line arguments. std::vector <std::string> words = context.cli.getWords (); if (words.size () > 0) { std::string subcommand = words[0]; if (subcommand == "define") rc = defineContext (words, out); else if (subcommand == "delete") rc = deleteContext (words, out); else if (subcommand == "list") rc = listContexts (words, out); else if (subcommand == "none") rc = unsetContext (words, out); else if (subcommand == "show") rc = showContext (words, out); else rc = setContext (words, out); } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// // Joins all the words in the specified interval <from, to) to one string, // which is then returned. // // If to is specified as 0 (default value), all the remaining words will be joined. // std::string CmdContext::joinWords (std::vector <std::string>& words, unsigned int from, unsigned int to /* = 0 */) { std::string value = ""; if (to == 0) to = words.size(); for (unsigned int i = from; i < to; ++i) { if (i > from) value += " "; value += words[i]; } return value; } //////////////////////////////////////////////////////////////////////////////// // Returns all user defined contexts. // std::vector <std::string> CmdContext::getContexts () { std::vector <std::string> contexts; for (auto& name : context.config) if (name.first.substr (0, 8) == "context.") contexts.push_back (name.first.substr (8)); return contexts; } //////////////////////////////////////////////////////////////////////////////// // Defines a new user-provided context. // - The context definition is written into .taskrc as a context.<name> variable. // - Deletion of the context requires confirmation if rc.confirmation=yes. // // Returns: 0 if the addition of the config variable was successful, 1 otherwise // // Invoked with: task context define <name> <filter> // Example: task context define home project:Home // int CmdContext::defineContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; bool confirmation = context.config.getBoolean ("confirmation"); if (words.size () > 2) { std::string name = "context." + words[1]; std::string value = joinWords (words, 2); // Check if the value is a proper filter by filtering current pending.data Filter filter; std::vector <Task> filtered; auto pending = context.tdb2.pending.get_tasks (); try { // This result is not used, and is just to check validity. context.cli.addRawFilter ("( " + value + " )"); filter.subset (pending, filtered); } catch (std::string exception) { throw format (STRING_CMD_CONTEXT_DEF_ABRT2, exception); } // Make user explicitly confirm filters that are matching no pending tasks if (filtered.size () == 0) if (confirmation && ! confirm (format (STRING_CMD_CONTEXT_DEF_CONF, value))) throw std::string (STRING_CMD_CONTEXT_DEF_ABRT); // Set context definition config variable bool success = CmdConfig::setConfigVariable (name, value, confirmation); if (success) out << format (STRING_CMD_CONTEXT_DEF_SUCC, words[1]) << "\n"; else { out << format (STRING_CMD_CONTEXT_DEF_FAIL, words[1]) << "\n"; rc = 1; } } else { out << STRING_CMD_CONTEXT_DEF_USAG << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Deletes the specified context. // - If the deleted context is currently active, unset it. // - Deletion of the context requires confirmation if rc.confirmation=yes. // // Returns: 0 if the removal of the config variable was successful, 1 otherwise // // Invoked with: task context delete <name> // Example: task context delete home // int CmdContext::deleteContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; if (words.size () > 1) { // Delete the specified context std::string name = "context." + words[1]; bool confirmation = context.config.getBoolean ("confirmation"); rc = CmdConfig::unsetConfigVariable(name, confirmation); // If the currently set context was deleted, unset it std::string currentContext = context.config.get ("context"); if (currentContext == words[1]) CmdConfig::unsetConfigVariable("context", false); // Output feedback if (rc == 0) out << format (STRING_CMD_CONTEXT_DEL_SUCC, words[1]) << "\n"; else out << format (STRING_CMD_CONTEXT_DEL_FAIL, words[1]) << "\n"; } else { out << STRING_CMD_CONTEXT_DEL_USAG << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Render a list of context names and their definitions. // // Returns: 0 the resulting list is non-empty, 1 otherwise // // Invoked with: task context list // Example: task context list // int CmdContext::listContexts (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; std::vector <std::string> contexts = getContexts(); if (contexts.size ()) { std::sort (contexts.begin (), contexts.end ()); ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", "Name")); view.add (Column::factory ("string", "Definition")); view.add (Column::factory ("string", "Active")); Color label (context.config.get ("color.label")); view.colorHeader (label); std::string activeContext = context.config.get ("context"); for (auto& userContext : contexts) { std::string definition = context.config.get ("context." + userContext); std::string active = "no"; if (userContext == activeContext) active = "yes"; int row = view.addRow (); view.set (row, 0, userContext); view.set (row, 1, definition); view.set (row, 2, active); } out << optionalBlankLine () << view.render () << optionalBlankLine (); } else { out << STRING_CMD_CONTEXT_LIST_EMPT << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Sets the specified context as currently active. // - If some other context was active, the value of currently active context // is replaced, not added. // - Setting of the context does not require confirmation. // // Returns: 0 if the setting of the context was successful, 1 otherwise // // Invoked with: task context <name> // Example: task context home // int CmdContext::setContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; std::string value = words[0]; std::vector <std::string> contexts = getContexts (); // Check that the specified context is defined if (std::find (contexts.begin (), contexts.end (), value) == contexts.end ()) throw format (STRING_CMD_CONTEXT_SET_NFOU, value); // Set the active context. // Should always succeed, as we do not require confirmation. bool success = CmdConfig::setConfigVariable ("context", value, false); if (success) out << format (STRING_CMD_CONTEXT_SET_SUCC, value) << "\n"; else { out << format (STRING_CMD_CONTEXT_SET_FAIL, value) << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Shows the currently active context. // // Returns: Always returns 0. // // Invoked with: task context show // Example: task context show // int CmdContext::showContext (std::vector <std::string>& words, std::stringstream& out) { std::string currentContext = context.config.get ("context"); if (currentContext == "") out << STRING_CMD_CONTEXT_SHOW_EMPT << "\n"; else { std::string currentFilter = context.config.get ("context." + currentContext); out << format (STRING_CMD_CONTEXT_SHOW, currentContext, currentFilter) << "\n"; } return 0; } //////////////////////////////////////////////////////////////////////////////// // Unsets the currently active context. // - Unsetting of the context does not require confirmation. // // Returns: 0 if the unsetting of the context was successful, 1 otherwise (also // returned if no context is currently active) // // Invoked with: task context none // Example: task context none // int CmdContext::unsetContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; int status = CmdConfig::unsetConfigVariable ("context", false); if (status == 0) out << STRING_CMD_CONTEXT_NON_SUCC << "\n"; else { out << STRING_CMD_CONTEXT_NON_FAIL << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// CmdCompletionContext::CmdCompletionContext () { _keyword = "_context"; _usage = "task _context"; _description = STRING_CMD_HCONTEXT_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdCompletionContext::execute (std::string& output) { std::vector <std::string> userContexts = CmdContext::getContexts (); for (auto& userContext : userContexts) output += userContext + "\n"; return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>CmdContext: Converted from CLI to CLI2<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <Context.h> #include <Filter.h> #include <sstream> #include <algorithm> #include <i18n.h> #include <util.h> #include <text.h> #include <CmdContext.h> #include <CmdConfig.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdContext::CmdContext () { _keyword = "context"; _usage = "task context [<name> | subcommand]"; _description = STRING_CMD_CONTEXT_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdContext::execute (std::string& output) { int rc = 0; std::stringstream out; // Get the non-attribute, non-fancy command line arguments. std::vector <std::string> words = context.cli2.getWords (); if (words.size () > 0) { std::string subcommand = words[0]; if (subcommand == "define") rc = defineContext (words, out); else if (subcommand == "delete") rc = deleteContext (words, out); else if (subcommand == "list") rc = listContexts (words, out); else if (subcommand == "none") rc = unsetContext (words, out); else if (subcommand == "show") rc = showContext (words, out); else rc = setContext (words, out); } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// // Joins all the words in the specified interval <from, to) to one string, // which is then returned. // // If to is specified as 0 (default value), all the remaining words will be joined. // std::string CmdContext::joinWords (std::vector <std::string>& words, unsigned int from, unsigned int to /* = 0 */) { std::string value = ""; if (to == 0) to = words.size(); for (unsigned int i = from; i < to; ++i) { if (i > from) value += " "; value += words[i]; } return value; } //////////////////////////////////////////////////////////////////////////////// // Returns all user defined contexts. // std::vector <std::string> CmdContext::getContexts () { std::vector <std::string> contexts; for (auto& name : context.config) if (name.first.substr (0, 8) == "context.") contexts.push_back (name.first.substr (8)); return contexts; } //////////////////////////////////////////////////////////////////////////////// // Defines a new user-provided context. // - The context definition is written into .taskrc as a context.<name> variable. // - Deletion of the context requires confirmation if rc.confirmation=yes. // // Returns: 0 if the addition of the config variable was successful, 1 otherwise // // Invoked with: task context define <name> <filter> // Example: task context define home project:Home // int CmdContext::defineContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; bool confirmation = context.config.getBoolean ("confirmation"); if (words.size () > 2) { std::string name = "context." + words[1]; std::string value = joinWords (words, 2); // Check if the value is a proper filter by filtering current pending.data Filter filter; std::vector <Task> filtered; auto pending = context.tdb2.pending.get_tasks (); try { // This result is not used, and is just to check validity. context.cli.addRawFilter ("( " + value + " )"); filter.subset (pending, filtered); } catch (std::string exception) { throw format (STRING_CMD_CONTEXT_DEF_ABRT2, exception); } // Make user explicitly confirm filters that are matching no pending tasks if (filtered.size () == 0) if (confirmation && ! confirm (format (STRING_CMD_CONTEXT_DEF_CONF, value))) throw std::string (STRING_CMD_CONTEXT_DEF_ABRT); // Set context definition config variable bool success = CmdConfig::setConfigVariable (name, value, confirmation); if (success) out << format (STRING_CMD_CONTEXT_DEF_SUCC, words[1]) << "\n"; else { out << format (STRING_CMD_CONTEXT_DEF_FAIL, words[1]) << "\n"; rc = 1; } } else { out << STRING_CMD_CONTEXT_DEF_USAG << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Deletes the specified context. // - If the deleted context is currently active, unset it. // - Deletion of the context requires confirmation if rc.confirmation=yes. // // Returns: 0 if the removal of the config variable was successful, 1 otherwise // // Invoked with: task context delete <name> // Example: task context delete home // int CmdContext::deleteContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; if (words.size () > 1) { // Delete the specified context std::string name = "context." + words[1]; bool confirmation = context.config.getBoolean ("confirmation"); rc = CmdConfig::unsetConfigVariable(name, confirmation); // If the currently set context was deleted, unset it std::string currentContext = context.config.get ("context"); if (currentContext == words[1]) CmdConfig::unsetConfigVariable("context", false); // Output feedback if (rc == 0) out << format (STRING_CMD_CONTEXT_DEL_SUCC, words[1]) << "\n"; else out << format (STRING_CMD_CONTEXT_DEL_FAIL, words[1]) << "\n"; } else { out << STRING_CMD_CONTEXT_DEL_USAG << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Render a list of context names and their definitions. // // Returns: 0 the resulting list is non-empty, 1 otherwise // // Invoked with: task context list // Example: task context list // int CmdContext::listContexts (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; std::vector <std::string> contexts = getContexts(); if (contexts.size ()) { std::sort (contexts.begin (), contexts.end ()); ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", "Name")); view.add (Column::factory ("string", "Definition")); view.add (Column::factory ("string", "Active")); Color label (context.config.get ("color.label")); view.colorHeader (label); std::string activeContext = context.config.get ("context"); for (auto& userContext : contexts) { std::string definition = context.config.get ("context." + userContext); std::string active = "no"; if (userContext == activeContext) active = "yes"; int row = view.addRow (); view.set (row, 0, userContext); view.set (row, 1, definition); view.set (row, 2, active); } out << optionalBlankLine () << view.render () << optionalBlankLine (); } else { out << STRING_CMD_CONTEXT_LIST_EMPT << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Sets the specified context as currently active. // - If some other context was active, the value of currently active context // is replaced, not added. // - Setting of the context does not require confirmation. // // Returns: 0 if the setting of the context was successful, 1 otherwise // // Invoked with: task context <name> // Example: task context home // int CmdContext::setContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; std::string value = words[0]; std::vector <std::string> contexts = getContexts (); // Check that the specified context is defined if (std::find (contexts.begin (), contexts.end (), value) == contexts.end ()) throw format (STRING_CMD_CONTEXT_SET_NFOU, value); // Set the active context. // Should always succeed, as we do not require confirmation. bool success = CmdConfig::setConfigVariable ("context", value, false); if (success) out << format (STRING_CMD_CONTEXT_SET_SUCC, value) << "\n"; else { out << format (STRING_CMD_CONTEXT_SET_FAIL, value) << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// // Shows the currently active context. // // Returns: Always returns 0. // // Invoked with: task context show // Example: task context show // int CmdContext::showContext (std::vector <std::string>& words, std::stringstream& out) { std::string currentContext = context.config.get ("context"); if (currentContext == "") out << STRING_CMD_CONTEXT_SHOW_EMPT << "\n"; else { std::string currentFilter = context.config.get ("context." + currentContext); out << format (STRING_CMD_CONTEXT_SHOW, currentContext, currentFilter) << "\n"; } return 0; } //////////////////////////////////////////////////////////////////////////////// // Unsets the currently active context. // - Unsetting of the context does not require confirmation. // // Returns: 0 if the unsetting of the context was successful, 1 otherwise (also // returned if no context is currently active) // // Invoked with: task context none // Example: task context none // int CmdContext::unsetContext (std::vector <std::string>& words, std::stringstream& out) { int rc = 0; int status = CmdConfig::unsetConfigVariable ("context", false); if (status == 0) out << STRING_CMD_CONTEXT_NON_SUCC << "\n"; else { out << STRING_CMD_CONTEXT_NON_FAIL << "\n"; rc = 1; } return rc; } //////////////////////////////////////////////////////////////////////////////// CmdCompletionContext::CmdCompletionContext () { _keyword = "_context"; _usage = "task _context"; _description = STRING_CMD_HCONTEXT_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdCompletionContext::execute (std::string& output) { std::vector <std::string> userContexts = CmdContext::getContexts (); for (auto& userContext : userContexts) output += userContext + "\n"; return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include <nan.h> #include "../kv-types.h" #include "env.h" #include "txn.h" #include "db.h" using namespace v8; using namespace kv; using namespace kv::lmdb; template<class T> int mdb_cmp_fn(const MDB_val *a, const MDB_val *b) { T ta((const char*)a->mv_data, a->mv_size), tb((const char*)b->mv_data, b->mv_size); return ta.compare(tb); } template<class T> struct mdb_cmp_setter { static void set_cmp(MDB_txn*, MDB_dbi) { } static void set_dup_cmp(MDB_txn*, MDB_dbi) { } }; template<class N> struct mdb_cmp_setter<number_type<N> > { static void set_cmp(MDB_txn* txn, MDB_dbi dbi) { mdb_set_compare(txn, dbi, mdb_cmp_fn<number_type<N> >); } static void set_dup_cmp(MDB_txn* txn, MDB_dbi dbi) { mdb_set_dupsort(txn, dbi, mdb_cmp_fn<number_type<N> >); } }; #define DB_EXPORT(KT, VT) db<KT, VT>::setup_export(exports); void kv::lmdb::setup_db_export(v8::Handle<v8::Object>& exports) { KV_TYPE_EACH(DB_EXPORT); } template <class K, class V> void db<K, V>::setup_export(Handle<Object>& exports) { char class_name[64]; sprintf(class_name, "DB_%s_%s", K::type_name, V::type_name); // Prepare constructor template Local<FunctionTemplate> dbiTpl = NanNew<FunctionTemplate>(db::ctor); dbiTpl->SetClassName(NanNew(class_name)); dbiTpl->InstanceTemplate()->SetInternalFieldCount(1); // Add functions to the prototype NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "close", db::close); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "get", db::get); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "put", db::put); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "del", db::del); // TODO: wrap mdb_stat too // Set exports exports->Set(NanNew(class_name), dbiTpl->GetFunction()); } #define KVDB db<K, V> #define KVDB_METHOD(fn) template <class K, class V> NAN_METHOD(KVDB::fn) KVDB_METHOD(ctor) { int rc = 0; NanScope(); MDB_txn *txn; MDB_dbi dbi; env *ew = node::ObjectWrap::Unwrap<env>(args[0]->ToObject()); if (args[1]->IsObject()) { Local<Object> options = args[1]->ToObject(); NanUtf8String name(options->Get(NanNew("name"))); bool allowdup = options->Get(NanNew("allowDup"))->BooleanValue(); // Open transaction rc = mdb_txn_begin(ew->_env, NULL, 0, &txn); if (rc != 0) { mdb_txn_abort(txn); NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } // Open database rc = mdb_dbi_open(txn, *name, MDB_CREATE, &dbi); if (rc != 0) { mdb_txn_abort(txn); NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } // Set compare function. mdb_cmp_setter<K>::set_cmp(txn, dbi); if (allowdup) mdb_cmp_setter<V>::set_dup_cmp(txn, dbi); // Commit transaction rc = mdb_txn_commit(txn); if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } } else { NanThrowError("Invalid parameters."); NanReturnUndefined(); } db* ptr = new db(ew->_env, dbi); ptr->Wrap(args.This()); NanReturnValue(args.This()); } KVDB_METHOD(close) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); mdb_dbi_close(dw->_env, dw->_dbi); NanReturnUndefined(); } class kv::lmdb::txn_scope { public: txn_scope(Local<Value> arg, MDB_env *env, bool readonly = false) : _txn(NULL), _created(false), _commit(false) { if (arg->IsObject()) { _txn = node::ObjectWrap::Unwrap<txn>(arg->ToObject())->_txn; } else { _created = true; mdb_txn_begin(env, NULL, readonly ? MDB_RDONLY : 0, &_txn); } } ~txn_scope() { if (_created) { if (!_commit) mdb_txn_abort(_txn); else mdb_txn_commit(_txn); } } MDB_txn *operator*() { return _txn; } void commit() { _commit = true; } private: MDB_txn *_txn; bool _created; bool _commit; }; KVDB_METHOD(get) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); txn_scope tc(args[1], dw->_env, true); MDB_val k, v; k.mv_data = (void*)key.data(); k.mv_size = key.size(); int rc = mdb_get(*tc, dw->_dbi, &k, &v); if (rc == MDB_NOTFOUND) { NanReturnNull(); } if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } V val((const char*)v.mv_data, v.mv_size); NanReturnValue(val.v8value()); } KVDB_METHOD(put) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); V val = V(args[1]); txn_scope tc(args[2], dw->_env); MDB_val k, v; k.mv_data = (void*)key.data(); k.mv_size = key.size(); v.mv_data = (void*)val.data(); v.mv_size = val.size(); int rc = mdb_put(*tc, dw->_dbi, &k, &v, 0); if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } tc.commit(); NanReturnValue(NanNew(true)); } KVDB_METHOD(del) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); txn_scope tc(args[1], dw->_env); MDB_val k; k.mv_data = (void*)key.data(); k.mv_size = key.size(); int rc = mdb_del(*tc, dw->_dbi, &k, NULL); if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } tc.commit(); NanReturnValue(NanNew(true)); } template <class K, class V> db<K, V>::db(MDB_env* env, MDB_dbi dbi) : _dbi(dbi), _env(env) { } <commit_msg>return false when del non-exist key.<commit_after>#include <nan.h> #include "../kv-types.h" #include "env.h" #include "txn.h" #include "db.h" using namespace v8; using namespace kv; using namespace kv::lmdb; template<class T> int mdb_cmp_fn(const MDB_val *a, const MDB_val *b) { T ta((const char*)a->mv_data, a->mv_size), tb((const char*)b->mv_data, b->mv_size); return ta.compare(tb); } template<class T> struct mdb_cmp_setter { static void set_cmp(MDB_txn*, MDB_dbi) { } static void set_dup_cmp(MDB_txn*, MDB_dbi) { } }; template<class N> struct mdb_cmp_setter<number_type<N> > { static void set_cmp(MDB_txn* txn, MDB_dbi dbi) { mdb_set_compare(txn, dbi, mdb_cmp_fn<number_type<N> >); } static void set_dup_cmp(MDB_txn* txn, MDB_dbi dbi) { mdb_set_dupsort(txn, dbi, mdb_cmp_fn<number_type<N> >); } }; #define DB_EXPORT(KT, VT) db<KT, VT>::setup_export(exports); void kv::lmdb::setup_db_export(v8::Handle<v8::Object>& exports) { KV_TYPE_EACH(DB_EXPORT); } template <class K, class V> void db<K, V>::setup_export(Handle<Object>& exports) { char class_name[64]; sprintf(class_name, "DB_%s_%s", K::type_name, V::type_name); // Prepare constructor template Local<FunctionTemplate> dbiTpl = NanNew<FunctionTemplate>(db::ctor); dbiTpl->SetClassName(NanNew(class_name)); dbiTpl->InstanceTemplate()->SetInternalFieldCount(1); // Add functions to the prototype NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "close", db::close); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "get", db::get); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "put", db::put); NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "del", db::del); // TODO: wrap mdb_stat too // Set exports exports->Set(NanNew(class_name), dbiTpl->GetFunction()); } #define KVDB db<K, V> #define KVDB_METHOD(fn) template <class K, class V> NAN_METHOD(KVDB::fn) KVDB_METHOD(ctor) { int rc = 0; NanScope(); MDB_txn *txn; MDB_dbi dbi; env *ew = node::ObjectWrap::Unwrap<env>(args[0]->ToObject()); if (args[1]->IsObject()) { Local<Object> options = args[1]->ToObject(); NanUtf8String name(options->Get(NanNew("name"))); bool allowdup = options->Get(NanNew("allowDup"))->BooleanValue(); // Open transaction rc = mdb_txn_begin(ew->_env, NULL, 0, &txn); if (rc != 0) { mdb_txn_abort(txn); NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } // Open database rc = mdb_dbi_open(txn, *name, MDB_CREATE, &dbi); if (rc != 0) { mdb_txn_abort(txn); NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } // Set compare function. mdb_cmp_setter<K>::set_cmp(txn, dbi); if (allowdup) mdb_cmp_setter<V>::set_dup_cmp(txn, dbi); // Commit transaction rc = mdb_txn_commit(txn); if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } } else { NanThrowError("Invalid parameters."); NanReturnUndefined(); } db* ptr = new db(ew->_env, dbi); ptr->Wrap(args.This()); NanReturnValue(args.This()); } KVDB_METHOD(close) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); mdb_dbi_close(dw->_env, dw->_dbi); NanReturnUndefined(); } class kv::lmdb::txn_scope { public: txn_scope(Local<Value> arg, MDB_env *env, bool readonly = false) : _txn(NULL), _created(false), _commit(false) { if (arg->IsObject()) { _txn = node::ObjectWrap::Unwrap<txn>(arg->ToObject())->_txn; } else { _created = true; mdb_txn_begin(env, NULL, readonly ? MDB_RDONLY : 0, &_txn); } } ~txn_scope() { if (_created) { if (!_commit) mdb_txn_abort(_txn); else mdb_txn_commit(_txn); } } MDB_txn *operator*() { return _txn; } void commit() { _commit = true; } private: MDB_txn *_txn; bool _created; bool _commit; }; KVDB_METHOD(get) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); txn_scope tc(args[1], dw->_env, true); MDB_val k, v; k.mv_data = (void*)key.data(); k.mv_size = key.size(); int rc = mdb_get(*tc, dw->_dbi, &k, &v); if (rc == MDB_NOTFOUND) { NanReturnNull(); } if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } V val((const char*)v.mv_data, v.mv_size); NanReturnValue(val.v8value()); } KVDB_METHOD(put) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); V val = V(args[1]); txn_scope tc(args[2], dw->_env); MDB_val k, v; k.mv_data = (void*)key.data(); k.mv_size = key.size(); v.mv_data = (void*)val.data(); v.mv_size = val.size(); int rc = mdb_put(*tc, dw->_dbi, &k, &v, 0); if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } tc.commit(); NanReturnValue(NanNew(true)); } KVDB_METHOD(del) { NanScope(); db *dw = ObjectWrap::Unwrap<db>(args.This()); K key = K(args[0]); txn_scope tc(args[1], dw->_env); MDB_val k; k.mv_data = (void*)key.data(); k.mv_size = key.size(); int rc = mdb_del(*tc, dw->_dbi, &k, NULL); if (rc == MDB_NOTFOUND) { NanReturnValue(NanNew(false)); } if (rc != 0) { NanThrowError(mdb_strerror(rc)); NanReturnUndefined(); } tc.commit(); NanReturnValue(NanNew(true)); } template <class K, class V> db<K, V>::db(MDB_env* env, MDB_dbi dbi) : _dbi(dbi), _env(env) { } <|endoftext|>
<commit_before>// ============================================================================= // Event Class for .NET Style Events // by Clint Caywood // February 18, 2010 // ============================================================================= #ifndef EVENT_HPP #define EVENT_HPP #include <vector> #include <algorithm> #include <iostream> #include <stdio.h> #include "Delegate.hpp" template <typename T> class Event { typedef typename std::vector< Delegate<T>* >::iterator iter; public: void operator+=(Delegate<T>* delegate) { // An object can only subscribe once if (find(_delegates.begin(), _delegates.end(), delegate) == _delegates.end()) { _delegates.push_back(delegate); } } void operator-=(Delegate<T>* delegate) { iter i = _delegates.begin(); while (i != _delegates.end()) { if (*i == delegate) { i = _delegates.erase(i); } else { ++i; } } } void operator()(T param) { for (iter i = _delegates.begin(); i != _delegates.end(); ++i) { if((*i) != NULL) (*i)->operator()(param); } } typename std::vector<Delegate<T>* >::size_type numDelegates() { return _delegates.size(); } private: std::vector< Delegate<T>* > _delegates; }; #endif <commit_msg>Adds Clear() to Event.<commit_after>// ============================================================================= // Event Class for .NET Style Events // by Clint Caywood // February 18, 2010 // ============================================================================= #ifndef EVENT_HPP #define EVENT_HPP #include <vector> #include <algorithm> #include <iostream> #include <stdio.h> #include "Delegate.hpp" template <typename T> class Event { typedef typename std::vector< Delegate<T>* >::iterator iter; public: void operator+=(Delegate<T>* delegate) { // An object can only subscribe once if (find(_delegates.begin(), _delegates.end(), delegate) == _delegates.end()) { _delegates.push_back(delegate); } } void operator-=(Delegate<T>* delegate) { iter i = _delegates.begin(); while (i != _delegates.end()) { if (*i == delegate) { i = _delegates.erase(i); } else { ++i; } } } void operator()(T param) { for (iter i = _delegates.begin(); i != _delegates.end(); ++i) { if((*i) != NULL) (*i)->operator()(param); } } typename std::vector<Delegate<T>* >::size_type numDelegates() { return _delegates.size(); } void Clear() { _delegates.clear(); } private: std::vector< Delegate<T>* > _delegates; }; #endif <|endoftext|>
<commit_before> #include "logging.h" #include <stdio.h> /* printf, fopen */ #include <stdarg.h> /* va_args */ #include <string.h> /* memcpy */ #include <time.h> /* time_t */ static const char* loglevel2string (const enum TCAM_LOG_LEVEL level) { switch (level) { case TCAM_LOG_OFF: return "OFF"; case TCAM_LOG_DEBUG: return "DEBUG"; case TCAM_LOG_INFO: return "INFO"; case TCAM_LOG_WARNING: return "WARNING"; case TCAM_LOG_ERROR: return "ERROR"; default: return NULL; } } static enum TCAM_LOG_LEVEL string2loglevel (const char* level) { if (strcmp("OFF", level) == 0) { return TCAM_LOG_OFF; } else if (strcmp("DEBUG", level) == 0) { return TCAM_LOG_DEBUG; } else if (strcmp("INFO", level) == 0) { return TCAM_LOG_INFO; } else if (strcmp("WARNING", level) == 0) { return TCAM_LOG_WARNING; } else if (strcmp("ERROR", level) == 0) { return TCAM_LOG_ERROR; } else return TCAM_LOG_ERROR; } Logger::Logger (): callback(nullptr), logfile(nullptr) { load_default_settings(); // TODO: make environment variable name configurable char* log_def = getenv("TCAM_LOG"); if (log_def != nullptr) { printf("ENV: %s\n", log_def); level = string2loglevel(log_def); } } void Logger::load_default_settings () { level = TCAM_LOG_ERROR; target = STDIO; log_file = "tmp/tis.log"; } void Logger::log (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, va_list args) { if (level < this->level) { return; } char msg[1024]; char buffer [2056]; /* fill user defined message */ vsprintf(msg, message, args); clock_t t; t = clock(); /* write complete message */ sprintf(buffer, "%-10ld <%s> %s:%d: %s\n", /* ctime(&timer), */ t, loglevel2string(level), function, line, msg); switch (target) { case STDIO: log_to_stdout(buffer); break; case LOGFILE: log_to_file(buffer); break; case USER_DEFINED: //logger.callback(level, file, line, message, args); break; default: break; } } void Logger::log_to_stdout (const char* message) { fprintf(stdout, "%s", message); fflush(stdout); } void Logger::log_to_file (const char* message) {} void Logger::set_log_level (enum TCAM_LOG_LEVEL l) { level = l; } enum TCAM_LOG_LEVEL Logger::get_log_level () const { return level; } void Logger::set_target (enum TCAM_LOG_TARGET t) { target = t; } enum TCAM_LOG_TARGET Logger::get_target () const { return target; } void Logger::set_log_file (const std::string& filename) { log_file = filename; } std::string Logger::get_log_file () const { return log_file; } void Logger::set_external_callback (logging_callback c) { callback = c; } void Logger::delete_external_callback () { callback = nullptr; } void Logger::open_logfile () { if (!log_file.empty()) logfile = fopen(log_file.c_str(), "a+"); } void Logger::close_logfile () { if (logfile != NULL) { fclose(logfile); logfile = NULL; } } Logger& Logger::getInstance () { static Logger instance; return instance; } void tcam_set_logging_level (enum TCAM_LOG_LEVEL level) { Logger::getInstance().set_log_level(level); } enum TCAM_LOG_LEVEL tcam_get_logging_level () { return Logger::getInstance().get_log_level(); } void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level) { tcam_set_logging_target(target); tcam_set_logging_level(level); } void tcam_set_logging_target (enum TCAM_LOG_TARGET target) { Logger::getInstance().set_target(target); } void tcam_set_logging_file (const char* logfile_name) { Logger::getInstance().set_log_file(logfile_name); } const char* tcam_get_logging_file () { return Logger::getInstance().get_log_file().c_str(); } void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log("", level, file, line, message, args); va_end(args); } void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log(module, level, function, line, message, args); va_end(args); } <commit_msg>Correct defualt file path of tcam log file<commit_after> #include "logging.h" #include <stdio.h> /* printf, fopen */ #include <stdarg.h> /* va_args */ #include <string.h> /* memcpy */ #include <time.h> /* time_t */ static const char* loglevel2string (const enum TCAM_LOG_LEVEL level) { switch (level) { case TCAM_LOG_OFF: return "OFF"; case TCAM_LOG_DEBUG: return "DEBUG"; case TCAM_LOG_INFO: return "INFO"; case TCAM_LOG_WARNING: return "WARNING"; case TCAM_LOG_ERROR: return "ERROR"; default: return NULL; } } static enum TCAM_LOG_LEVEL string2loglevel (const char* level) { if (strcmp("OFF", level) == 0) { return TCAM_LOG_OFF; } else if (strcmp("DEBUG", level) == 0) { return TCAM_LOG_DEBUG; } else if (strcmp("INFO", level) == 0) { return TCAM_LOG_INFO; } else if (strcmp("WARNING", level) == 0) { return TCAM_LOG_WARNING; } else if (strcmp("ERROR", level) == 0) { return TCAM_LOG_ERROR; } else return TCAM_LOG_ERROR; } Logger::Logger (): callback(nullptr), logfile(nullptr) { load_default_settings(); // TODO: make environment variable name configurable char* log_def = getenv("TCAM_LOG"); if (log_def != nullptr) { printf("ENV: %s\n", log_def); level = string2loglevel(log_def); } } void Logger::load_default_settings () { level = TCAM_LOG_ERROR; target = STDIO; log_file = "/tmp/tis.log"; } void Logger::log (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, va_list args) { if (level < this->level) { return; } char msg[1024]; char buffer [2056]; /* fill user defined message */ vsprintf(msg, message, args); clock_t t; t = clock(); /* write complete message */ sprintf(buffer, "%-10ld <%s> %s:%d: %s\n", /* ctime(&timer), */ t, loglevel2string(level), function, line, msg); switch (target) { case STDIO: log_to_stdout(buffer); break; case LOGFILE: log_to_file(buffer); break; case USER_DEFINED: //logger.callback(level, file, line, message, args); break; default: break; } } void Logger::log_to_stdout (const char* message) { fprintf(stdout, "%s", message); fflush(stdout); } void Logger::log_to_file (const char* message) {} void Logger::set_log_level (enum TCAM_LOG_LEVEL l) { level = l; } enum TCAM_LOG_LEVEL Logger::get_log_level () const { return level; } void Logger::set_target (enum TCAM_LOG_TARGET t) { target = t; } enum TCAM_LOG_TARGET Logger::get_target () const { return target; } void Logger::set_log_file (const std::string& filename) { log_file = filename; } std::string Logger::get_log_file () const { return log_file; } void Logger::set_external_callback (logging_callback c) { callback = c; } void Logger::delete_external_callback () { callback = nullptr; } void Logger::open_logfile () { if (!log_file.empty()) logfile = fopen(log_file.c_str(), "a+"); } void Logger::close_logfile () { if (logfile != NULL) { fclose(logfile); logfile = NULL; } } Logger& Logger::getInstance () { static Logger instance; return instance; } void tcam_set_logging_level (enum TCAM_LOG_LEVEL level) { Logger::getInstance().set_log_level(level); } enum TCAM_LOG_LEVEL tcam_get_logging_level () { return Logger::getInstance().get_log_level(); } void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level) { tcam_set_logging_target(target); tcam_set_logging_level(level); } void tcam_set_logging_target (enum TCAM_LOG_TARGET target) { Logger::getInstance().set_target(target); } void tcam_set_logging_file (const char* logfile_name) { Logger::getInstance().set_log_file(logfile_name); } const char* tcam_get_logging_file () { return Logger::getInstance().get_log_file().c_str(); } void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log("", level, file, line, message, args); va_end(args); } void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log(module, level, function, line, message, args); va_end(args); } <|endoftext|>
<commit_before> #include "idTable.h" // @Author: Vik Singh // @Date: 12/30/2004 // CLASS Id Id::Id (IdTable * table) { this->table = table; } Id::Id (const u_int32_t * num, IdTable * table) { for (int i = 0; i < 5; i += 1) key[i] = *(num + i); this->table = table; } Id::Id (const std::string& idString, IdTable * table) { this->table = table; } std::bitset<160> Id::toBitWord (u_int32_t num) { return std::bitset<160> (num); /* std::bitset<160> result; for (int i = 0; i < 32 && num >= 1; i += 1) { if (num % 2) result.set (i); num /= 2; } return result; */ } std::string Id::toHexWord (u_int32_t num) { const std::string HEX_DIGITS = "0123456789ABCDEF"; char result[] = {'0','0','0','0','0','0','0','0','\0'}; int remainder; for (int i = 0; i < 8 && num >= 1; i += 1) { if (remainder = num % 16) result[7 - i] = HEX_DIGITS.at (remainder); num /= 16; } return std::string (result); } std::bitset<160> Id::toBitSet () const { std::bitset<160> result; for (int i = 0; i < 5; i += 1) result ^= toBitWord (key[i]) << ((4 - i) * 32); return result; } std::string Id::toHexString () const { std::string currentWord; char result[] = {'0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '\0'}; for (int i = 0; i < 5; i += 1) { currentWord = toHexWord (key[i]); for (int j = i * 8; j < (i * 8) + 8; j += 1) result[j] = currentWord.at (j % 8); } return std::string (result); } size_t Id::hashCode () const { size_t result = 0; for (int i = 0; i < 5; i += 1) result ^= key[i]; return result; } u_int32_t Id::getWord (const int index) const { assert (index >= 0 && index < 5); return key[index]; } // CLASS IdTable IdTable::IdTable () { maxSize = 0; } void IdTable::initialize_gc (const size_t num) { maxSize = num; } bool IdTable::equalByVal (const Id * x, const Id * y) { for (int i = 0; i < 5; i += 1) { if (x->key[i] == y->key[i]) continue; else return false; } return true; } // const Id * create (const XDR * xdr); const Id * IdTable::create (const std::string& idString) { Id * result = new Id (this); // use New ref<Id> (idString); return storeId (result); } const Id * IdTable::create (const u_int32_t * random) { Id * result = new Id (random, this); // use New ref<Id> (random); return storeId (result); } const Id * IdTable::create () { Id * result = new Id (this); // auto gen with dev/urandom return storeId (result); } size_t IdTable::size () const { return idSet.size (); } void IdTable::remove (const Id * idPtr) { idSet.erase (idPtr); } void IdTable::clear () { idSet.clear (); } const Id * IdTable::storeId (const Id * idKey) { std::map<const Id *, int, IdComparator>::iterator idFound = idSet.find (idKey); if (idFound != idSet.end ()) { delete idKey; return idFound->first; } else { add (idKey); return idKey; } } void IdTable::add (const Id * idKey) { idSet.insert (std::pair<const Id *, int> (idKey, 0)); if (maxSize == 0) return; else if (idSet.size () > maxSize) gc (); } // ref<Id> 's are deleted automatically from the set when // refcount goes to zero - look at Id::finalize () void IdTable::gc () { /** * Get the size of @idSet * divide size by 2 * first half = old * second half = recent * fudge factor = desired size, keep collecting until ff * reached * within this set order @Id's by # of references * within this set order @Id's by time of last use * */ std::map<const Id *, int, IdComparator>::iterator items = idSet.begin (); while (items != idSet.end ()) { } } <commit_msg>Added parentheses around assignment/boolean expression within an if.<commit_after> #include "idTable.h" // @Author: Vik Singh // @Date: 12/30/2004 // CLASS Id Id::Id (IdTable * table) { this->table = table; } Id::Id (const u_int32_t * num, IdTable * table) { for (int i = 0; i < 5; i += 1) key[i] = *(num + i); this->table = table; } Id::Id (const std::string& idString, IdTable * table) { this->table = table; } std::bitset<160> Id::toBitWord (u_int32_t num) { return std::bitset<160> (num); /* std::bitset<160> result; for (int i = 0; i < 32 && num >= 1; i += 1) { if (num % 2) result.set (i); num /= 2; } return result; */ } std::string Id::toHexWord (u_int32_t num) { const std::string HEX_DIGITS = "0123456789ABCDEF"; char result[] = {'0','0','0','0','0','0','0','0','\0'}; int remainder; for (int i = 0; i < 8 && num >= 1; i += 1) { if ((remainder = num % 16)) result[7 - i] = HEX_DIGITS.at (remainder); num /= 16; } return std::string (result); } std::bitset<160> Id::toBitSet () const { std::bitset<160> result; for (int i = 0; i < 5; i += 1) result ^= toBitWord (key[i]) << ((4 - i) * 32); return result; } std::string Id::toHexString () const { std::string currentWord; char result[] = {'0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0','0','0', '\0'}; for (int i = 0; i < 5; i += 1) { currentWord = toHexWord (key[i]); for (int j = i * 8; j < (i * 8) + 8; j += 1) result[j] = currentWord.at (j % 8); } return std::string (result); } size_t Id::hashCode () const { size_t result = 0; for (int i = 0; i < 5; i += 1) result ^= key[i]; return result; } u_int32_t Id::getWord (const int index) const { assert (index >= 0 && index < 5); return key[index]; } // CLASS IdTable IdTable::IdTable () { maxSize = 0; } void IdTable::initialize_gc (const size_t num) { maxSize = num; } bool IdTable::equalByVal (const Id * x, const Id * y) { for (int i = 0; i < 5; i += 1) { if (x->key[i] == y->key[i]) continue; else return false; } return true; } // const Id * create (const XDR * xdr); const Id * IdTable::create (const std::string& idString) { Id * result = new Id (this); // use New ref<Id> (idString); return storeId (result); } const Id * IdTable::create (const u_int32_t * random) { Id * result = new Id (random, this); // use New ref<Id> (random); return storeId (result); } const Id * IdTable::create () { Id * result = new Id (this); // auto gen with dev/urandom return storeId (result); } size_t IdTable::size () const { return idSet.size (); } void IdTable::remove (const Id * idPtr) { idSet.erase (idPtr); } void IdTable::clear () { idSet.clear (); } const Id * IdTable::storeId (const Id * idKey) { std::map<const Id *, int, IdComparator>::iterator idFound = idSet.find (idKey); if (idFound != idSet.end ()) { delete idKey; return idFound->first; } else { add (idKey); return idKey; } } void IdTable::add (const Id * idKey) { idSet.insert (std::pair<const Id *, int> (idKey, 0)); if (maxSize == 0) return; else if (idSet.size () > maxSize) gc (); } // ref<Id> 's are deleted automatically from the set when // refcount goes to zero - look at Id::finalize () void IdTable::gc () { /** * Get the size of @idSet * divide size by 2 * first half = old * second half = recent * fudge factor = desired size, keep collecting until ff * reached * within this set order @Id's by # of references * within this set order @Id's by time of last use * */ std::map<const Id *, int, IdComparator>::iterator items = idSet.begin (); while (items != idSet.end ()) { } } <|endoftext|>
<commit_before>/* Calf DSP Library * RDF file generator for LADSPA plugins. * Copyright (C) 2007 Krzysztof Foltman * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ #include <getopt.h> #include <stdint.h> #include <stdlib.h> #include <config.h> #include <calf/giface.h> #include <calf/modules.h> using namespace std; using namespace synth; static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"mode", 0, 0, 'm'}, {0,0,0,0}, }; void make_rdf() { string rdf; rdf = "<?xml version='1.0' encoding='ISO-8859-1'?>\n" "<!DOCTYPE rdf:RDF [\n" " <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" " <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n" " <!ENTITY dc 'http://purl.org/dc/elements/1.1/'>\n" " <!ENTITY ladspa 'http://ladspa.org/ontology#'>\n" "]>\n"; rdf += "<rdf:RDF xmlns:rdf=\"&rdf;\" xmlns:rdfs=\"&rdfs;\" xmlns:dc=\"&dc;\" xmlns:ladspa=\"&ladspa;\">\n"; rdf += synth::get_builtin_modules_rdf(); rdf += "</rdf:RDF>\n"; printf("%s\n", rdf.c_str()); } static void add_port(string &ports, const char *symbol, const char *name, const char *direction, int pidx) { stringstream ss; const char *ind = " "; if (ports != "") ports += " , "; ss << "[\n"; if (direction) ss << ind << "a lv2:" << direction << "Port ;\n"; ss << ind << "a lv2:AudioPort ;\n"; ss << ind << "lv2:index " << pidx << " ;\n"; ss << ind << "lv2:symbol \"" << symbol << "\" ;\n"; ss << ind << "lv2:name \"" << name << "\" ;\n"; ss << " ]"; ports += ss.str(); } static void add_ctl_port(string &ports, parameter_properties &pp, int pidx) { stringstream ss; const char *ind = " "; if (ports != "") ports += " , "; ss << "[\n"; ss << ind << "a lv2:InputPort ;\n"; ss << ind << "a lv2:ControlPort ;\n"; ss << ind << "lv2:index " << pidx << " ;\n"; ss << ind << "lv2:symbol \"" << pp.short_name << "\" ;\n"; ss << ind << "lv2:name \"" << pp.name << "\" ;\n"; if ((pp.flags & PF_TYPEMASK) == PF_BOOL) ss << ind << "lv2:portProperty lv2:toggled ;\n"; else if ((pp.flags & PF_TYPEMASK) == PF_ENUM) { ss << ind << "lv2:portProperty lv2:integer ;\n"; for (int i = (int)pp.min; i <= (int)pp.max; i++) ss << ind << "lv2:scalePoint [ rdfs:label \"" << pp.choices[i - (int)pp.min] << "\"; rdf:value " << i <<" ] ;\n"; } else if ((pp.flags & PF_TYPEMASK) > 0) ss << ind << "lv2:portProperty lv2:integer ;\n"; ss << showpoint; ss << ind << "lv2:default " << pp.def_value << " ;\n"; ss << ind << "lv2:minimum " << pp.min << " ;\n"; ss << ind << "lv2:maximum " << pp.max << " ;\n"; ss << " ]"; ports += ss.str(); } void make_ttl() { string ttl; ttl = "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n" "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" "@prefix doap: <http://usefulinc.com/ns/doap#> .\n" "@prefix guiext: <http://ll-plugins.nongnu.org/lv2/ext/gui#> .\n" "\n" ; vector<synth::giface_plugin_info> plugins; synth::get_all_plugins(plugins); map<string, string> classes; const char *ptypes[] = { "Flanger", "Reverb", "Generator", "Instrument", "Oscillator", "Utility", "Converter", "Analyser", "Mixer", "Simulator", "Delay", "Modulator", "Phaser", "Chorus", "Filter", "Lowpass", "Highpass", "Bandpass", "Comb", "Allpass", "Amplifier", "Distortion", "Waveshaper", "Dynamics", "Compressor", "Expander", "Limiter", "Gate", NULL }; for(const char **p = ptypes; *p; p++) { string name = string(*p) + "Plugin"; classes[name] = "lv2:" + name; } #if USE_LV2_GUI ttl += "<http://calf.sourceforge.net/plugins/gui/gtk2-gui>\n a guiext:GtkGUI ;\n guiext:binary <calflv2gui.so> .\n\n"; #endif for (unsigned int i = 0; i < plugins.size(); i++) { synth::giface_plugin_info &pi = plugins[i]; ttl += string("<http://calf.sourceforge.net/plugins/") + string(pi.info->label) + "> a lv2:Plugin ;\n"; if (classes.count(pi.info->plugin_type)) ttl += " a " + classes[pi.info->plugin_type]+" ;\n"; ttl += " doap:name \""+string(pi.info->name)+"\" ;\n"; #if USE_LV2_GUI ttl += " guiext:gui <http://calf.sourceforge.net/plugins/gui/gtk2-gui> ;\n"; #endif #if USE_PHAT ttl += " doap:license <http://usefulinc.com/doap/licenses/gpl> ;\n"; #else ttl += " doap:license <http://usefulinc.com/doap/licenses/lgpl> ;\n"; #endif if (pi.rt_capable) ttl += " lv2:optionalFeature lv2:hardRtCapable ;\n"; string ports = ""; int pn = 0; const char *in_names[] = { "in_l", "in_r" }; const char *out_names[] = { "out_l", "out_r" }; for (int i = 0; i < pi.inputs; i++) add_port(ports, in_names[i], in_names[i], "Input", pn++); for (int i = 0; i < pi.outputs; i++) add_port(ports, out_names[i], out_names[i], "Output", pn++); for (int i = 0; i < pi.params; i++) add_ctl_port(ports, pi.param_props[i], pn++); if (!ports.empty()) ttl += " lv2:port " + ports + "\n"; ttl += ".\n\n"; } printf("%s\n", ttl.c_str()); } void make_manifest() { string ttl; ttl = "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n" "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"; vector<synth::giface_plugin_info> plugins; synth::get_all_plugins(plugins); for (unsigned int i = 0; i < plugins.size(); i++) ttl += string("<http://calf.sourceforge.net/plugins/") + string(plugins[i].info->label) + "> a lv2:Plugin ; lv2:binary <calf.so> ; rdfs:seeAlso <calf.ttl> .\n"; printf("%s\n", ttl.c_str()); } int main(int argc, char *argv[]) { string mode = "rdf"; while(1) { int option_index; int c = getopt_long(argc, argv, "hvm:", long_options, &option_index); if (c == -1) break; switch(c) { case 'h': case '?': printf("LADSPA RDF / LV2 TTL generator for Calf plugin pack\nSyntax: %s [--help] [--version] [--mode rdf|ttl|manifest]\n", argv[0]); return 0; case 'v': printf("%s\n", PACKAGE_STRING); return 0; case 'm': mode = optarg; if (mode != "rdf" && mode != "ttl" && mode != "manifest") { fprintf(stderr, "calfmakerdf: Invalid mode %s\n", optarg); return 1; } break; } } if (mode == "rdf") make_rdf(); if (mode == "ttl") make_ttl(); if (mode == "manifest") make_manifest(); return 0; } <commit_msg>+ LV2: Fixed classification for instrument plugins (they're still useless because of lack of MIDI port)<commit_after>/* Calf DSP Library * RDF file generator for LADSPA plugins. * Copyright (C) 2007 Krzysztof Foltman * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ #include <getopt.h> #include <stdint.h> #include <stdlib.h> #include <config.h> #include <calf/giface.h> #include <calf/modules.h> using namespace std; using namespace synth; static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"mode", 0, 0, 'm'}, {0,0,0,0}, }; void make_rdf() { string rdf; rdf = "<?xml version='1.0' encoding='ISO-8859-1'?>\n" "<!DOCTYPE rdf:RDF [\n" " <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" " <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n" " <!ENTITY dc 'http://purl.org/dc/elements/1.1/'>\n" " <!ENTITY ladspa 'http://ladspa.org/ontology#'>\n" "]>\n"; rdf += "<rdf:RDF xmlns:rdf=\"&rdf;\" xmlns:rdfs=\"&rdfs;\" xmlns:dc=\"&dc;\" xmlns:ladspa=\"&ladspa;\">\n"; rdf += synth::get_builtin_modules_rdf(); rdf += "</rdf:RDF>\n"; printf("%s\n", rdf.c_str()); } static void add_port(string &ports, const char *symbol, const char *name, const char *direction, int pidx) { stringstream ss; const char *ind = " "; if (ports != "") ports += " , "; ss << "[\n"; if (direction) ss << ind << "a lv2:" << direction << "Port ;\n"; ss << ind << "a lv2:AudioPort ;\n"; ss << ind << "lv2:index " << pidx << " ;\n"; ss << ind << "lv2:symbol \"" << symbol << "\" ;\n"; ss << ind << "lv2:name \"" << name << "\" ;\n"; ss << " ]"; ports += ss.str(); } static void add_ctl_port(string &ports, parameter_properties &pp, int pidx) { stringstream ss; const char *ind = " "; if (ports != "") ports += " , "; ss << "[\n"; ss << ind << "a lv2:InputPort ;\n"; ss << ind << "a lv2:ControlPort ;\n"; ss << ind << "lv2:index " << pidx << " ;\n"; ss << ind << "lv2:symbol \"" << pp.short_name << "\" ;\n"; ss << ind << "lv2:name \"" << pp.name << "\" ;\n"; if ((pp.flags & PF_TYPEMASK) == PF_BOOL) ss << ind << "lv2:portProperty lv2:toggled ;\n"; else if ((pp.flags & PF_TYPEMASK) == PF_ENUM) { ss << ind << "lv2:portProperty lv2:integer ;\n"; for (int i = (int)pp.min; i <= (int)pp.max; i++) ss << ind << "lv2:scalePoint [ rdfs:label \"" << pp.choices[i - (int)pp.min] << "\"; rdf:value " << i <<" ] ;\n"; } else if ((pp.flags & PF_TYPEMASK) > 0) ss << ind << "lv2:portProperty lv2:integer ;\n"; ss << showpoint; ss << ind << "lv2:default " << pp.def_value << " ;\n"; ss << ind << "lv2:minimum " << pp.min << " ;\n"; ss << ind << "lv2:maximum " << pp.max << " ;\n"; ss << " ]"; ports += ss.str(); } void make_ttl() { string ttl; ttl = "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n" "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" "@prefix doap: <http://usefulinc.com/ns/doap#> .\n" "@prefix guiext: <http://ll-plugins.nongnu.org/lv2/ext/gui#> .\n" "\n" ; vector<synth::giface_plugin_info> plugins; synth::get_all_plugins(plugins); map<string, string> classes; const char *ptypes[] = { "Flanger", "Reverb", "Generator", "Instrument", "Oscillator", "Utility", "Converter", "Analyser", "Mixer", "Simulator", "Delay", "Modulator", "Phaser", "Chorus", "Filter", "Lowpass", "Highpass", "Bandpass", "Comb", "Allpass", "Amplifier", "Distortion", "Waveshaper", "Dynamics", "Compressor", "Expander", "Limiter", "Gate", NULL }; for(const char **p = ptypes; *p; p++) { string name = string(*p) + "Plugin"; classes[name] = "lv2:" + name; } classes["SynthesizerPlugin"] = "lv2:InstrumentPlugin"; #if USE_LV2_GUI ttl += "<http://calf.sourceforge.net/plugins/gui/gtk2-gui>\n a guiext:GtkGUI ;\n guiext:binary <calflv2gui.so> .\n\n"; #endif for (unsigned int i = 0; i < plugins.size(); i++) { synth::giface_plugin_info &pi = plugins[i]; ttl += string("<http://calf.sourceforge.net/plugins/") + string(pi.info->label) + "> a lv2:Plugin ;\n"; if (classes.count(pi.info->plugin_type)) ttl += " a " + classes[pi.info->plugin_type]+" ;\n"; ttl += " doap:name \""+string(pi.info->name)+"\" ;\n"; #if USE_LV2_GUI ttl += " guiext:gui <http://calf.sourceforge.net/plugins/gui/gtk2-gui> ;\n"; #endif #if USE_PHAT ttl += " doap:license <http://usefulinc.com/doap/licenses/gpl> ;\n"; #else ttl += " doap:license <http://usefulinc.com/doap/licenses/lgpl> ;\n"; #endif if (pi.rt_capable) ttl += " lv2:optionalFeature lv2:hardRtCapable ;\n"; string ports = ""; int pn = 0; const char *in_names[] = { "in_l", "in_r" }; const char *out_names[] = { "out_l", "out_r" }; for (int i = 0; i < pi.inputs; i++) add_port(ports, in_names[i], in_names[i], "Input", pn++); for (int i = 0; i < pi.outputs; i++) add_port(ports, out_names[i], out_names[i], "Output", pn++); for (int i = 0; i < pi.params; i++) add_ctl_port(ports, pi.param_props[i], pn++); if (!ports.empty()) ttl += " lv2:port " + ports + "\n"; ttl += ".\n\n"; } printf("%s\n", ttl.c_str()); } void make_manifest() { string ttl; ttl = "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n" "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"; vector<synth::giface_plugin_info> plugins; synth::get_all_plugins(plugins); for (unsigned int i = 0; i < plugins.size(); i++) ttl += string("<http://calf.sourceforge.net/plugins/") + string(plugins[i].info->label) + "> a lv2:Plugin ; lv2:binary <calf.so> ; rdfs:seeAlso <calf.ttl> .\n"; printf("%s\n", ttl.c_str()); } int main(int argc, char *argv[]) { string mode = "rdf"; while(1) { int option_index; int c = getopt_long(argc, argv, "hvm:", long_options, &option_index); if (c == -1) break; switch(c) { case 'h': case '?': printf("LADSPA RDF / LV2 TTL generator for Calf plugin pack\nSyntax: %s [--help] [--version] [--mode rdf|ttl|manifest]\n", argv[0]); return 0; case 'v': printf("%s\n", PACKAGE_STRING); return 0; case 'm': mode = optarg; if (mode != "rdf" && mode != "ttl" && mode != "manifest") { fprintf(stderr, "calfmakerdf: Invalid mode %s\n", optarg); return 1; } break; } } if (mode == "rdf") make_rdf(); if (mode == "ttl") make_ttl(); if (mode == "manifest") make_manifest(); return 0; } <|endoftext|>
<commit_before><commit_msg>am c2bb5391: Merge "Use GetEntryPointFromQuickCompiledCode instead of GetQuickOatCodeOffset"<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2011, Jon Maken * License: 3-clause BSD * Revision: 12/09/2011 2:36:08 PM * * Example: * * HiRes::Statistics<double> stats = * for_each(istream_iterator<double>(cin), * istream_iterator<double><(), * HiRes::Statistics<double>()); */ #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <vector> #if defined(_WIN32) # include <io.h> # define executable "basic_stats.exe" #else # include <unistd.h> # define executable "basic_stats" #endif #include "hrtimer.h" #include "statistics.h" const int TEST_COUNT = 20; int main(int argc, char* argv[]) { using namespace std; double rv = 0.0; vector<double> data; HiRes::Timer<HiRes::us> tmr_us; for (int i = 0; i < TEST_COUNT; i++) { tmr_us.start(); _access(executable, 4); rv = tmr_us.stop(); data.push_back(rv); } HiRes::Statistics<double> stats = for_each(data.begin(), data.end(), HiRes::Statistics<double>()); cout << "Count = " << stats.count() << '\n' << "Min = " << stats.min() << '\n' << "Max = " << stats.max() << '\n' << "Sum = " << stats.sum() << '\n' << "Sum of Squares = " << stats.sum_of_squares() << '\n' << "Mean = " << stats.mean() << '\n' << "Variance = " << stats.variance() << '\n' << "Stdev = " << stats.stdev() << '\n' << "Coefficient of Variation = " << stats.cv() << endl; return 0; } <commit_msg>Fix _access symbol naming<commit_after>/* Copyright (c) 2011, Jon Maken * License: 3-clause BSD * Revision: 12/09/2011 2:36:08 PM * * Example: * * HiRes::Statistics<double> stats = * for_each(istream_iterator<double>(cin), * istream_iterator<double><(), * HiRes::Statistics<double>()); */ #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <vector> #if defined(_WIN32) # include <io.h> # define executable "basic_stats.exe" # define access _access #else # include <unistd.h> # define executable "basic_stats" #endif #include "hrtimer.h" #include "statistics.h" const int TEST_COUNT = 20; int main(int argc, char* argv[]) { using namespace std; double rv = 0.0; vector<double> data; HiRes::Timer<HiRes::us> tmr_us; for (int i = 0; i < TEST_COUNT; i++) { tmr_us.start(); access(executable, 4); rv = tmr_us.stop(); data.push_back(rv); } HiRes::Statistics<double> stats = for_each(data.begin(), data.end(), HiRes::Statistics<double>()); cout << "Count = " << stats.count() << '\n' << "Min = " << stats.min() << '\n' << "Max = " << stats.max() << '\n' << "Sum = " << stats.sum() << '\n' << "Sum of Squares = " << stats.sum_of_squares() << '\n' << "Mean = " << stats.mean() << '\n' << "Variance = " << stats.variance() << '\n' << "Stdev = " << stats.stdev() << '\n' << "Coefficient of Variation = " << stats.cv() << endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013, David C Horton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace drachtio { class SipDialogController ; } #include <boost/bind.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> #include "pending-request-controller.hpp" #include "controller.hpp" #include "cdr.hpp" #include "request-router.hpp" #include "request-handler.hpp" #define CLIENT_TIMEOUT (64000) namespace drachtio { PendingRequest_t::PendingRequest_t(msg_t* msg, sip_t* sip, tport_t* tp ) : m_msg( msg ), m_tp(tp), m_canceled(false), m_callId(sip->sip_call_id->i_id), m_seq(sip->sip_cseq->cs_seq), m_methodName(sip->sip_cseq->cs_method_name) { //DR_LOG(log_debug) << "PendingRequest_t::PendingRequest_t" ; generateUuid( m_transactionId ) ; msg_ref_create( m_msg ) ; } PendingRequest_t::~PendingRequest_t() { msg_destroy( m_msg ) ; } msg_t* PendingRequest_t::getMsg() { return m_msg ; } sip_t* PendingRequest_t::getSipObject() { return sip_object(m_msg); } const string& PendingRequest_t::getCallId() { return m_callId; } const string& PendingRequest_t::getTransactionId() { return m_transactionId; } const string& PendingRequest_t::getMethodName() { return m_methodName; } tport_t* PendingRequest_t::getTport() { return m_tp; } uint32_t PendingRequest_t::getCSeq() { return m_seq; } PendingRequestController::PendingRequestController( DrachtioController* pController) : m_pController(pController), m_agent(pController->getAgent()), m_pClientController(pController->getClientController()), m_timerQueue(pController->getRoot(), "pending-request" ) { assert(m_agent) ; } PendingRequestController::~PendingRequestController() { } int PendingRequestController::processNewRequest( msg_t* msg, sip_t* sip, tport_t* tp_incoming, string& transactionId ) { assert(sip->sip_request->rq_method != sip_method_invite || NULL == sip->sip_to->a_tag ) ; //new INVITEs only client_ptr client ; RequestRouter& router = m_pController->getRequestRouter() ; string httpMethod, httpUrl ; bool verifyPeer ; if( !router.getRoute( sip->sip_request->rq_method_name, httpMethod, httpUrl, verifyPeer ) ) { //using inbound connections for this call client = m_pClientController->selectClientForRequestOutsideDialog( sip->sip_request->rq_method_name ) ; if( !client ) { DR_LOG(log_error) << "processNewRequest - No providers available for " << sip->sip_request->rq_method_name ; generateUuid( transactionId ) ; return 503 ; } } boost::shared_ptr<PendingRequest_t> p = add( msg, sip ) ; transactionId = p->getTransactionId() ; msg_destroy( msg ) ; //our PendingRequest_t is now the holder of the message string encodedMessage ; EncodeStackMessage( sip, encodedMessage ) ; SipMsgData_t meta( msg ) ; p->setMeta(meta); p->setEncodedMsg(encodedMessage); if( !httpUrl.empty() ) { // using outbound connection for this call vector< pair<string, string> > v; v.push_back( make_pair("method", sip->sip_request->rq_method_name )) ; v.push_back( make_pair("domain", sip->sip_request->rq_url->url_host )) ; v.push_back( make_pair("protocol", meta.getProtocol() )) ; v.push_back( make_pair("source_address", meta.getAddress() )) ; v.push_back( make_pair("fromUser", sip->sip_from->a_url->url_user ? sip->sip_from->a_url->url_user : "" )) ; v.push_back( make_pair("toUser", sip->sip_to->a_url->url_user ? sip->sip_to->a_url->url_user : "" )) ; // add request uri params to the querystring as well if (sip->sip_request->rq_url->url_params) { string paramString(sip->sip_request->rq_url->url_params); vector<string> strs; boost::split(strs, paramString, boost::is_any_of(";")); for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it) { vector<string> kv ; boost::split(kv, *it, boost::is_any_of("=")); v.push_back(pair<string,string>(kv[0], kv.size() == 2 ? kv[1] : "")); } } //tmp!! httpUrl.append("/"); int i = 0 ; pair<string,string> p; BOOST_FOREACH(p, v) { if( i++ > 0 ) { httpUrl.append("&") ; } else { httpUrl.append("?"); } httpUrl.append(p.first) ; httpUrl.append("=") ; httpUrl.append(urlencode(p.second)); } boost::shared_ptr<RequestHandler> pHandler = RequestHandler::getInstance(); pHandler->makeRequestForRoute(transactionId, httpMethod, httpUrl, encodedMessage) ; } else { m_pClientController->addNetTransaction( client, p->getTransactionId() ) ; m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(), encodedMessage, meta ) ) ; } return 0 ; } int PendingRequestController::routeNewRequestToClient( client_ptr client, const string& transactionId) { boost::shared_ptr<PendingRequest_t> p = this->find( transactionId ) ; if( !p ) { DR_LOG(log_error) << "PendingRequestController::routeNewRequestToClient: transactionId not found: " << transactionId ; return 500 ; } m_pClientController->addNetTransaction( client, p->getTransactionId() ) ; m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(), p->getEncodedMsg(), p->getMeta() ) ) ; return 0 ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::add( msg_t* msg, sip_t* sip ) { tport_t *tp = nta_incoming_transport(m_pController->getAgent(), NULL, msg); tport_unref(tp) ; //because the above increments the refcount and we don't need to boost::shared_ptr<PendingRequest_t> p = boost::make_shared<PendingRequest_t>( msg, sip, tp ) ; DR_LOG(log_debug) << "PendingRequestController::add - tport: " << std::hex << (void*) tp << ", Call-ID: " << p->getCallId() << ", transactionId " << p->getTransactionId() ; // give client 4 seconds to respond before clearing state TimerEventHandle handle = m_timerQueue.add( boost::bind(&PendingRequestController::timeout, shared_from_this(), p->getTransactionId()), NULL, CLIENT_TIMEOUT ) ; p->setTimerHandle( handle ) ; string id ; p->getUniqueSipTransactionIdentifier(id) ; boost::lock_guard<boost::mutex> lock(m_mutex) ; m_mapCallId2Invite.insert( mapCallId2Invite::value_type(id, p) ) ; m_mapTxnId2Invite.insert( mapTxnId2Invite::value_type(p->getTransactionId(), p) ) ; return p ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::findAndRemove( const string& transactionId, bool timeout ) { boost::shared_ptr<PendingRequest_t> p ; string id ; boost::lock_guard<boost::mutex> lock(m_mutex) ; mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ; if( it != m_mapTxnId2Invite.end() ) { p = it->second ; m_mapTxnId2Invite.erase( it ) ; p->getUniqueSipTransactionIdentifier(id) ; mapCallId2Invite::iterator it2 = m_mapCallId2Invite.find( id ) ; assert( it2 != m_mapCallId2Invite.end()) ; m_mapCallId2Invite.erase( it2 ) ; if( !timeout ) { m_timerQueue.remove( p->getTimerHandle() ) ; } } return p ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::find( const string& transactionId ) { boost::shared_ptr<PendingRequest_t> p ; boost::lock_guard<boost::mutex> lock(m_mutex) ; mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ; if( it != m_mapTxnId2Invite.end() ) { p = it->second ; } return p ; } void PendingRequestController::timeout(const string& transactionId) { DR_LOG(log_debug) << "PendingRequestController::timeout: giving up on transactionId " << transactionId ; this->findAndRemove( transactionId, true ) ; m_pClientController->removeNetTransaction( transactionId ) ; } void PendingRequestController::logStorageCount(void) { boost::lock_guard<boost::mutex> lock(m_mutex) ; DR_LOG(log_debug) << "PendingRequestController storage counts" ; DR_LOG(log_debug) << "----------------------------------" ; DR_LOG(log_debug) << "m_mapCallId2Invite size: " << m_mapCallId2Invite.size() ; DR_LOG(log_debug) << "m_mapTxnId2Invite size: " << m_mapTxnId2Invite.size() ; } } ; <commit_msg>add content-type, uri, and uriUser to the params sent via http for routing instructions<commit_after>/* Copyright (c) 2013, David C Horton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace drachtio { class SipDialogController ; } #include <boost/bind.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> #include "pending-request-controller.hpp" #include "controller.hpp" #include "cdr.hpp" #include "request-router.hpp" #include "request-handler.hpp" #define CLIENT_TIMEOUT (64000) namespace drachtio { PendingRequest_t::PendingRequest_t(msg_t* msg, sip_t* sip, tport_t* tp ) : m_msg( msg ), m_tp(tp), m_canceled(false), m_callId(sip->sip_call_id->i_id), m_seq(sip->sip_cseq->cs_seq), m_methodName(sip->sip_cseq->cs_method_name) { //DR_LOG(log_debug) << "PendingRequest_t::PendingRequest_t" ; generateUuid( m_transactionId ) ; msg_ref_create( m_msg ) ; } PendingRequest_t::~PendingRequest_t() { msg_destroy( m_msg ) ; } msg_t* PendingRequest_t::getMsg() { return m_msg ; } sip_t* PendingRequest_t::getSipObject() { return sip_object(m_msg); } const string& PendingRequest_t::getCallId() { return m_callId; } const string& PendingRequest_t::getTransactionId() { return m_transactionId; } const string& PendingRequest_t::getMethodName() { return m_methodName; } tport_t* PendingRequest_t::getTport() { return m_tp; } uint32_t PendingRequest_t::getCSeq() { return m_seq; } PendingRequestController::PendingRequestController( DrachtioController* pController) : m_pController(pController), m_agent(pController->getAgent()), m_pClientController(pController->getClientController()), m_timerQueue(pController->getRoot(), "pending-request" ) { assert(m_agent) ; } PendingRequestController::~PendingRequestController() { } int PendingRequestController::processNewRequest( msg_t* msg, sip_t* sip, tport_t* tp_incoming, string& transactionId ) { assert(sip->sip_request->rq_method != sip_method_invite || NULL == sip->sip_to->a_tag ) ; //new INVITEs only client_ptr client ; RequestRouter& router = m_pController->getRequestRouter() ; string httpMethod, httpUrl ; bool verifyPeer ; if( !router.getRoute( sip->sip_request->rq_method_name, httpMethod, httpUrl, verifyPeer ) ) { //using inbound connections for this call client = m_pClientController->selectClientForRequestOutsideDialog( sip->sip_request->rq_method_name ) ; if( !client ) { DR_LOG(log_error) << "processNewRequest - No providers available for " << sip->sip_request->rq_method_name ; generateUuid( transactionId ) ; return 503 ; } } boost::shared_ptr<PendingRequest_t> p = add( msg, sip ) ; transactionId = p->getTransactionId() ; msg_destroy( msg ) ; //our PendingRequest_t is now the holder of the message string encodedMessage ; EncodeStackMessage( sip, encodedMessage ) ; SipMsgData_t meta( msg ) ; p->setMeta(meta); p->setEncodedMsg(encodedMessage); if( !httpUrl.empty() ) { // using outbound connection for this call vector< pair<string, string> > v; v.push_back( make_pair("method", sip->sip_request->rq_method_name )) ; v.push_back( make_pair("domain", sip->sip_request->rq_url->url_host )) ; v.push_back( make_pair("protocol", meta.getProtocol() )) ; v.push_back( make_pair("source_address", meta.getAddress() )) ; v.push_back( make_pair("fromUser", sip->sip_from->a_url->url_user ? sip->sip_from->a_url->url_user : "" )) ; v.push_back( make_pair("toUser", sip->sip_to->a_url->url_user ? sip->sip_to->a_url->url_user : "" )) ; v.push_back( make_pair("uriUser", sip->sip_request->rq_url->url_user ? sip->sip_request->rq_url->url_user : "" )) ; // add content-type string ct = ""; if (sip->sip_content_type && sip->sip_content_type->c_type) { ct = sip->sip_content_type->c_type; } v.push_back( make_pair("contentType", ct)) ; // uri char buf[4096]; url_e(buf, 4096, sip->sip_request->rq_url); v.push_back( make_pair("uri", buf)) ; // add request uri params to the querystring as well if (sip->sip_request->rq_url->url_params) { string paramString(sip->sip_request->rq_url->url_params); vector<string> strs; boost::split(strs, paramString, boost::is_any_of(";")); for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it) { vector<string> kv ; boost::split(kv, *it, boost::is_any_of("=")); v.push_back(pair<string,string>(kv[0], kv.size() == 2 ? kv[1] : "")); } } //tmp!! httpUrl.append("/"); int i = 0 ; pair<string,string> p; BOOST_FOREACH(p, v) { if( i++ > 0 ) { httpUrl.append("&") ; } else { httpUrl.append("?"); } httpUrl.append(p.first) ; httpUrl.append("=") ; httpUrl.append(urlencode(p.second)); } boost::shared_ptr<RequestHandler> pHandler = RequestHandler::getInstance(); pHandler->makeRequestForRoute(transactionId, httpMethod, httpUrl, encodedMessage) ; } else { m_pClientController->addNetTransaction( client, p->getTransactionId() ) ; m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(), encodedMessage, meta ) ) ; } return 0 ; } int PendingRequestController::routeNewRequestToClient( client_ptr client, const string& transactionId) { boost::shared_ptr<PendingRequest_t> p = this->find( transactionId ) ; if( !p ) { DR_LOG(log_error) << "PendingRequestController::routeNewRequestToClient: transactionId not found: " << transactionId ; return 500 ; } m_pClientController->addNetTransaction( client, p->getTransactionId() ) ; m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(), p->getEncodedMsg(), p->getMeta() ) ) ; return 0 ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::add( msg_t* msg, sip_t* sip ) { tport_t *tp = nta_incoming_transport(m_pController->getAgent(), NULL, msg); tport_unref(tp) ; //because the above increments the refcount and we don't need to boost::shared_ptr<PendingRequest_t> p = boost::make_shared<PendingRequest_t>( msg, sip, tp ) ; DR_LOG(log_debug) << "PendingRequestController::add - tport: " << std::hex << (void*) tp << ", Call-ID: " << p->getCallId() << ", transactionId " << p->getTransactionId() ; // give client 4 seconds to respond before clearing state TimerEventHandle handle = m_timerQueue.add( boost::bind(&PendingRequestController::timeout, shared_from_this(), p->getTransactionId()), NULL, CLIENT_TIMEOUT ) ; p->setTimerHandle( handle ) ; string id ; p->getUniqueSipTransactionIdentifier(id) ; boost::lock_guard<boost::mutex> lock(m_mutex) ; m_mapCallId2Invite.insert( mapCallId2Invite::value_type(id, p) ) ; m_mapTxnId2Invite.insert( mapTxnId2Invite::value_type(p->getTransactionId(), p) ) ; return p ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::findAndRemove( const string& transactionId, bool timeout ) { boost::shared_ptr<PendingRequest_t> p ; string id ; boost::lock_guard<boost::mutex> lock(m_mutex) ; mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ; if( it != m_mapTxnId2Invite.end() ) { p = it->second ; m_mapTxnId2Invite.erase( it ) ; p->getUniqueSipTransactionIdentifier(id) ; mapCallId2Invite::iterator it2 = m_mapCallId2Invite.find( id ) ; assert( it2 != m_mapCallId2Invite.end()) ; m_mapCallId2Invite.erase( it2 ) ; if( !timeout ) { m_timerQueue.remove( p->getTimerHandle() ) ; } } return p ; } boost::shared_ptr<PendingRequest_t> PendingRequestController::find( const string& transactionId ) { boost::shared_ptr<PendingRequest_t> p ; boost::lock_guard<boost::mutex> lock(m_mutex) ; mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ; if( it != m_mapTxnId2Invite.end() ) { p = it->second ; } return p ; } void PendingRequestController::timeout(const string& transactionId) { DR_LOG(log_debug) << "PendingRequestController::timeout: giving up on transactionId " << transactionId ; this->findAndRemove( transactionId, true ) ; m_pClientController->removeNetTransaction( transactionId ) ; } void PendingRequestController::logStorageCount(void) { boost::lock_guard<boost::mutex> lock(m_mutex) ; DR_LOG(log_debug) << "PendingRequestController storage counts" ; DR_LOG(log_debug) << "----------------------------------" ; DR_LOG(log_debug) << "m_mapCallId2Invite size: " << m_mapCallId2Invite.size() ; DR_LOG(log_debug) << "m_mapTxnId2Invite size: " << m_mapTxnId2Invite.size() ; } } ; <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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 3 of the License, or (at your option) any later * version. * * cclive 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 "config.h" #include <fstream> #include <string> #include <vector> #ifdef HAVE_ICONV #include <cerrno> #include <iconv.h> #endif #include "hosthandler.h" #include "opts.h" #include "log.h" #include "curl.h" HostHandler::HostHandler() : pageContent(""), props(VideoProperties()) { } HostHandler::~HostHandler() { } const bool HostHandler::isHost(std::string url) { return Util::toLower(url).find(props.getDomain()) != std::string::npos; } void HostHandler::parsePage(const std::string& url) { props.setPageLink(url); pageContent = curlmgr.fetchToMem(url); // Call overridden functions. parseTitle(); parseId (); parseLink (); // Handle title encoding. Done here since we still have page html. toUnicode(); // Apply regexp. std::string title = props.getTitle(); if (optsmgr.getOptions().regexp_given) applyRegexp(title); // Remove leading and trailing whitespace. pcrecpp::RE("^[\\s]+").Replace("", &title); pcrecpp::RE("\\s+$").Replace("", &title); props.setTitle(title); pageContent.clear(); } void HostHandler::toUnicode() { #ifdef HAVE_ICONV std::string charset; // Skip if charset was not found. try { partialMatch("(?i)charset=\"?(.*?)([\"\\/>\\s]|$)", &charset); } catch (const HostHandler::ParseException& x) { return; } std::string from = charset; std::string to = "UTF-8//TRANSLIT"; iconv_t cd = iconv_open( to.c_str(), from.c_str() ); if (cd == (iconv_t)-1) { if (errno == EINVAL) { logmgr.cerr() << "error: conversion from \"" << from << "\" to \"" << to << "\" unavailable" << std::endl; } else { perror("iconv_popen"); return; } } char inbuf[256]; ICONV_CONST char *inptr = inbuf; size_t insize = props.getTitle().length(); if (insize >= sizeof(inbuf)) insize = sizeof(inbuf); snprintf(inbuf, sizeof(inbuf), "%s", props.getTitle().c_str()); char outbuf[256]; size_t avail = sizeof(outbuf); char *wptr = (char *)outbuf; memset(wptr, 0, sizeof(outbuf)); const size_t rc = iconv(cd, &inptr, &insize, &wptr, &avail); iconv_close(cd); cd = 0; if (rc == (size_t)-1) { logmgr.cerr() << "error: converting characters from \"" << from << "\" to \"" << to << "\" failed" << std::endl; } props.setTitle(outbuf); #endif } void HostHandler::applyRegexp(std::string& title) { const Options opts = optsmgr.getOptions(); if (opts.find_all_given) { pcrecpp::StringPiece sp(title); pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8()); title.clear(); std::string s; while (re.FindAndConsume(&sp, &s)) title += s; } else { std::string tmp = title; title.clear(); pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8()) .PartialMatch(tmp, &title); } props.setTitle(title); } void HostHandler::partialMatch( const std::string& re, const pcrecpp::Arg& dst, const std::string& data/*=""*/) { const std::string& content = !data.empty() ? data : pageContent; if (!pcrecpp::RE(re).PartialMatch(content, dst)) throw HostHandler::ParseException("no match: "+re); } const VideoProperties& HostHandler::getVideoProperties() const { return props; } HostHandler:: ParseException::ParseException(const std::string& error) : RuntimeException(CCLIVE_PARSE, error) { } <commit_msg>iconv: correct use of translit.<commit_after>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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 3 of the License, or (at your option) any later * version. * * cclive 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 "config.h" #include <fstream> #include <string> #include <vector> #ifdef HAVE_ICONV #include <cerrno> #include <iconv.h> #endif #include "hosthandler.h" #include "opts.h" #include "log.h" #include "curl.h" HostHandler::HostHandler() : pageContent(""), props(VideoProperties()) { } HostHandler::~HostHandler() { } const bool HostHandler::isHost(std::string url) { return Util::toLower(url).find(props.getDomain()) != std::string::npos; } void HostHandler::parsePage(const std::string& url) { props.setPageLink(url); pageContent = curlmgr.fetchToMem(url); // Call overridden functions. parseTitle(); parseId (); parseLink (); // Handle title encoding. Done here since we still have page html. toUnicode(); // Apply regexp. std::string title = props.getTitle(); if (optsmgr.getOptions().regexp_given) applyRegexp(title); // Remove leading and trailing whitespace. pcrecpp::RE("^[\\s]+").Replace("", &title); pcrecpp::RE("\\s+$").Replace("", &title); props.setTitle(title); pageContent.clear(); } void HostHandler::toUnicode() { #ifdef HAVE_ICONV std::string charset; // Skip if charset was not found. try { partialMatch("(?i)charset=\"?(.*?)([\"\\/>\\s]|$)", &charset); } catch (const HostHandler::ParseException& x) { return; } std::string from = charset; std::string to = "UTF-8"; // Try with TRANSLIT first. iconv_t cd = iconv_open( to.c_str(), std::string(from+"//TRANSLIT").c_str() ); if (cd == (iconv_t)-1) { // Without TRANSLIT. cd = iconv_open( to.c_str(), from.c_str()); } if (cd == (iconv_t)-1) { if (errno == EINVAL) { logmgr.cerr() << "error: conversion from \"" << from << "\" to \"" << to << "\" unavailable" << std::endl; } else { perror("iconv_popen"); return; } } char inbuf[256]; ICONV_CONST char *inptr = inbuf; size_t insize = props.getTitle().length(); if (insize >= sizeof(inbuf)) insize = sizeof(inbuf); snprintf(inbuf, sizeof(inbuf), "%s", props.getTitle().c_str()); char outbuf[256]; size_t avail = sizeof(outbuf); char *wptr = (char *)outbuf; memset(wptr, 0, sizeof(outbuf)); const size_t rc = iconv(cd, &inptr, &insize, &wptr, &avail); iconv_close(cd); cd = 0; if (rc == (size_t)-1) { logmgr.cerr() << "error: converting characters from \"" << from << "\" to \"" << to << "\" failed" << std::endl; } props.setTitle(outbuf); #endif } void HostHandler::applyRegexp(std::string& title) { const Options opts = optsmgr.getOptions(); if (opts.find_all_given) { pcrecpp::StringPiece sp(title); pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8()); title.clear(); std::string s; while (re.FindAndConsume(&sp, &s)) title += s; } else { std::string tmp = title; title.clear(); pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8()) .PartialMatch(tmp, &title); } props.setTitle(title); } void HostHandler::partialMatch( const std::string& re, const pcrecpp::Arg& dst, const std::string& data/*=""*/) { const std::string& content = !data.empty() ? data : pageContent; if (!pcrecpp::RE(re).PartialMatch(content, dst)) throw HostHandler::ParseException("no match: "+re); } const VideoProperties& HostHandler::getVideoProperties() const { return props; } HostHandler:: ParseException::ParseException(const std::string& error) : RuntimeException(CCLIVE_PARSE, error) { } <|endoftext|>
<commit_before>#include "config.h" #include <algorithm> #include <functional> #include "http_client.h" #include "exception.h" #include <cinttypes> #ifndef HAVE_LIBCURL #include "buffered_socket.h" #else #include <cstring> #endif namespace arg3 { namespace net { #define THIS_USER_AGENT "libarg3net" #ifdef HAVE_LIBCURL size_t curl_append_response_callback(void *ptr, size_t size, size_t nmemb, string *s) { if (s == NULL) return 0; const size_t new_len = size * nmemb; char buf[new_len + 1]; memcpy(buf, ptr, size * nmemb); buf[new_len] = '\0'; s->append(buf); return new_len; } #endif size_t skip_newline(const string &s, size_t pos) { for (int i = 0; i < 2; i++, pos++) { if (s[pos] != '\r' && s[pos] != '\n') break; } return pos; } http_transfer::http_transfer() : version_(http::VERSION_1_1) {} http_transfer::http_transfer(const http_transfer &other) : payload_(other.payload_), headers_(other.headers_), version_(other.version_) {} http_transfer::http_transfer(http_transfer &&other) : payload_(std::move(other.payload_)), headers_(std::move(other.headers_)), version_(std::move(other.version_)) {} http_transfer::~http_transfer() {} http_transfer &http_transfer::operator=(const http_transfer &other) { payload_ = other.payload_; headers_ = other.headers_; version_ = other.version_; return *this; } http_transfer &http_transfer::operator=(http_transfer && other) { payload_ = std::move(other.payload_); headers_ = std::move(other.headers_); version_ = std::move(other.version_); return *this; } string http_transfer::header(const string &key) { return headers_[key]; } const map<string, string> http_transfer::headers() const { return headers_; } string http_transfer::payload() const { return payload_; } string http_transfer::version() const { return version_; } void http_transfer::set_version(const string &value) { version_ = value; } http_response::http_response() : responseCode_(0) {} http_response::http_response(const string &fullResponse) : response_(fullResponse), responseCode_(0) { parse(); } http_response::http_response(const http_response &other) : http_transfer(other), response_(other.response_), responseCode_(other.responseCode_) {} http_response::http_response(http_response &&other) : http_transfer(std::move(other)), response_(std::move(other.response_)), responseCode_(std::move(other.responseCode_)) {} http_response::~http_response() {} http_response &http_response::operator=(const http_response &other) { http_transfer::operator=(other); response_ = other.response_; responseCode_ = other.responseCode_; return *this; } http_response &http_response::operator=(http_response && other) { http_transfer::operator=(std::move(other)); response_ = std::move(other.response_); responseCode_ = std::move(other.responseCode_); return *this; } string http_response::full_response() const { return response_; } http_response::operator string() const { return payload_; } int http_response::code() const { return responseCode_; } void http_response::parse(const string &value) { response_ = value; parse(); } void http_response::clear() { response_.clear(); responseCode_ = 0; headers_.clear(); payload_.clear(); } void http_response::parse() { auto pos = response_.find("\r\n"); if (pos == string::npos) { payload_ = response_; return; } string line = response_.substr(0, pos); char buf[http::MAX_URL_LEN + 1] = {0}; char version[http::MAX_URL_LEN + 1] = {0}; if (sscanf(line.c_str(), http::RESPONSE_PREAMBLE, version, &responseCode_, buf) != 3) { payload_ = response_; return; } version_ = version; pos = skip_newline(response_, pos); while (!line.empty()) { auto next = response_.find("\r\n", pos); if (next == string::npos) break; line = response_.substr(pos, next - pos); auto sep = line.find(':'); if (sep != string::npos) { auto key = line.substr(0, sep); auto value = line.substr(sep + 2); headers_[key] = value; } pos = skip_newline(response_, next); } if (pos != string::npos) payload_ = response_.substr(pos); } http_client::http_client(const string &host) : scheme_(http::SCHEME), host_(host) { add_header(http::HEADER_USER_AGENT, THIS_USER_AGENT); } http_client::http_client() { add_header(http::HEADER_USER_AGENT, THIS_USER_AGENT); } http_client::~http_client() { } http_client::http_client(const http_client &other) : http_transfer(other), scheme_(other.scheme_), host_(other.host_), response_(other.response_) { } http_client::http_client(http_client &&other) : http_transfer(std::move(other)), scheme_(std::move(other.scheme_)), host_(std::move(other.host_)), response_(std::move(other.response_)) { } http_client &http_client::operator=(const http_client &other) { http_transfer::operator=(other); scheme_ = other.scheme_; host_ = other.host_; headers_ = other.headers_; return *this; } http_client &http_client::operator=(http_client && other) { http_transfer::operator=(std::move(other)); scheme_ = std::move(other.scheme_); host_ = std::move(other.host_); response_ = std::move(other.response_); return *this; } http_client &http_client::add_header(const string &key, const string &value) { headers_[key] = value; return *this; } void http_client::remove_header(const string &key) { headers_.erase(key); } string http_client::host() const { return host_; } http_response http_client::response() const { return response_; } bool http_client::is_secure() const { return scheme_ == http::SECURE_SCHEME; } http_client &http_client::set_host(const string &host) { host_ = host; return *this; } http_client &http_client::set_secure(bool value) { scheme_ = value ? http::SECURE_SCHEME : http::SCHEME; return *this; } http_client &http_client::set_payload(const string &payload) { payload_ = payload; return *this; } #ifdef HAVE_LIBCURL void http_client::request_curl(http::method method, const string &path) { char buf[http::MAX_URL_LEN + 1] = {0}; struct curl_slist *headers = NULL; CURL *curl_ = curl_easy_init(); if (curl_ == NULL) { throw rest_exception("unable to initialize request"); } if (path.empty()) snprintf(buf, http::MAX_URL_LEN, "%s://%s", scheme_.c_str(), host_.c_str()); else if (path[0] == '/') snprintf(buf, http::MAX_URL_LEN, "%s://%s%s", scheme_.c_str(), host_.c_str(), path.c_str()); else snprintf(buf, http::MAX_URL_LEN, "%s://%s/%s", scheme_.c_str(), host_.c_str(), path.c_str()); curl_easy_setopt(curl_, CURLOPT_URL, buf); curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_append_response_callback); curl_easy_setopt(curl_, CURLOPT_HEADER, 1L); #ifdef DEBUG curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L); #endif switch (method) { case http::GET: curl_easy_setopt(curl_, CURLOPT_HTTPGET, 1L); break; case http::POST: curl_easy_setopt(curl_, CURLOPT_POST, 1L); if (!payload_.empty()) { curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, payload_.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, payload_.size()); } break; case http::PUT: curl_easy_setopt(curl_, CURLOPT_PUT, 1L); if (!payload_.empty()) { curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, payload_.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, payload_.size()); } case http::DELETE: curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, http::method_names[http::DELETE]); break; } for (auto &h : headers_) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", h.first.c_str(), h.second.c_str()); headers = curl_slist_append(headers, buf); } curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response_.response_); CURLcode res = curl_easy_perform(curl_); if (res != CURLE_OK) { curl_easy_cleanup(curl_); throw rest_exception(curl_easy_strerror(res)); } curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &response_.responseCode_); curl_easy_cleanup(curl_); response_.parse(); } #else void http_client::request_socket(http::method method, const string &path) { char buf[http::MAX_URL_LEN + 1] = {0}; buffered_socket sock; // create the socket based on hostname and port auto pos = host().find(':'); if (is_secure()) sock.set_secure(true); if (pos != string::npos) { string hostname = host().substr(0, pos); int port = stoi(host().substr(pos + 1)); if (!sock.connect(hostname, port)) throw socket_exception("unable to connect to " + host()); } else { if (!sock.connect(host(), is_secure() ? http::DEFAULT_SECURE_PORT : http::DEFAULT_PORT)) throw socket_exception("unable to connect to " + host()); } // send the method and path if (path.empty()) snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], "/", version_.c_str()); else if (path[0] == '/') snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], path.c_str(), version_.c_str()); else snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], ("/" + path).c_str(), version_.c_str()); sock.writeln(buf); bool chunked = headers_.count(http::HEADER_TRANSFER_ENCODING) != 0 && !strcasecmp(headers_[http::HEADER_TRANSFER_ENCODING].c_str(), "chunked"); // specify the host if (headers_.count(http::HEADER_HOST) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", http::HEADER_HOST, host().c_str()); sock.writeln(buf); } if (headers_.count(http::HEADER_ACCEPT) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: */*", http::HEADER_ACCEPT); sock.writeln(buf); } if (headers_.count(http::HEADER_CONNECTION) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: close", http::HEADER_CONNECTION); sock.writeln(buf); } // add the headers for (const auto &h : headers_) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", h.first.c_str(), h.second.c_str()); sock.writeln(buf); } // if we have a payload, add the size if (!chunked && !payload_.empty()) { snprintf(buf, http::MAX_URL_LEN, "%s: %zu", http::HEADER_CONTENT_SIZE, payload_.size()); sock.writeln(buf); } // finish header sock.writeln(); // add the payload if (!payload_.empty()) { sock.write(payload_); } #ifdef DEBUG cout << string(sock.output().begin(), sock.output().end()); #endif if (!sock.write_from_buffer()) throw socket_exception("unable to write to socket"); if (!sock.read_to_buffer()) throw socket_exception("unable to read from socket"); auto input = sock.input(); response_.parse(string(input.begin(), input.end())); //sock.close(); } #endif http_client &http_client::request(http::method method, const string &path) { response_.clear(); if (host_.empty()) throw socket_exception("no host"); #ifdef HAVE_LIBCURL request_curl(method, path); #else request_socket(method, path); #endif return *this; } http_client &http_client::get(const string &path) { return request(http::GET, path); } http_client &http_client::post(const string &path) { return request(http::POST, path); } http_client &http_client::put(const string &path) { return request(http::PUT, path); } http_client &http_client::de1ete(const string &path) { return request(http::DELETE, path); } } } <commit_msg>fix header issue<commit_after>#include "config.h" #include <algorithm> #include <functional> #include "http_client.h" #include "exception.h" #include <cinttypes> #ifndef HAVE_LIBCURL #include "buffered_socket.h" #else #include <strings.h> #endif namespace arg3 { namespace net { #define THIS_USER_AGENT "libarg3net" #ifdef HAVE_LIBCURL size_t curl_append_response_callback(void *ptr, size_t size, size_t nmemb, string *s) { if (s == NULL) return 0; const size_t new_len = size * nmemb; char buf[new_len + 1]; memcpy(buf, ptr, size * nmemb); buf[new_len] = '\0'; s->append(buf); return new_len; } #endif size_t skip_newline(const string &s, size_t pos) { for (int i = 0; i < 2; i++, pos++) { if (s[pos] != '\r' && s[pos] != '\n') break; } return pos; } http_transfer::http_transfer() : version_(http::VERSION_1_1) { } http_transfer::http_transfer(const http_transfer &other) : payload_(other.payload_), headers_(other.headers_), version_(other.version_) { } http_transfer::http_transfer(http_transfer &&other) : payload_(std::move(other.payload_)), headers_(std::move(other.headers_)), version_(std::move(other.version_)) { } http_transfer::~http_transfer() { } http_transfer &http_transfer::operator=(const http_transfer &other) { payload_ = other.payload_; headers_ = other.headers_; version_ = other.version_; return *this; } http_transfer &http_transfer::operator=(http_transfer &&other) { payload_ = std::move(other.payload_); headers_ = std::move(other.headers_); version_ = std::move(other.version_); return *this; } string http_transfer::header(const string &key) { return headers_[key]; } const map<string, string> http_transfer::headers() const { return headers_; } string http_transfer::payload() const { return payload_; } string http_transfer::version() const { return version_; } void http_transfer::set_version(const string &value) { version_ = value; } http_response::http_response() : responseCode_(0) { } http_response::http_response(const string &fullResponse) : response_(fullResponse), responseCode_(0) { parse(); } http_response::http_response(const http_response &other) : http_transfer(other), response_(other.response_), responseCode_(other.responseCode_) { } http_response::http_response(http_response &&other) : http_transfer(std::move(other)), response_(std::move(other.response_)), responseCode_(std::move(other.responseCode_)) { } http_response::~http_response() { } http_response &http_response::operator=(const http_response &other) { http_transfer::operator=(other); response_ = other.response_; responseCode_ = other.responseCode_; return *this; } http_response &http_response::operator=(http_response &&other) { http_transfer::operator=(std::move(other)); response_ = std::move(other.response_); responseCode_ = std::move(other.responseCode_); return *this; } string http_response::full_response() const { return response_; } http_response::operator string() const { return payload_; } int http_response::code() const { return responseCode_; } void http_response::parse(const string &value) { response_ = value; parse(); } void http_response::clear() { response_.clear(); responseCode_ = 0; headers_.clear(); payload_.clear(); } void http_response::parse() { auto pos = response_.find("\r\n"); if (pos == string::npos) { payload_ = response_; return; } string line = response_.substr(0, pos); char buf[http::MAX_URL_LEN + 1] = {0}; char version[http::MAX_URL_LEN + 1] = {0}; if (sscanf(line.c_str(), http::RESPONSE_PREAMBLE, version, &responseCode_, buf) != 3) { payload_ = response_; return; } version_ = version; pos = skip_newline(response_, pos); while (!line.empty()) { auto next = response_.find("\r\n", pos); if (next == string::npos) break; line = response_.substr(pos, next - pos); auto sep = line.find(':'); if (sep != string::npos) { auto key = line.substr(0, sep); auto value = line.substr(sep + 2); headers_[key] = value; } pos = skip_newline(response_, next); } if (pos != string::npos) payload_ = response_.substr(pos); } http_client::http_client(const string &host) : scheme_(http::SCHEME), host_(host) { add_header(http::HEADER_USER_AGENT, THIS_USER_AGENT); } http_client::http_client() { add_header(http::HEADER_USER_AGENT, THIS_USER_AGENT); } http_client::~http_client() { } http_client::http_client(const http_client &other) : http_transfer(other), scheme_(other.scheme_), host_(other.host_), response_(other.response_) { } http_client::http_client(http_client &&other) : http_transfer(std::move(other)), scheme_(std::move(other.scheme_)), host_(std::move(other.host_)), response_(std::move(other.response_)) { } http_client &http_client::operator=(const http_client &other) { http_transfer::operator=(other); scheme_ = other.scheme_; host_ = other.host_; headers_ = other.headers_; return *this; } http_client &http_client::operator=(http_client &&other) { http_transfer::operator=(std::move(other)); scheme_ = std::move(other.scheme_); host_ = std::move(other.host_); response_ = std::move(other.response_); return *this; } http_client &http_client::add_header(const string &key, const string &value) { headers_[key] = value; return *this; } void http_client::remove_header(const string &key) { headers_.erase(key); } string http_client::host() const { return host_; } http_response http_client::response() const { return response_; } bool http_client::is_secure() const { return scheme_ == http::SECURE_SCHEME; } http_client &http_client::set_host(const string &host) { host_ = host; return *this; } http_client &http_client::set_secure(bool value) { scheme_ = value ? http::SECURE_SCHEME : http::SCHEME; return *this; } http_client &http_client::set_payload(const string &payload) { payload_ = payload; return *this; } #ifdef HAVE_LIBCURL void http_client::request_curl(http::method method, const string &path) { char buf[http::MAX_URL_LEN + 1] = {0}; struct curl_slist *headers = NULL; CURL *curl_ = curl_easy_init(); if (curl_ == NULL) { throw rest_exception("unable to initialize request"); } if (path.empty()) snprintf(buf, http::MAX_URL_LEN, "%s://%s", scheme_.c_str(), host_.c_str()); else if (path[0] == '/') snprintf(buf, http::MAX_URL_LEN, "%s://%s%s", scheme_.c_str(), host_.c_str(), path.c_str()); else snprintf(buf, http::MAX_URL_LEN, "%s://%s/%s", scheme_.c_str(), host_.c_str(), path.c_str()); curl_easy_setopt(curl_, CURLOPT_URL, buf); curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_append_response_callback); curl_easy_setopt(curl_, CURLOPT_HEADER, 1L); #ifdef DEBUG curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L); #endif switch (method) { case http::GET: curl_easy_setopt(curl_, CURLOPT_HTTPGET, 1L); break; case http::POST: curl_easy_setopt(curl_, CURLOPT_POST, 1L); if (!payload_.empty()) { curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, payload_.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, payload_.size()); } break; case http::PUT: curl_easy_setopt(curl_, CURLOPT_PUT, 1L); if (!payload_.empty()) { curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, payload_.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, payload_.size()); } case http::DELETE: curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, http::method_names[http::DELETE]); break; } for (auto &h : headers_) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", h.first.c_str(), h.second.c_str()); headers = curl_slist_append(headers, buf); } curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response_.response_); CURLcode res = curl_easy_perform(curl_); if (res != CURLE_OK) { curl_easy_cleanup(curl_); throw rest_exception(curl_easy_strerror(res)); } curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &response_.responseCode_); curl_easy_cleanup(curl_); response_.parse(); } #else void http_client::request_socket(http::method method, const string &path) { char buf[http::MAX_URL_LEN + 1] = {0}; buffered_socket sock; // create the socket based on hostname and port auto pos = host().find(':'); if (is_secure()) sock.set_secure(true); if (pos != string::npos) { string hostname = host().substr(0, pos); int port = stoi(host().substr(pos + 1)); if (!sock.connect(hostname, port)) throw socket_exception("unable to connect to " + host()); } else { if (!sock.connect(host(), is_secure() ? http::DEFAULT_SECURE_PORT : http::DEFAULT_PORT)) throw socket_exception("unable to connect to " + host()); } // send the method and path if (path.empty()) snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], "/", version_.c_str()); else if (path[0] == '/') snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], path.c_str(), version_.c_str()); else snprintf(buf, http::MAX_URL_LEN, http::REQUEST_PREAMBLE, http::method_names[method], ("/" + path).c_str(), version_.c_str()); sock.writeln(buf); bool chunked = headers_.count(http::HEADER_TRANSFER_ENCODING) != 0 && !strcasecmp(headers_[http::HEADER_TRANSFER_ENCODING].c_str(), "chunked"); // specify the host if (headers_.count(http::HEADER_HOST) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", http::HEADER_HOST, host().c_str()); sock.writeln(buf); } if (headers_.count(http::HEADER_ACCEPT) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: */*", http::HEADER_ACCEPT); sock.writeln(buf); } if (headers_.count(http::HEADER_CONNECTION) == 0) { snprintf(buf, http::MAX_URL_LEN, "%s: close", http::HEADER_CONNECTION); sock.writeln(buf); } // add the headers for (const auto &h : headers_) { snprintf(buf, http::MAX_URL_LEN, "%s: %s", h.first.c_str(), h.second.c_str()); sock.writeln(buf); } // if we have a payload, add the size if (!chunked && !payload_.empty()) { snprintf(buf, http::MAX_URL_LEN, "%s: %zu", http::HEADER_CONTENT_SIZE, payload_.size()); sock.writeln(buf); } // finish header sock.writeln(); // add the payload if (!payload_.empty()) { sock.write(payload_); } #ifdef DEBUG cout << string(sock.output().begin(), sock.output().end()); #endif if (!sock.write_from_buffer()) throw socket_exception("unable to write to socket"); if (!sock.read_to_buffer()) throw socket_exception("unable to read from socket"); auto input = sock.input(); response_.parse(string(input.begin(), input.end())); // sock.close(); } #endif http_client &http_client::request(http::method method, const string &path) { response_.clear(); if (host_.empty()) throw socket_exception("no host"); #ifdef HAVE_LIBCURL request_curl(method, path); #else request_socket(method, path); #endif return *this; } http_client &http_client::get(const string &path) { return request(http::GET, path); } http_client &http_client::post(const string &path) { return request(http::POST, path); } http_client &http_client::put(const string &path) { return request(http::PUT, path); } http_client &http_client::de1ete(const string &path) { return request(http::DELETE, path); } } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2015 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 "http_client.h" #include "str_helpers.h" #include <iomanip> #include <sstream> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> multipart_form_data::multipart_form_data() { boost::uuids::random_generator gen; m_boundary = boost::uuids::to_string(gen()); } void multipart_form_data::add_value(const std::string& name, const std::string& value) { m_body += "--" + m_boundary + "\r\n"; m_body += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"; m_body += value; m_body += "\r\n"; } void multipart_form_data::add_file(const std::string& name, const std::string& filename, const std::string& file_content) { m_body += "--" + m_boundary + "\r\n"; m_body += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n"; m_body += "Content-Type: application/octet-stream\r\n"; m_body += "Content-Transfer-Encoding: binary\r\n"; m_body += "\r\n"; m_body += file_content; m_body += "\r\n"; } std::string multipart_form_data::content_type() const { return "multipart/form-data; boundary=" + m_boundary; } std::string multipart_form_data::body() const { return m_body + "--" + m_boundary + "--\r\n\r\n"; } void urlencoded_data::add_value(const std::string& name, const std::string& value) { if (!m_body.empty()) m_body += '&'; m_body += name; m_body += '='; m_body += http_client::url_encode(value); } std::string http_client::url_encode(const std::string& s) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto c: s) { if (c == '-' || c == '_' || c == '.' || c == '~' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { escaped << c; } else { escaped << '%' << std::setw(2) << int((unsigned char)c); } } return escaped.str(); } std::string http_client::url_encode(const std::wstring& s) { return url_encode(str::to_utf8(s)); } <commit_msg>Use + in urlencoded data in http_client<commit_after>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2015 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 "http_client.h" #include "str_helpers.h" #include <iomanip> #include <sstream> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> multipart_form_data::multipart_form_data() { boost::uuids::random_generator gen; m_boundary = boost::uuids::to_string(gen()); } void multipart_form_data::add_value(const std::string& name, const std::string& value) { m_body += "--" + m_boundary + "\r\n"; m_body += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"; m_body += value; m_body += "\r\n"; } void multipart_form_data::add_file(const std::string& name, const std::string& filename, const std::string& file_content) { m_body += "--" + m_boundary + "\r\n"; m_body += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n"; m_body += "Content-Type: application/octet-stream\r\n"; m_body += "Content-Transfer-Encoding: binary\r\n"; m_body += "\r\n"; m_body += file_content; m_body += "\r\n"; } std::string multipart_form_data::content_type() const { return "multipart/form-data; boundary=" + m_boundary; } std::string multipart_form_data::body() const { return m_body + "--" + m_boundary + "--\r\n\r\n"; } void urlencoded_data::add_value(const std::string& name, const std::string& value) { if (!m_body.empty()) m_body += '&'; m_body += name; m_body += '='; m_body += http_client::url_encode(value); } std::string http_client::url_encode(const std::string& s) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto c: s) { if (c == '-' || c == '_' || c == '.' || c == '~' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { escaped << c; } else if (c == ' ') { escaped << '+'; } else { escaped << '%' << std::setw(2) << int((unsigned char)c); } } return escaped.str(); } std::string http_client::url_encode(const std::wstring& s) { return url_encode(str::to_utf8(s)); } <|endoftext|>
<commit_before>#include <string> #include <fstream> #include <iostream> #include <utility> #include <cstdio> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ptrace.h> #include <sys/wait.h> #include <sys/user.h> #include "dwarf/dwarf++.hh" #include "elf/elf++.hh" #include "linenoise.h" class breakpoint { public: breakpoint(pid_t pid, std::intptr_t addr) : m_pid{pid}, m_addr{addr}, m_enabled{false}, m_saved_data{} {} void enable() { m_saved_data = ptrace(PTRACE_PEEKTEXT, m_pid, (void*)m_addr, 0); auto int3 = 0xcc; auto data_with_int3 = (m_saved_data & ~0xff | int3); ptrace(PTRACE_POKETEXT, m_pid, (void*)m_addr, data_with_int3); m_enabled = true; } void disable() { ptrace(PTRACE_POKETEXT, m_pid, (void*)m_addr, m_saved_data); m_enabled = false; } std::intptr_t get_address() { return m_addr; } private: pid_t m_pid; std::intptr_t m_addr; bool m_enabled; unsigned m_saved_data; }; class debugger { public: debugger (std::string prog_name, pid_t pid) : m_prog_name{std::move(prog_name)}, m_pid{pid} { auto fd = open(m_prog_name.c_str(), O_RDONLY); m_elf = elf::elf{elf::create_mmap_loader(fd)}; m_dwarf = dwarf::dwarf{dwarf::elf::create_loader(m_elf)}; } void run(); void dump_registers(); void continue_execution(); void single_step_instruction(); siginfo_t get_signal_info(); void set_breakpoint_at_address(std::intptr_t addr); void set_breakpoint_at_source_line(const std::string& file, unsigned line); void print_source(const std::string& file_name, unsigned line, unsigned n_lines_context=2); private: void handle_command(const std::string& line); void handle_sigtrap(siginfo_t info); void wait_for_signal(); uint64_t get_pc(); void set_pc(uint64_t pc); void decrement_pc(); dwarf::line_table::entry get_current_line_entry(); std::string m_prog_name; pid_t m_pid; dwarf::dwarf m_dwarf; elf::elf m_elf; unsigned m_saved_data; std::unique_ptr<breakpoint> m_breakpoint; }; uint64_t debugger::get_pc() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); return regs.rip; } void debugger::set_pc(uint64_t pc) { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); regs.rip = pc; ptrace(PTRACE_SETREGS, m_pid, nullptr, &regs); } void debugger::decrement_pc() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); regs.rip -= 1; ptrace(PTRACE_SETREGS, m_pid, nullptr, &regs); } dwarf::line_table::entry debugger::get_current_line_entry() { auto pc = get_pc(); for (auto &cu : m_dwarf.compilation_units()) { if (die_pc_range(cu.root()).contains(pc)) { auto &lt = cu.get_line_table(); auto it = lt.find_address(pc); if (it == lt.end()) { throw std::out_of_range{"Cannot find line entry"}; } else { return *it; } } } throw std::out_of_range{"Cannot find line entry"}; } void debugger::run() { char* line = nullptr; while((line = linenoise("minidbg> ")) != nullptr) { handle_command(line); linenoiseHistoryAdd(line); linenoiseFree(line); } } void debugger::print_source(const std::string& file_name, unsigned line, unsigned n_lines_context) { std::ifstream file {file_name}; auto start_line = line < n_lines_context ? 0 : line - n_lines_context; auto end_line = line + n_lines_context + (line < n_lines_context ? n_lines_context - line : 0) + 1; char c{}; auto current_line = 1u; while (current_line != start_line && file.get(c)) { if (c == '\n') { ++current_line; } } std::cout << (current_line==line ? "> " : " "); while (current_line != end_line && file.get(c)) { std::cout << c; if (c == '\n') { ++current_line; std::cout << (current_line==line ? "> " : " "); } } std::cout << std::endl; } bool is_prefix(const std::string& s, const std::string& of) { if (s.size() > of.size()) return false; return std::equal(s.begin(), s.end(), of.begin()); } bool is_suffix(const std::string& s, const std::string& of) { if (s.size() > of.size()) return false; auto diff = of.size() - s.size(); return std::equal(s.begin(), s.end(), of.begin() + diff); } siginfo_t debugger::get_signal_info() { siginfo_t info; ptrace(PTRACE_GETSIGINFO, m_pid, nullptr, &info); return info; } void debugger::handle_sigtrap(siginfo_t info) { switch (info.si_code) { case SI_KERNEL: case TRAP_BRKPT: { std::cout << "Hit breakpoint at address 0x" << std::hex << get_pc() << std::endl; auto line_entry = get_current_line_entry(); print_source(line_entry.file->path, line_entry.line); return; } case TRAP_TRACE: std::cout << "Finished single stepping" << std::endl; return; default: std::cout << "Unknown SIGTRAP code " << info.si_code << std::endl; return; } } void debugger::wait_for_signal() { int wait_status; auto options = 0; waitpid(m_pid, &wait_status, options); auto siginfo = get_signal_info(); switch (siginfo.si_signo) { case SIGTRAP: handle_sigtrap(siginfo); break; case SIGSEGV: std::cout << "Yay, segfault" << std::endl; break; default: std::cout << "Got signal " << strsignal(siginfo.si_signo) << std::endl; } } void debugger::continue_execution() { if (m_breakpoint && m_breakpoint->get_address() == get_pc() - 1) { m_breakpoint->disable(); dump_registers(); decrement_pc(); dump_registers(); // single_step_instruction(); // m_breakpoint->enable(); } ptrace(PTRACE_CONT, m_pid, nullptr, nullptr); wait_for_signal(); } void debugger::single_step_instruction() { ptrace(PTRACE_SINGLESTEP, m_pid, nullptr, nullptr); wait_for_signal(); } void debugger::set_breakpoint_at_address(std::intptr_t addr) { std::cout << "Set breakpoint at address 0x" << std::hex << addr << std::endl; m_breakpoint = std::make_unique<breakpoint>(m_pid, addr); m_breakpoint->enable(); } void debugger::set_breakpoint_at_source_line(const std::string& file, unsigned line) { for (const auto& cu : m_dwarf.compilation_units()) { if (is_suffix(file, at_name(cu.root()))) { const auto& lt = cu.get_line_table(); for (const auto& entry : lt) { if (entry.is_stmt && entry.line == line) { set_breakpoint_at_address(entry.address); return; } } } } } void debugger::dump_registers() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); std::cout << "r15" << ' ' << std::hex << regs.r15 << std::endl; std::cout << "r14" << ' ' << std::hex << regs.r14 << std::endl; std::cout << "r13" << ' ' << std::hex << regs.r13 << std::endl; std::cout << "r12" << ' ' << std::hex << regs.r12 << std::endl; std::cout << "bp" << ' ' << std::hex << regs.rbp << std::endl; std::cout << "bx" << ' ' << std::hex << regs.rbx << std::endl; std::cout << "r11" << ' ' << std::hex << regs.r11 << std::endl; std::cout << "r10" << ' ' << std::hex << regs.r10 << std::endl; std::cout << "r9" << ' ' << std::hex << regs.r9 << std::endl; std::cout << "r8" << ' ' << std::hex << regs.r8 << std::endl; std::cout << "ax" << ' ' << std::hex << regs.rax << std::endl; std::cout << "cx" << ' ' << std::hex << regs.rcx << std::endl; std::cout << "dx" << ' ' << std::hex << regs.rdx << std::endl; std::cout << "si" << ' ' << std::hex << regs.rsi << std::endl; std::cout << "di" << ' ' << std::hex << regs.rdi << std::endl; std::cout << "orig_ax" << ' ' << std::hex << regs.orig_rax << std::endl; std::cout << "ip" << ' ' << std::hex << regs.rip << std::endl; std::cout << "cs" << ' ' << std::hex << regs.cs << std::endl; std::cout << "flags" << ' ' << std::hex << regs.eflags << std::endl; std::cout << "sp" << ' ' << std::hex << regs.rsp << std::endl; std::cout << "ss" << ' ' << std::hex << regs.ss << std::endl; std::cout << "fs_base" << ' ' << std::hex << regs.fs_base << std::endl; std::cout << "gs_base" << ' ' << std::hex << regs.gs_base << std::endl; std::cout << "ds" << ' ' << std::hex << regs.ds << std::endl; std::cout << "es" << ' ' << std::hex << regs.es << std::endl; std::cout << "fs" << ' ' << std::hex << regs.fs << std::endl; std::cout << "gs" << ' ' << std::hex << regs.gs << std::endl; } void debugger::handle_command(const std::string& line) { if (is_prefix(line, "cont")) { continue_execution(); } else if (is_prefix(line, "line")) { auto line_entry = get_current_line_entry(); std::cout << line_entry.file->path << ':' << line_entry.line << std::endl; } else if (is_prefix(line, "registers")) { dump_registers(); } else if (is_prefix(line, "pc")) { std::cout << std::hex << get_pc() << std::endl; } else if(is_prefix(line, "break")) { set_breakpoint_at_source_line("hello.cpp", 4); } else if(is_prefix(line, "step")) { single_step_instruction(); } else { std::cerr << "Unknown command\n"; } } void execute_debugger (const std::string& prog_name, pid_t pid) { int wait_status; wait(&wait_status); debugger dbg{prog_name, pid}; dbg.run(); } void execute_debugee (const std::string& prog_name) { if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) { std::cerr << "Error in ptrace\n"; return; } execl(prog_name.c_str(), prog_name.c_str(), nullptr); } int main(int argc, char* argv[]) { auto prog = argv[1]; auto pid = fork(); if (pid == 0) { //child execute_debugee(prog); } else if (pid >= 1) { //parent execute_debugger(prog, pid); } else { std::cerr << "Error forking"; } } <commit_msg>Fix breakpoint saving and restoring<commit_after>#include <string> #include <fstream> #include <iostream> #include <iomanip> #include <utility> #include <cstdio> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ptrace.h> #include <sys/wait.h> #include <sys/user.h> #include "dwarf/dwarf++.hh" #include "elf/elf++.hh" #include "linenoise.h" class breakpoint { public: breakpoint(pid_t pid, std::intptr_t addr) : m_pid{pid}, m_addr{addr}, m_enabled{false}, m_saved_data{} {} void enable() { m_saved_data = ptrace(PTRACE_PEEKTEXT, m_pid, (void*)m_addr, 0); uint64_t int3 = 0xcc; uint64_t data_with_int3 = (m_saved_data & ~0xff | int3); ptrace(PTRACE_POKETEXT, m_pid, (void*)m_addr, data_with_int3); m_enabled = true; } void disable() { ptrace(PTRACE_POKETEXT, m_pid, (void*)m_addr, m_saved_data); m_enabled = false; } bool is_enabled() { return m_enabled; } std::intptr_t get_address() { return m_addr; } private: pid_t m_pid; std::intptr_t m_addr; bool m_enabled; uint64_t m_saved_data; }; class debugger { public: debugger (std::string prog_name, pid_t pid) : m_prog_name{std::move(prog_name)}, m_pid{pid} { auto fd = open(m_prog_name.c_str(), O_RDONLY); m_elf = elf::elf{elf::create_mmap_loader(fd)}; m_dwarf = dwarf::dwarf{dwarf::elf::create_loader(m_elf)}; } void run(); void dump_registers(); void read_memory(); void continue_execution(); void single_step_instruction(); siginfo_t get_signal_info(); void set_breakpoint_at_address(std::intptr_t addr); void set_breakpoint_at_source_line(const std::string& file, unsigned line); void print_source(const std::string& file_name, unsigned line, unsigned n_lines_context=2); private: void unchecked_single_step_instruction(); void handle_command(const std::string& line); void handle_sigtrap(siginfo_t info); void wait_for_signal(); uint64_t get_pc(); void set_pc(uint64_t pc); void decrement_pc(); dwarf::line_table::entry get_current_line_entry(); std::string m_prog_name; pid_t m_pid; dwarf::dwarf m_dwarf; elf::elf m_elf; unsigned m_saved_data; std::unique_ptr<breakpoint> m_breakpoint; }; uint64_t debugger::get_pc() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); return regs.rip; } void debugger::set_pc(uint64_t pc) { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); regs.rip = pc; ptrace(PTRACE_SETREGS, m_pid, nullptr, &regs); } void debugger::decrement_pc() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); regs.rip -= 1; ptrace(PTRACE_SETREGS, m_pid, nullptr, &regs); } dwarf::line_table::entry debugger::get_current_line_entry() { auto pc = get_pc(); for (auto &cu : m_dwarf.compilation_units()) { if (die_pc_range(cu.root()).contains(pc)) { auto &lt = cu.get_line_table(); auto it = lt.find_address(pc); if (it == lt.end()) { throw std::out_of_range{"Cannot find line entry"}; } else { return *it; } } } throw std::out_of_range{"Cannot find line entry"}; } void debugger::run() { char* line = nullptr; while((line = linenoise("minidbg> ")) != nullptr) { handle_command(line); linenoiseHistoryAdd(line); linenoiseFree(line); } } void debugger::print_source(const std::string& file_name, unsigned line, unsigned n_lines_context) { std::ifstream file {file_name}; auto start_line = line < n_lines_context ? 0 : line - n_lines_context; auto end_line = line + n_lines_context + (line < n_lines_context ? n_lines_context - line : 0) + 1; char c{}; auto current_line = 1u; while (current_line != start_line && file.get(c)) { if (c == '\n') { ++current_line; } } std::cout << (current_line==line ? "> " : " "); while (current_line != end_line && file.get(c)) { std::cout << c; if (c == '\n') { ++current_line; std::cout << (current_line==line ? "> " : " "); } } std::cout << std::endl; } bool is_prefix(const std::string& s, const std::string& of) { if (s.size() > of.size()) return false; return std::equal(s.begin(), s.end(), of.begin()); } bool is_suffix(const std::string& s, const std::string& of) { if (s.size() > of.size()) return false; auto diff = of.size() - s.size(); return std::equal(s.begin(), s.end(), of.begin() + diff); } siginfo_t debugger::get_signal_info() { siginfo_t info; ptrace(PTRACE_GETSIGINFO, m_pid, nullptr, &info); return info; } void debugger::handle_sigtrap(siginfo_t info) { switch (info.si_code) { case SI_KERNEL: case TRAP_BRKPT: { decrement_pc(); std::cout << "Hit breakpoint at address 0x" << std::hex << get_pc() << std::endl; auto line_entry = get_current_line_entry(); print_source(line_entry.file->path, line_entry.line); return; } case TRAP_TRACE: std::cout << "Finished single stepping" << std::endl; return; default: std::cout << "Unknown SIGTRAP code " << info.si_code << std::endl; return; } } void debugger::wait_for_signal() { int wait_status; auto options = 0; waitpid(m_pid, &wait_status, options); auto siginfo = get_signal_info(); switch (siginfo.si_signo) { case SIGTRAP: handle_sigtrap(siginfo); break; case SIGSEGV: std::cout << "Yay, segfault. Reason: " << siginfo.si_code << std::endl; break; default: std::cout << "Got signal " << strsignal(siginfo.si_signo) << std::endl; } } void debugger::continue_execution() { if (m_breakpoint && m_breakpoint->get_address() == get_pc()) { m_breakpoint->disable(); unchecked_single_step_instruction(); m_breakpoint->enable(); } ptrace(PTRACE_CONT, m_pid, nullptr, nullptr); wait_for_signal(); } void debugger::unchecked_single_step_instruction() { ptrace(PTRACE_SINGLESTEP, m_pid, nullptr, nullptr); wait_for_signal(); } void debugger::single_step_instruction() { if (m_breakpoint && m_breakpoint->get_address() == get_pc()) { m_breakpoint->disable(); unchecked_single_step_instruction(); m_breakpoint->enable(); return; } unchecked_single_step_instruction(); } void debugger::set_breakpoint_at_address(std::intptr_t addr) { std::cout << "Set breakpoint at address 0x" << std::hex << addr << std::endl; m_breakpoint = std::make_unique<breakpoint>(m_pid, addr); m_breakpoint->enable(); } void debugger::set_breakpoint_at_source_line(const std::string& file, unsigned line) { for (const auto& cu : m_dwarf.compilation_units()) { if (is_suffix(file, at_name(cu.root()))) { const auto& lt = cu.get_line_table(); for (const auto& entry : lt) { if (entry.is_stmt && entry.line == line) { set_breakpoint_at_address(entry.address); return; } } } } } void debugger::dump_registers() { struct user_regs_struct regs; ptrace(PTRACE_GETREGS, m_pid, nullptr, &regs); std::cout << "rax 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rax << std::endl; std::cout << "rbx 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rbx << std::endl; std::cout << "rcx 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rcx << std::endl; std::cout << "rdx 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rdx << std::endl; std::cout << "rdi 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rdi << std::endl; std::cout << "rsi 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rsi << std::endl; std::cout << "rbp 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rbp << std::endl; std::cout << "rsp 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rsp << std::endl; std::cout << "r8 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r8 << std::endl; std::cout << "r9 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r9 << std::endl; std::cout << "r10 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r10 << std::endl; std::cout << "r11 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r11 << std::endl; std::cout << "r12 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r12 << std::endl; std::cout << "r13 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r13 << std::endl; std::cout << "r14 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r14 << std::endl; std::cout << "r15 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.r15 << std::endl; std::cout << "rip 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.rip << std::endl; std::cout << "rflags 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.eflags << std::endl; std::cout << "cs 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.cs << std::endl; std::cout << "fs 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.fs << std::endl; std::cout << "gs 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.gs << std::endl; std::cout << "ss 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.ss << std::endl; std::cout << "ds 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.ds << std::endl; std::cout << "es 0x" << std::setfill('0') << std::setw(16) << std::hex << regs.es << std::endl; } void debugger::read_memory() { std::cout << std::hex << ptrace(PTRACE_PEEKDATA, m_pid, 0x40089a, nullptr) << std::endl; std::cout << std::hex << ptrace(PTRACE_PEEKDATA, m_pid, 0x40089e, nullptr) << std::endl; std::cout << std::hex << ptrace(PTRACE_PEEKDATA, m_pid, 0x400893, nullptr) << std::endl; } void debugger::handle_command(const std::string& line) { if (is_prefix(line, "cont")) { continue_execution(); } else if (is_prefix(line, "line")) { auto line_entry = get_current_line_entry(); std::cout << line_entry.file->path << ':' << line_entry.line << std::endl; } else if (is_prefix(line, "registers")) { dump_registers(); } else if (is_prefix(line, "pc")) { std::cout << std::hex << get_pc() << std::endl; } else if(is_prefix(line, "break")) { set_breakpoint_at_source_line("hello.cpp", 4); } else if(is_prefix(line, "step")) { single_step_instruction(); } else if(is_prefix(line, "memory")) { read_memory(); } else { std::cerr << "Unknown command\n"; } } void execute_debugger (const std::string& prog_name, pid_t pid) { int wait_status; wait(&wait_status); debugger dbg{prog_name, pid}; dbg.run(); } void execute_debugee (const std::string& prog_name) { if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) { std::cerr << "Error in ptrace\n"; return; } execl(prog_name.c_str(), prog_name.c_str(), nullptr); } int main(int argc, char* argv[]) { auto prog = argv[1]; auto pid = fork(); if (pid == 0) { //child execute_debugee(prog); } else if (pid >= 1) { //parent execute_debugger(prog, pid); } else { std::cerr << "Error forking"; } } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "image_helper.hh" bool ishere(int hayx,int neex,int neey,int x,int y, const PixelPacket *hay_pixel, const PixelPacket *nee_pixel) { // Check diagonal first. Seems to speed up things. for(int i=0;i<neey&&i<neex;i++) { if (*(hay_pixel+hayx*(y+i)+x+i) != *(nee_pixel+neex*i+i)) { return false; } } for(int _y=0;_y<neey;_y++) { for(int _x=0;_x<neex;_x++) { if (*(hay_pixel+hayx*(y+_y)+x+_x) != *(nee_pixel+neex*_y+_x)) { return false; } } } return true; } void img_search(std::vector<std::pair<int,int> >& res,Image& haystack, Image& needle) { int hayx=haystack.columns(),hayy=haystack.rows(); haystack.modifyImage(); haystack.type(TrueColorType); const PixelPacket *hay_pixel=haystack.getConstPixels(0,0,hayx,hayy); int neex=needle.columns(),neey=needle.rows(); needle.modifyImage(); needle.type(TrueColorType); const PixelPacket *nee_pixel=needle.getConstPixels(0,0,neex,neey); for(int y=0;y<hayy-neey;y++) { for(int x=0;x<hayx-neex;x++) { if (ishere(hayx,neex,neey,x,y,hay_pixel,nee_pixel)) { res.push_back(std::pair<int,int>(x,y)); } } } } /* * g++ -o image_helper -O3 -Wall `pkg-config --cflags --libs Magick++` image_helper.cc */ int main(int argc,char** argv) { Image i1(argv[1]); Image i2(argv[2]); std::vector<std::pair<int,int> > r; img_search(r,i1,i2); for(unsigned i=0;i<r.size();i++) { printf("%i %i\n",r[i].first,r[i].second); } return 0; } <commit_msg>image_helper<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "image_helper.hh" bool ishere(int hayx,int neex,int neey,int x,int y, const PixelPacket *hay_pixel, const PixelPacket *nee_pixel) { // Check diagonal first. Seems to speed up things. for(int i=0;i<neey&&i<neex;i++) { if (*(hay_pixel+hayx*(y+i)+x+i) != *(nee_pixel+neex*i+i)) { return false; } } for(int _y=0;_y<neey;_y++) { for(int _x=0;_x<neex;_x++) { if (*(hay_pixel+hayx*(y+_y)+x+_x) != *(nee_pixel+neex*_y+_x)) { return false; } } } return true; } void img_search(std::vector<std::pair<int,int> >& res,Image& haystack, Image& needle) { int hayx=haystack.columns(),hayy=haystack.rows(); haystack.modifyImage(); haystack.type(TrueColorType); const PixelPacket *hay_pixel=haystack.getConstPixels(0,0,hayx,hayy); int neex=needle.columns(),neey=needle.rows(); needle.modifyImage(); needle.type(TrueColorType); const PixelPacket *nee_pixel=needle.getConstPixels(0,0,neex,neey); for(int y=0;y<hayy-neey;y++) { for(int x=0;x<hayx-neex;x++) { if (ishere(hayx,neex,neey,x,y,hay_pixel,nee_pixel)) { res.push_back(std::pair<int,int>(x,y)); } } } } /* * g++ -o image_helper -O3 -Wall `pkg-config --cflags --libs Magick++` image_helper.cc * image_helper x:'root' x:'root[300x400+879+122]' * If you are lucky, it will print you "879 122" */ #ifdef IMAGE_HELPER_MAIN int main(int argc,char** argv) { Image i1(argv[1]); Image i2(argv[2]); std::vector<std::pair<int,int> > r; img_search(r,i1,i2); for(unsigned i=0;i<r.size();i++) { printf("%i %i\n",r[i].first,r[i].second); } return 0; } #endif <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliMUONTracker.h" #include "AliMUONTrackReconstructorK.h" #include "AliMUONTrackReconstructor.h" #include "AliMUONRecData.h" #include "AliLog.h" //_____________________________________________________________________________ AliMUONTracker::AliMUONTracker() : AliTracker(), fTriggerCircuit(0x0), fMUONData(0x0), fTrackReco(0x0) { /// constructor } //_____________________________________________________________________________ AliMUONTracker::~AliMUONTracker() { /// dtr delete fTrackReco; } //_____________________________________________________________________________ void AliMUONTracker::SetOption(Option_t* option) { /// set reconstructor class if (!fMUONData) AliError("MUONData not defined"); if (!fTriggerCircuit) AliError("TriggerCircuit not defined"); if (strstr(option,"Original")) fTrackReco = new AliMUONTrackReconstructor(fMUONData); else if (strstr(option,"Combi")) fTrackReco = new AliMUONTrackReconstructorK(fMUONData,"Combi"); else fTrackReco = new AliMUONTrackReconstructorK(fMUONData,"Kalman"); fTrackReco->SetTriggerCircuit(fTriggerCircuit); } //_____________________________________________________________________________ Int_t AliMUONTracker::Clusters2Tracks(AliESD* /*esd*/) { /// clusters2Tracks method /// in general tracking framework // open TClonesArray for reading fMUONData->SetTreeAddress("TC,RC"); // open for writing // trigger branch fMUONData->MakeBranch("RL"); //trigger track fMUONData->SetTreeAddress("RL"); fTrackReco->EventReconstructTrigger(); fMUONData->Fill("RL"); // tracking branch fMUONData->MakeBranch("RT"); //track fMUONData->SetTreeAddress("RT"); fTrackReco->EventReconstruct(); fMUONData->Fill("RT"); fMUONData->ResetRecTracks(); fMUONData->ResetRecTriggerTracks(); return kTRUE; } <commit_msg>Adding class description (Christian)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /// \class AliMUONTracker /// Interface class for use of global tracking framework; /// reconstruct tracks from recpoints /// /// \author Christian Finck, SUBATECH Nantes #include "AliMUONTracker.h" #include "AliMUONTrackReconstructorK.h" #include "AliMUONTrackReconstructor.h" #include "AliMUONRecData.h" #include "AliLog.h" //_____________________________________________________________________________ AliMUONTracker::AliMUONTracker() : AliTracker(), fTriggerCircuit(0x0), fMUONData(0x0), fTrackReco(0x0) { /// constructor } //_____________________________________________________________________________ AliMUONTracker::~AliMUONTracker() { /// dtr delete fTrackReco; } //_____________________________________________________________________________ void AliMUONTracker::SetOption(Option_t* option) { /// set reconstructor class if (!fMUONData) AliError("MUONData not defined"); if (!fTriggerCircuit) AliError("TriggerCircuit not defined"); if (strstr(option,"Original")) fTrackReco = new AliMUONTrackReconstructor(fMUONData); else if (strstr(option,"Combi")) fTrackReco = new AliMUONTrackReconstructorK(fMUONData,"Combi"); else fTrackReco = new AliMUONTrackReconstructorK(fMUONData,"Kalman"); fTrackReco->SetTriggerCircuit(fTriggerCircuit); } //_____________________________________________________________________________ Int_t AliMUONTracker::Clusters2Tracks(AliESD* /*esd*/) { /// clusters2Tracks method /// in general tracking framework // open TClonesArray for reading fMUONData->SetTreeAddress("TC,RC"); // open for writing // trigger branch fMUONData->MakeBranch("RL"); //trigger track fMUONData->SetTreeAddress("RL"); fTrackReco->EventReconstructTrigger(); fMUONData->Fill("RL"); // tracking branch fMUONData->MakeBranch("RT"); //track fMUONData->SetTreeAddress("RT"); fTrackReco->EventReconstruct(); fMUONData->Fill("RT"); fMUONData->ResetRecTracks(); fMUONData->ResetRecTriggerTracks(); return kTRUE; } <|endoftext|>
<commit_before>#include <iostream> #include "process_curve.h" #include "init_curves.h" #include "spline.h" #define BORDER 100 using namespace std; // Resolution: the number of discrete line segments in each curve. // numPoints: the number of points to plot; number of splines is // thus numPoints - 2. // numSets: the number of spline curve sets to calculate. int resolution, numPoints, numSets; // Keep track of largest/smallest x/y vals float hix = -10000.0, lox = 10000.0, hiy = -10000.0, loy = 10000.0; float normx = 1, normy = 1; Point** finVals; Point** sets; void Splines::init() { cin >> resolution >> numPoints >> numSets; sets = new Point*[numSets]; for (int set = 0; set < numSets; set++) { sets[set] = new Point[numPoints]; for (int point = 0; point < numPoints; point++) { float x, y; cin >> x >> y; if (x > hix) { hix = x; } if (x < lox) { lox = x; } if (y > hiy) { hiy = y; } if (y < loy) { loy = y; } sets[set][point].x = x; sets[set][point].y = y; } } } void Splines::transform(int n, int e, int s, int w) { normx = (1 - e) / (lox - hix); normy = (1 - s) / (loy - hiy); float offx = ((1 - e) * -lox) / (lox - hix); float offy = ((1 - s) * -loy) / (loy - hiy); for (int set = 0; set < numSets; set++) { for (int point = 0; point < numPoints; point++) { sets[set][point].x = sets[set][point].x * normx + offx; sets[set][point].y = sets[set][point].y * normy + offy; } } } void Splines::generate() { finVals = generatePoints(sets, numSets, numPoints, resolution); } void Splines::iterate( void (*process)(int setNum, int numPoints, int resolution, Point* vals)) { for (int set = 0; set < numSets; set++) { process(set, numPoints, resolution, finVals[set]); } } void Splines::cleanup() { for (int set = 0; set < numSets; set++) { delete [] sets[set]; } delete []sets; } <commit_msg>Add printout to indicate what values should be passed in<commit_after>#include <iostream> #include "process_curve.h" #include "init_curves.h" #include "spline.h" #define BORDER 100 using namespace std; // Resolution: the number of discrete line segments in each curve. // numPoints: the number of points to plot; number of splines is // thus numPoints - 2. // numSets: the number of spline curve sets to calculate. int resolution, numPoints, numSets; // Keep track of largest/smallest x/y vals float hix = -10000.0, lox = 10000.0, hiy = -10000.0, loy = 10000.0; float normx = 1, normy = 1; Point** finVals; Point** sets; void Splines::init() { cout << "Enter [resolution numPoints numSets] followed by " << endl; cout << "data points, one per line: "; cin >> resolution >> numPoints >> numSets; sets = new Point*[numSets]; for (int set = 0; set < numSets; set++) { sets[set] = new Point[numPoints]; for (int point = 0; point < numPoints; point++) { float x, y; cin >> x >> y; if (x > hix) { hix = x; } if (x < lox) { lox = x; } if (y > hiy) { hiy = y; } if (y < loy) { loy = y; } sets[set][point].x = x; sets[set][point].y = y; } } } void Splines::transform(int n, int e, int s, int w) { normx = (1 - e) / (lox - hix); normy = (1 - s) / (loy - hiy); float offx = ((1 - e) * -lox) / (lox - hix); float offy = ((1 - s) * -loy) / (loy - hiy); for (int set = 0; set < numSets; set++) { for (int point = 0; point < numPoints; point++) { sets[set][point].x = sets[set][point].x * normx + offx; sets[set][point].y = sets[set][point].y * normy + offy; } } } void Splines::generate() { finVals = generatePoints(sets, numSets, numPoints, resolution); } void Splines::iterate( void (*process)(int setNum, int numPoints, int resolution, Point* vals)) { for (int set = 0; set < numSets; set++) { process(set, numPoints, resolution, finVals[set]); } } void Splines::cleanup() { for (int set = 0; set < numSets; set++) { delete [] sets[set]; } delete []sets; } <|endoftext|>
<commit_before>// // inpal_prime.cpp // InversePalindrome // // Created by Bryan Triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpal_prime.hpp" #include <cmath> #include <vector> #include <string> #include <algorithm> std::vector<std::size_t> inpal::prime::prime_list(std::size_t range) { auto primes = prime_sieve(range); std::vector<std::size_t> p_list; for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i); return p_list; } std::vector<std::size_t> inpal::prime::factor_list(std::size_t num) { std::vector<std::size_t> p_fac; std::size_t prime_factor = 2; //trial division while(prime_factor<=num) { while(num%prime_factor==0) { p_fac.push_back(prime_factor); num=num/prime_factor; } prime_factor += prime_factor==2 ? 1 : 2; } return p_fac; } std::size_t inpal::prime::prime_count(std::size_t range) { auto primes = prime_sieve(range); return std::count(primes.begin(), primes.end(), true); } std::size_t inpal::prime::max_prime(std::size_t num) { auto primes = prime_sieve(num); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } double inpal::prime::prime_density(double range) { return prime_count(range)/range; } bool inpal::prime::prime_test(std::size_t num) { return num == max_prime(num); } bool inpal::prime::twin_test(std::size_t num) { auto primes = prime_sieve(num+2); return num!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]); } bool inpal::prime::cousin_test(std::size_t num) { auto primes = prime_sieve(num+4); return num!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]); } bool inpal::prime::sexy_test(std::size_t num) { auto primes = prime_sieve(num+6); return (num!=2 && num!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]); } std::size_t inpal::prime::max_palprime(std::size_t num) { auto primes = prime_sieve(num); for(std::size_t i=num; i>=2; --i) if(primes[i] && pal_test(i)) return i; return 2; } std::size_t inpal::prime::max_factor(std::size_t num) { return factor_list(num).back(); } std::size_t inpal::prime::factor_count(std::size_t num) { return factor_list(num).size(); } std::vector<bool> inpal::prime::prime_sieve(std::size_t range) { std::vector<bool> p_test(range+1, false); //defines square root of range for future usage std::size_t root = ceil(sqrt(range)); //sieve axioms for(std::size_t x=1; x<=root; x++) for(std::size_t y=1; y<=root; y++) { std::size_t i = (4*x*x)+(y*y); if (i<=range && (i%12==1 || i%12==5)) { p_test[i].flip(); } i = (3*x*x)+(y*y); if(i<=range && i%12==7) { p_test[i].flip(); } i = (3*x*x)-(y*y); if(x>y && i<=range && i%12==11) { p_test[i].flip(); } } //marks 2,3,5 and 7 as prime numbers to deal with input smaller than 7 p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(std::size_t r=5; r<=root; r++) { if((p_test[r])) { for(std::size_t j=r*r; j<=range; j+=r*r) { p_test[j]=false; } } } return p_test; } bool inpal::prime::pal_test(std::size_t num) { std::string rev = std::to_string(num); //checks if half the reverse of rev is equal to the other half of rev if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin())) { return true; } return false; } <commit_msg>Update inpal_prime.cpp<commit_after>// // inpal_prime.cpp // InversePalindrome // // Created by Bryan Triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpal_prime.hpp" #include <cmath> #include <vector> #include <string> #include <algorithm> std::vector<std::size_t> inpal::prime::prime_list(std::size_t range) { auto primes = prime_sieve(range); std::vector<std::size_t> p_list; for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i); return p_list; } std::vector<std::size_t> inpal::prime::factor_list(std::size_t num) { std::vector<std::size_t> p_fac; std::size_t prime_factor = 2; //trial division while(prime_factor<=num) { while(num%prime_factor==0) { p_fac.push_back(prime_factor); num=num/prime_factor; } prime_factor += prime_factor==2 ? 1 : 2; } return p_fac; } std::size_t inpal::prime::max_prime(std::size_t num) { auto primes = prime_sieve(num); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } std::size_t inpal::prime::prime_count(std::size_t range) { auto primes = prime_sieve(range); return std::count(primes.begin(), primes.end(), true); } double inpal::prime::prime_density(double range) { return prime_count(range)/range; } bool inpal::prime::prime_test(std::size_t num) { return num == max_prime(num); } bool inpal::prime::twin_test(std::size_t num) { auto primes = prime_sieve(num+2); return num!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]); } bool inpal::prime::cousin_test(std::size_t num) { auto primes = prime_sieve(num+4); return num!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]); } bool inpal::prime::sexy_test(std::size_t num) { auto primes = prime_sieve(num+6); return (num!=2 && num!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]); } std::size_t inpal::prime::max_palprime(std::size_t num) { auto primes = prime_sieve(num); for(std::size_t i=num; i>=2; --i) if(primes[i] && pal_test(i)) return i; return 2; } std::size_t inpal::prime::max_factor(std::size_t num) { return factor_list(num).back(); } std::size_t inpal::prime::factor_count(std::size_t num) { return factor_list(num).size(); } std::vector<bool> inpal::prime::prime_sieve(std::size_t range) { std::vector<bool> p_test(range+1, false); //defines square root of range for future usage std::size_t root = ceil(sqrt(range)); //sieve axioms for(std::size_t x=1; x<=root; x++) for(std::size_t y=1; y<=root; y++) { std::size_t i = (4*x*x)+(y*y); if (i<=range && (i%12==1 || i%12==5)) { p_test[i].flip(); } i = (3*x*x)+(y*y); if(i<=range && i%12==7) { p_test[i].flip(); } i = (3*x*x)-(y*y); if(x>y && i<=range && i%12==11) { p_test[i].flip(); } } //marks 2,3,5 and 7 as prime numbers to deal with input smaller than 7 p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(std::size_t r=5; r<=root; r++) { if((p_test[r])) { for(std::size_t j=r*r; j<=range; j+=r*r) { p_test[j]=false; } } } return p_test; } bool inpal::prime::pal_test(std::size_t num) { std::string rev = std::to_string(num); //checks if half the reverse of rev is equal to the other half of rev if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin())) { return true; } return false; } <|endoftext|>
<commit_before>// // inpal_prime.cpp // Inverse Palindrome Library // // Created by Bryan Triana on 7/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpal_prime.hpp" #include "inpal_algorithm.hpp" std::vector<std::size_t> inpal::prime::prime_list(std::size_t range) { const auto primes = prime_sieve(range); std::vector<std::size_t> p_list; for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i); return p_list; } std::vector<bool> inpal::prime::prime_sieve(std::size_t range) { std::vector<bool> p_test(range+1, false); //defines square root of range for future usage const std::size_t root = ceil(sqrt(range)); //sieve axioms for(std::size_t x=1; x<=root; x++) for(std::size_t y=1; y<=root; y++) { std::size_t i = (4*x*x)+(y*y); if (i<=range && (i%12==1 || i%12==5)) { p_test[i].flip(); } i = (3*x*x)+(y*y); if(i<=range && i%12==7) { p_test[i].flip(); } i = (3*x*x)-(y*y); if(x>y && i<=range && i%12==11) { p_test[i].flip(); } } //marks 2,3,5 and 7 as prime numbers to deal with input smaller than 7 p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(std::size_t r=5; r<=root; r++) { if((p_test[r])) { for(std::size_t j=r*r; j<=range; j+=r*r) { p_test[j]=false; } } } return p_test; } std::vector<std::size_t> inpal::prime::factor_list(std::size_t num) { if(num<100000) { return algorithm::trial_division(num); } std::vector<std::size_t> factors; std::vector<std::size_t> primes; std::size_t factor = algorithm::pollard_rho(num); factors.push_back(num/factor); factors.push_back(factor); do { std::size_t m = factors.back(); factors.pop_back(); if(m==1) continue; if(prime_test(m)) { primes.push_back(m); //decomposes the factors into primes for(std::size_t i=0; i<factors.size(); i++) { std::size_t k = factors[i]; if(k%m==0) { do k/=m; while(k%m==0); factors[i]=k; } } } else { factor=algorithm::pollard_rho(m); factors.push_back(m/factor); factors.push_back(factor); } } while(!factors.empty()); return primes; } std::size_t inpal::prime::prime_locate(std::size_t pos) { //index starts at 1 instead of 0, eg 1st prime is 2 pos = pos-1; //return values for input less or equal to 10 const auto small_primes = prime_list(29); if(pos<10) return small_primes[pos]; //denotes the limit of the sieve std::size_t limit = pos*log(pos)+pos*log(log(pos)); const auto primes = prime_list(limit); return primes[pos]; } std::size_t inpal::prime::max_prime(std::size_t num) { const auto primes = prime_sieve(num); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } std::size_t inpal::prime::prime_count(std::size_t range) { const auto primes = prime_sieve(range); return std::count(primes.begin(), primes.end(), true); } double inpal::prime::prime_density(double range) { return prime_count(range)/range; } bool inpal::prime::prime_test(std::size_t num) { if(num!=2 && num%2==0) return false; const std::size_t iteration = 20; std::size_t s = num-1; while(s%2==0) s/=2; for(std::size_t i=0; i<iteration; i++) { std::size_t a = rand()%(num-1)+1; std::size_t b = s; std::size_t mod = algorithm::modulo(a,b,num); while(b!=num-1 && mod!=1 && mod!=num-1) { mod=algorithm::mulmod(mod,mod,num); b*=2; } if(mod!=num-1 && b%2==0) return false; } return true; } bool inpal::prime::twin_test(std::size_t num) { return prime_test(num) && (prime_test(num-2) || prime_test(num+2)); } bool inpal::prime::cousin_test(std::size_t num) { return prime_test(num) && (prime_test(num-4) || prime_test(num+4)); } bool inpal::prime::sexy_test(std::size_t num) { return num!=3 && prime_test(num) && (prime_test(num-6) || prime_test(num+6)); } std::size_t inpal::prime::max_palprime(std::size_t num) { const auto primes = prime_sieve(num); for(std::size_t i=num; i>=2; --i) if(primes[i] && algorithm::pal_test(i)) return i; return 2; } std::size_t inpal::prime::max_factor(std::size_t num) { return factor_list(num).back(); } std::size_t inpal::prime::factor_count(std::size_t num) { return factor_list(num).size(); } <commit_msg>Update inpal_prime.cpp<commit_after>// // inpal_prime.cpp // Inverse Palindrome Library // // Created by Bryan Triana on 7/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpal_prime.hpp" #include "inpal_algorithm.hpp" std::vector<std::size_t> inpal::prime::prime_list(std::size_t range) { const auto primes = prime_sieve(range); std::vector<std::size_t> p_list; for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i); return p_list; } std::vector<bool> inpal::prime::prime_sieve(std::size_t range) { std::vector<bool> p_test(range+1, false); //defines square root of range for future usage const std::size_t root = ceil(sqrt(range)); //sieve axioms for(std::size_t x=1; x<=root; x++) for(std::size_t y=1; y<=root; y++) { std::size_t i = (4*x*x)+(y*y); if (i<=range && (i%12==1 || i%12==5)) { p_test[i].flip(); } i = (3*x*x)+(y*y); if(i<=range && i%12==7) { p_test[i].flip(); } i = (3*x*x)-(y*y); if(x>y && i<=range && i%12==11) { p_test[i].flip(); } } //marks 2,3,5 and 7 as prime numbers to deal with input smaller than 7 p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(std::size_t r=5; r<=root; r++) { if((p_test[r])) { for(std::size_t j=r*r; j<=range; j+=r*r) { p_test[j]=false; } } } return p_test; } std::vector<std::size_t> inpal::prime::factor_list(std::size_t num) { std::vector<std::size_t> factors; std::vector<std::size_t> primes; std::size_t factor = algorithm::pollard_rho(num); factors.push_back(num/factor); factors.push_back(factor); do { std::size_t m = factors.back(); factors.pop_back(); if(m==1) continue; if(prime_test(m)) { primes.push_back(m); //decomposes the factors into primes for(std::size_t i=0; i<factors.size(); i++) { std::size_t k = factors[i]; if(k%m==0) { do k/=m; while(k%m==0); factors[i]=k; } } } else { factor=algorithm::pollard_rho(m); factors.push_back(m/factor); factors.push_back(factor); } } while(!factors.empty()); std::sort(primes.begin(), primes.end()); return primes; } std::size_t inpal::prime::prime_locate(std::size_t pos) { //index starts at 1 instead of 0, eg 1st prime is 2 pos = pos-1; //return values for input less or equal to 10 const auto small_primes = prime_list(29); if(pos<10) return small_primes[pos]; //denotes the limit of the sieve std::size_t limit = pos*log(pos)+pos*log(log(pos)); const auto primes = prime_list(limit); return primes[pos]; } std::size_t inpal::prime::max_prime(std::size_t num) { const auto primes = prime_sieve(num); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } std::size_t inpal::prime::prime_count(std::size_t range) { const auto primes = prime_sieve(range); return std::count(primes.begin(), primes.end(), true); } double inpal::prime::prime_density(double range) { return prime_count(range)/range; } bool inpal::prime::prime_test(std::size_t num) { if(num!=2 && num%2==0) return false; const std::size_t iteration = 20; std::size_t s = num-1; while(s%2==0) s/=2; for(std::size_t i=0; i<iteration; i++) { std::size_t a = rand()%(num-1)+1; std::size_t b = s; std::size_t mod = algorithm::modulo(a,b,num); while(b!=num-1 && mod!=1 && mod!=num-1) { mod=algorithm::mulmod(mod,mod,num); b*=2; } if(mod!=num-1 && b%2==0) return false; } return true; } bool inpal::prime::twin_test(std::size_t num) { return prime_test(num) && (prime_test(num-2) || prime_test(num+2)); } bool inpal::prime::cousin_test(std::size_t num) { return prime_test(num) && (prime_test(num-4) || prime_test(num+4)); } bool inpal::prime::sexy_test(std::size_t num) { return num!=3 && prime_test(num) && (prime_test(num-6) || prime_test(num+6)); } std::size_t inpal::prime::max_palprime(std::size_t num) { const auto primes = prime_sieve(num); for(std::size_t i=num; i>=2; --i) if(primes[i] && algorithm::pal_test(i)) return i; return 2; } std::size_t inpal::prime::max_factor(std::size_t num) { return factor_list(num).back(); } std::size_t inpal::prime::factor_count(std::size_t num) { return factor_list(num).size(); } <|endoftext|>
<commit_before>#include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <mist/defines.h> #include "input.h" #include <sstream> #include <fstream> #include <iterator> namespace Mist { Input * Input::singleton = NULL; void Input::userCallback(char * data, size_t len, unsigned int id){ for (int i = 0; i < 5; i++){ long tid = ((long)(data[0]) << 24) | ((long)(data[1]) << 16) | ((long)(data[2]) << 8) | ((long)(data[3])); if (tid){ long keyNum = ((long)(data[4]) << 8) | ((long)(data[5])); bufferFrame(tid, keyNum + 1);//Try buffer next frame } } } void Input::doNothing(char * data, size_t len, unsigned int id){ DEBUG_MSG(DLVL_DONTEVEN, "Doing 'nothing'"); singleton->userCallback(data, 30, id);//call the userCallback for this input } Input::Input(Util::Config * cfg) { config = cfg; JSON::Value option; option["long"] = "json"; option["short"] = "j"; option["help"] = "Output MistIn info in JSON format, then exit."; option["value"].append(0ll); config->addOption("json", option); option.null(); option["arg_num"] = 1ll; option["arg"] = "string"; option["help"] = "Name of the input file or - for stdin"; option["value"].append("-"); config->addOption("input", option); option.null(); option["arg_num"] = 2ll; option["arg"] = "string"; option["help"] = "Name of the output file or - for stdout"; option["value"].append("-"); config->addOption("output", option); option.null(); option["arg"] = "string"; option["short"] = "s"; option["long"] = "stream"; option["help"] = "The name of the stream that this connector will transmit."; config->addOption("streamname", option); option.null(); option["short"] = "p"; option["long"] = "player"; option["help"] = "Makes this connector into a player"; config->addOption("player", option); packTime = 0; lastActive = Util::epoch(); playing = 0; playUntil = 0; singleton = this; isBuffer = false; } void Input::checkHeaderTimes(std::string streamFile){ std::string headerFile = streamFile + ".dtsh"; FILE * tmp = fopen(headerFile.c_str(),"r"); if (tmp == NULL) { INFO_MSG("can't open file: %s (no header times compared, nothing removed)", headerFile.c_str() ); return; } struct stat bufStream; struct stat bufHeader; //fstat(fileno(streamFile), &bufStream); //fstat(fileno(tmp), &bufHeader); if (stat(streamFile.c_str(), &bufStream) !=0 || stat(headerFile.c_str(), &bufHeader) !=0){ ERROR_MSG("could not get file info (no header times compared, nothing removed)"); fclose(tmp); return; } int timeStream = bufStream.st_mtime; int timeHeader = bufHeader.st_mtime; fclose(tmp); INFO_MSG("time header: %i time stream: %i ", timeHeader, timeStream); if (timeHeader < timeStream) { INFO_MSG("removing old header file: %s ",headerFile.c_str()); //delete filename remove(headerFile.c_str()); } } int Input::run() { if (config->getBool("json")) { std::cerr << capa.toString() << std::endl; return 0; } if (!setup()) { std::cerr << config->getString("cmd") << " setup failed." << std::endl; return 0; } checkHeaderTimes(config->getString("input")); if (!readHeader()) { std::cerr << "Reading header for " << config->getString("input") << " failed." << std::endl; return 0; } parseHeader(); if (!config->getBool("player")){ //check filename for no - if (config->getString("output") != "-"){ std::string filename = config->getString("output"); if (filename.size() < 5 || filename.substr(filename.size() - 5) != ".dtsc"){ filename += ".dtsc"; } //output to dtsc DTSC::Meta newMeta = myMeta; newMeta.reset(); JSON::Value tempVal; std::ofstream file(filename.c_str()); long long int bpos = 0; seek(0); getNext(); while (lastPack){ tempVal = lastPack.toJSON(); tempVal["bpos"] = bpos; newMeta.update(tempVal); file << std::string(lastPack.getData(), lastPack.getDataLen()); bpos += lastPack.getDataLen(); getNext(); } //close file file.close(); //create header file.open((filename+".dtsh").c_str()); file << newMeta.toJSON().toNetPacked(); file.close(); }else{ DEBUG_MSG(DLVL_FAIL,"No filename specified, exiting"); } }else{ //after this player functionality #ifdef __CYGWIN__ metaPage.init(config->getString("streamname"), 8 * 1024 * 1024, true); #else metaPage.init(config->getString("streamname"), (isBuffer ? 8 * 1024 * 1024 : myMeta.getSendLen()), true); #endif myMeta.writeTo(metaPage.mapped); userPage.init(config->getString("streamname") + "_users", 30, true); if (!isBuffer){ for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ bufferFrame(it->first, 1); } } IPC::semaphore waiting(std::string("/wait_" + config->getString("streamname")).c_str(), O_CREAT | O_RDWR, ACCESSPERMS, 0); if (!waiting){ DEBUG_MSG(DLVL_FAIL, "Failed to open semaphore - cancelling"); return -1; } waiting.post(); waiting.close(); DEBUG_MSG(DLVL_HIGH,"Pre-While"); long long int activityCounter = Util::getMS(); while ((Util::getMS() - activityCounter) < 10000){//10 second timeout DEBUG_MSG(DLVL_HIGH, "Timer running"); Util::sleep(1000); removeUnused(); userPage.parseEach(doNothing); if (userPage.amount){ activityCounter = Util::getMS(); DEBUG_MSG(DLVL_HIGH, "Connected users: %d", userPage.amount); } } DEBUG_MSG(DLVL_DEVEL,"Closing clean"); //end player functionality } return 0; } void Input::removeUnused(){ for (std::map<unsigned int, std::map<unsigned int, unsigned int> >::iterator it = pageCounter.begin(); it != pageCounter.end(); it++){ for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ it2->second--; } bool change = true; while (change){ change = false; for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ if (!it2->second){ dataPages[it->first].erase(it2->first); pageCounter[it->first].erase(it2->first); change = true; break; } } } } } void Input::parseHeader(){ DEBUG_MSG(DLVL_DEVEL,"Parsing the header"); //Select all tracks for parsing header selectedTracks.clear(); std::stringstream trackSpec; for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { DEBUG_MSG(DLVL_VERYHIGH, "Track %d encountered", it->first); if (trackSpec.str() != ""){ trackSpec << " "; } trackSpec << it->first; DEBUG_MSG(DLVL_VERYHIGH, "Trackspec now %s", trackSpec.str().c_str()); for (std::deque<DTSC::Key>::iterator it2 = it->second.keys.begin(); it2 != it->second.keys.end(); it2++){ keyTimes[it->first].insert(it2->getTime()); } } trackSelect(trackSpec.str()); std::map<int, DTSCPageData> curData; std::map<int, booking> bookKeeping; seek(0); getNext(); while(lastPack){//loop through all int tid = lastPack.getTrackId(); if (!tid){ getNext(false); continue; } if (!bookKeeping.count(tid)){ bookKeeping[tid].first = 1; bookKeeping[tid].curPart = 0; bookKeeping[tid].curKey = 0; curData[tid].lastKeyTime = 0xFFFFFFFF; curData[tid].keyNum = 1; curData[tid].partNum = 0; curData[tid].dataSize = 0; curData[tid].curOffset = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[0].getTime(); char tmpId[20]; sprintf(tmpId, "%d", tid); indexPages[tid].init(config->getString("streamname") + tmpId, 8 * 1024, true);//Pages of 8kb in size, room for 512 parts. } if (myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getParts() == curData[tid].partNum){ if (curData[tid].dataSize > 8 * 1024 * 1024) { pagesByTrack[tid][bookKeeping[tid].first] = curData[tid]; bookKeeping[tid].first += curData[tid].keyNum; curData[tid].keyNum = 0; curData[tid].dataSize = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getTime(); } bookKeeping[tid].curKey++; curData[tid].keyNum++; curData[tid].partNum = 0; } curData[tid].dataSize += lastPack.getDataLen(); curData[tid].partNum ++; bookKeeping[tid].curPart ++; getNext(false); } for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { if (curData.count(it->first) && !pagesByTrack[it->first].count(bookKeeping[it->first].first)){ pagesByTrack[it->first][bookKeeping[it->first].first] = curData[it->first]; } if (!pagesByTrack.count(it->first)){ DEBUG_MSG(DLVL_WARN, "No pages for track %d found", it->first); }else{ DEBUG_MSG(DLVL_DEVEL, "Track %d (%s) split into %lu pages", it->first, myMeta.tracks[it->first].codec.c_str(), pagesByTrack[it->first].size()); for (std::map<int, DTSCPageData>::iterator it2 = pagesByTrack[it->first].begin(); it2 != pagesByTrack[it->first].end(); it2++){ DEBUG_MSG(DLVL_DEVEL, "Page %u-%u", it2->first, it2->first + it2->second.keyNum - 1); } } } } bool Input::bufferFrame(int track, int keyNum){ if (keyNum < 1){keyNum = 1;} if (!pagesByTrack.count(track)){ return false; } std::map<int, DTSCPageData>::iterator it = pagesByTrack[track].upper_bound(keyNum); if (it != pagesByTrack[track].begin()){ it--; } int pageNum = it->first; pageCounter[track][pageNum] = 15;///Keep page 15seconds in memory after last use DEBUG_MSG(DLVL_DONTEVEN, "Attempting to buffer page %d key %d->%d", track, keyNum, pageNum); if (dataPages[track].count(pageNum)){ return true; } char pageId[100]; int pageIdLen = sprintf(pageId, "%s%d_%d", config->getString("streamname").c_str(), track, pageNum); std::string tmpString(pageId, pageIdLen); #ifdef __CYGWIN__ dataPages[track][pageNum].init(tmpString, 26 * 1024 * 1024, true); #else dataPages[track][pageNum].init(tmpString, it->second.dataSize, true); #endif DEBUG_MSG(DLVL_DEVEL, "Buffering track %d page %d through %d", track, pageNum, pageNum-1 + it->second.keyNum); std::stringstream trackSpec; trackSpec << track; trackSelect(trackSpec.str()); seek(myMeta.tracks[track].keys[pageNum-1].getTime()); long long unsigned int stopTime = myMeta.tracks[track].lastms + 1; if ((int)myMeta.tracks[track].keys.size() > pageNum-1 + it->second.keyNum){ stopTime = myMeta.tracks[track].keys[pageNum-1 + it->second.keyNum].getTime(); } DEBUG_MSG(DLVL_HIGH, "Playing from %ld to %llu", myMeta.tracks[track].keys[pageNum-1].getTime(), stopTime); it->second.curOffset = 0; getNext(); //in case earlier seeking was inprecise, seek to the exact point while (lastPack && lastPack.getTime() < (unsigned long long)myMeta.tracks[track].keys[pageNum-1].getTime()){ getNext(); } while (lastPack && lastPack.getTime() < stopTime){ if (it->second.curOffset + lastPack.getDataLen() > pagesByTrack[track][pageNum].dataSize){ DEBUG_MSG(DLVL_WARN, "Trying to write %u bytes on pos %llu where size is %llu (time: %llu / %llu, track %u page %u)", lastPack.getDataLen(), it->second.curOffset, pagesByTrack[track][pageNum].dataSize, lastPack.getTime(), stopTime, track, pageNum); break; }else{ memcpy(dataPages[track][pageNum].mapped + it->second.curOffset, lastPack.getData(), lastPack.getDataLen()); it->second.curOffset += lastPack.getDataLen(); } getNext(); } for (int i = 0; i < indexPages[track].len / 8; i++){ if (((long long int*)indexPages[track].mapped)[i] == 0){ ((long long int*)indexPages[track].mapped)[i] = (((long long int)htonl(pageNum)) << 32) | htonl(it->second.keyNum); break; } } return true; } bool Input::atKeyFrame(){ static std::map<int, unsigned long long> lastSeen; //not in keyTimes? We're not at a keyframe. unsigned int c = keyTimes[lastPack.getTrackId()].count(lastPack.getTime()); if (!c){ return false; } //skip double times if (lastSeen.count(lastPack.getTrackId()) && lastSeen[lastPack.getTrackId()] == lastPack.getTime()){ return false; } //set last seen, and return true lastSeen[lastPack.getTrackId()] = lastPack.getTime(); return true; } void Input::play(int until) { playing = -1; playUntil = until; initialTime = 0; benchMark = Util::getMS(); } void Input::playOnce() { if (playing <= 0) { playing = 1; } ++playing; benchMark = Util::getMS(); } void Input::quitPlay() { playing = 0; } } <commit_msg>Fixed Erik's silly mistake. Oh Erik. :')<commit_after>#include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <mist/defines.h> #include "input.h" #include <sstream> #include <fstream> #include <iterator> namespace Mist { Input * Input::singleton = NULL; void Input::userCallback(char * data, size_t len, unsigned int id){ for (int i = 0; i < 5; i++){ long tid = ((long)(data[i*6]) << 24) | ((long)(data[i*6+1]) << 16) | ((long)(data[i*6+2]) << 8) | ((long)(data[i*6+3])); if (tid){ long keyNum = ((long)(data[i*6+4]) << 8) | ((long)(data[i*6+5])); bufferFrame(tid, keyNum + 1);//Try buffer next frame } } } void Input::doNothing(char * data, size_t len, unsigned int id){ DEBUG_MSG(DLVL_DONTEVEN, "Doing 'nothing'"); singleton->userCallback(data, 30, id);//call the userCallback for this input } Input::Input(Util::Config * cfg) { config = cfg; JSON::Value option; option["long"] = "json"; option["short"] = "j"; option["help"] = "Output MistIn info in JSON format, then exit."; option["value"].append(0ll); config->addOption("json", option); option.null(); option["arg_num"] = 1ll; option["arg"] = "string"; option["help"] = "Name of the input file or - for stdin"; option["value"].append("-"); config->addOption("input", option); option.null(); option["arg_num"] = 2ll; option["arg"] = "string"; option["help"] = "Name of the output file or - for stdout"; option["value"].append("-"); config->addOption("output", option); option.null(); option["arg"] = "string"; option["short"] = "s"; option["long"] = "stream"; option["help"] = "The name of the stream that this connector will transmit."; config->addOption("streamname", option); option.null(); option["short"] = "p"; option["long"] = "player"; option["help"] = "Makes this connector into a player"; config->addOption("player", option); packTime = 0; lastActive = Util::epoch(); playing = 0; playUntil = 0; singleton = this; isBuffer = false; } void Input::checkHeaderTimes(std::string streamFile){ std::string headerFile = streamFile + ".dtsh"; FILE * tmp = fopen(headerFile.c_str(),"r"); if (tmp == NULL) { INFO_MSG("can't open file: %s (no header times compared, nothing removed)", headerFile.c_str() ); return; } struct stat bufStream; struct stat bufHeader; //fstat(fileno(streamFile), &bufStream); //fstat(fileno(tmp), &bufHeader); if (stat(streamFile.c_str(), &bufStream) !=0 || stat(headerFile.c_str(), &bufHeader) !=0){ ERROR_MSG("could not get file info (no header times compared, nothing removed)"); fclose(tmp); return; } int timeStream = bufStream.st_mtime; int timeHeader = bufHeader.st_mtime; fclose(tmp); INFO_MSG("time header: %i time stream: %i ", timeHeader, timeStream); if (timeHeader < timeStream) { INFO_MSG("removing old header file: %s ",headerFile.c_str()); //delete filename remove(headerFile.c_str()); } } int Input::run() { if (config->getBool("json")) { std::cerr << capa.toString() << std::endl; return 0; } if (!setup()) { std::cerr << config->getString("cmd") << " setup failed." << std::endl; return 0; } checkHeaderTimes(config->getString("input")); if (!readHeader()) { std::cerr << "Reading header for " << config->getString("input") << " failed." << std::endl; return 0; } parseHeader(); if (!config->getBool("player")){ //check filename for no - if (config->getString("output") != "-"){ std::string filename = config->getString("output"); if (filename.size() < 5 || filename.substr(filename.size() - 5) != ".dtsc"){ filename += ".dtsc"; } //output to dtsc DTSC::Meta newMeta = myMeta; newMeta.reset(); JSON::Value tempVal; std::ofstream file(filename.c_str()); long long int bpos = 0; seek(0); getNext(); while (lastPack){ tempVal = lastPack.toJSON(); tempVal["bpos"] = bpos; newMeta.update(tempVal); file << std::string(lastPack.getData(), lastPack.getDataLen()); bpos += lastPack.getDataLen(); getNext(); } //close file file.close(); //create header file.open((filename+".dtsh").c_str()); file << newMeta.toJSON().toNetPacked(); file.close(); }else{ DEBUG_MSG(DLVL_FAIL,"No filename specified, exiting"); } }else{ //after this player functionality #ifdef __CYGWIN__ metaPage.init(config->getString("streamname"), 8 * 1024 * 1024, true); #else metaPage.init(config->getString("streamname"), (isBuffer ? 8 * 1024 * 1024 : myMeta.getSendLen()), true); #endif myMeta.writeTo(metaPage.mapped); userPage.init(config->getString("streamname") + "_users", 30, true); if (!isBuffer){ for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ bufferFrame(it->first, 1); } } IPC::semaphore waiting(std::string("/wait_" + config->getString("streamname")).c_str(), O_CREAT | O_RDWR, ACCESSPERMS, 0); if (!waiting){ DEBUG_MSG(DLVL_FAIL, "Failed to open semaphore - cancelling"); return -1; } waiting.post(); waiting.close(); DEBUG_MSG(DLVL_HIGH,"Pre-While"); long long int activityCounter = Util::getMS(); while ((Util::getMS() - activityCounter) < 10000){//10 second timeout DEBUG_MSG(DLVL_HIGH, "Timer running"); Util::sleep(1000); removeUnused(); userPage.parseEach(doNothing); if (userPage.amount){ activityCounter = Util::getMS(); DEBUG_MSG(DLVL_HIGH, "Connected users: %d", userPage.amount); } } DEBUG_MSG(DLVL_DEVEL,"Closing clean"); //end player functionality } return 0; } void Input::removeUnused(){ for (std::map<unsigned int, std::map<unsigned int, unsigned int> >::iterator it = pageCounter.begin(); it != pageCounter.end(); it++){ for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ it2->second--; } bool change = true; while (change){ change = false; for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ if (!it2->second){ dataPages[it->first].erase(it2->first); pageCounter[it->first].erase(it2->first); change = true; break; } } } } } void Input::parseHeader(){ DEBUG_MSG(DLVL_DEVEL,"Parsing the header"); //Select all tracks for parsing header selectedTracks.clear(); std::stringstream trackSpec; for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { DEBUG_MSG(DLVL_VERYHIGH, "Track %d encountered", it->first); if (trackSpec.str() != ""){ trackSpec << " "; } trackSpec << it->first; DEBUG_MSG(DLVL_VERYHIGH, "Trackspec now %s", trackSpec.str().c_str()); for (std::deque<DTSC::Key>::iterator it2 = it->second.keys.begin(); it2 != it->second.keys.end(); it2++){ keyTimes[it->first].insert(it2->getTime()); } } trackSelect(trackSpec.str()); std::map<int, DTSCPageData> curData; std::map<int, booking> bookKeeping; seek(0); getNext(); while(lastPack){//loop through all int tid = lastPack.getTrackId(); if (!tid){ getNext(false); continue; } if (!bookKeeping.count(tid)){ bookKeeping[tid].first = 1; bookKeeping[tid].curPart = 0; bookKeeping[tid].curKey = 0; curData[tid].lastKeyTime = 0xFFFFFFFF; curData[tid].keyNum = 1; curData[tid].partNum = 0; curData[tid].dataSize = 0; curData[tid].curOffset = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[0].getTime(); char tmpId[20]; sprintf(tmpId, "%d", tid); indexPages[tid].init(config->getString("streamname") + tmpId, 8 * 1024, true);//Pages of 8kb in size, room for 512 parts. } if (myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getParts() == curData[tid].partNum){ if (curData[tid].dataSize > 8 * 1024 * 1024) { pagesByTrack[tid][bookKeeping[tid].first] = curData[tid]; bookKeeping[tid].first += curData[tid].keyNum; curData[tid].keyNum = 0; curData[tid].dataSize = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getTime(); } bookKeeping[tid].curKey++; curData[tid].keyNum++; curData[tid].partNum = 0; } curData[tid].dataSize += lastPack.getDataLen(); curData[tid].partNum ++; bookKeeping[tid].curPart ++; getNext(false); } for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { if (curData.count(it->first) && !pagesByTrack[it->first].count(bookKeeping[it->first].first)){ pagesByTrack[it->first][bookKeeping[it->first].first] = curData[it->first]; } if (!pagesByTrack.count(it->first)){ DEBUG_MSG(DLVL_WARN, "No pages for track %d found", it->first); }else{ DEBUG_MSG(DLVL_DEVEL, "Track %d (%s) split into %lu pages", it->first, myMeta.tracks[it->first].codec.c_str(), pagesByTrack[it->first].size()); for (std::map<int, DTSCPageData>::iterator it2 = pagesByTrack[it->first].begin(); it2 != pagesByTrack[it->first].end(); it2++){ DEBUG_MSG(DLVL_DEVEL, "Page %u-%u", it2->first, it2->first + it2->second.keyNum - 1); } } } } bool Input::bufferFrame(int track, int keyNum){ if (keyNum < 1){keyNum = 1;} if (!pagesByTrack.count(track)){ return false; } std::map<int, DTSCPageData>::iterator it = pagesByTrack[track].upper_bound(keyNum); if (it != pagesByTrack[track].begin()){ it--; } int pageNum = it->first; pageCounter[track][pageNum] = 15;///Keep page 15seconds in memory after last use DEBUG_MSG(DLVL_DONTEVEN, "Attempting to buffer page %d key %d->%d", track, keyNum, pageNum); if (dataPages[track].count(pageNum)){ return true; } char pageId[100]; int pageIdLen = sprintf(pageId, "%s%d_%d", config->getString("streamname").c_str(), track, pageNum); std::string tmpString(pageId, pageIdLen); #ifdef __CYGWIN__ dataPages[track][pageNum].init(tmpString, 26 * 1024 * 1024, true); #else dataPages[track][pageNum].init(tmpString, it->second.dataSize, true); #endif DEBUG_MSG(DLVL_DEVEL, "Buffering track %d page %d through %d", track, pageNum, pageNum-1 + it->second.keyNum); std::stringstream trackSpec; trackSpec << track; trackSelect(trackSpec.str()); seek(myMeta.tracks[track].keys[pageNum-1].getTime()); long long unsigned int stopTime = myMeta.tracks[track].lastms + 1; if ((int)myMeta.tracks[track].keys.size() > pageNum-1 + it->second.keyNum){ stopTime = myMeta.tracks[track].keys[pageNum-1 + it->second.keyNum].getTime(); } DEBUG_MSG(DLVL_HIGH, "Playing from %ld to %llu", myMeta.tracks[track].keys[pageNum-1].getTime(), stopTime); it->second.curOffset = 0; getNext(); //in case earlier seeking was inprecise, seek to the exact point while (lastPack && lastPack.getTime() < (unsigned long long)myMeta.tracks[track].keys[pageNum-1].getTime()){ getNext(); } while (lastPack && lastPack.getTime() < stopTime){ if (it->second.curOffset + lastPack.getDataLen() > pagesByTrack[track][pageNum].dataSize){ DEBUG_MSG(DLVL_WARN, "Trying to write %u bytes on pos %llu where size is %llu (time: %llu / %llu, track %u page %u)", lastPack.getDataLen(), it->second.curOffset, pagesByTrack[track][pageNum].dataSize, lastPack.getTime(), stopTime, track, pageNum); break; }else{ memcpy(dataPages[track][pageNum].mapped + it->second.curOffset, lastPack.getData(), lastPack.getDataLen()); it->second.curOffset += lastPack.getDataLen(); } getNext(); } for (int i = 0; i < indexPages[track].len / 8; i++){ if (((long long int*)indexPages[track].mapped)[i] == 0){ ((long long int*)indexPages[track].mapped)[i] = (((long long int)htonl(pageNum)) << 32) | htonl(it->second.keyNum); break; } } return true; } bool Input::atKeyFrame(){ static std::map<int, unsigned long long> lastSeen; //not in keyTimes? We're not at a keyframe. unsigned int c = keyTimes[lastPack.getTrackId()].count(lastPack.getTime()); if (!c){ return false; } //skip double times if (lastSeen.count(lastPack.getTrackId()) && lastSeen[lastPack.getTrackId()] == lastPack.getTime()){ return false; } //set last seen, and return true lastSeen[lastPack.getTrackId()] = lastPack.getTime(); return true; } void Input::play(int until) { playing = -1; playUntil = until; initialTime = 0; benchMark = Util::getMS(); } void Input::playOnce() { if (playing <= 0) { playing = 1; } ++playing; benchMark = Util::getMS(); } void Input::quitPlay() { playing = 0; } } <|endoftext|>
<commit_before>#include <cstdlib> #include <cstdarg> #include <boost/asio.hpp> #include <boost/bind.hpp> #include "perf.hpp" #include "iproto.hpp" #include "iproto_conn.hpp" #define LOG_DEBUG 0 namespace IProto { int stderr_printf(char const* format, ...) { va_list args; va_start(args, format); int result = vfprintf(stderr, format, args); va_end(args); fprintf(stderr, "\n"); return result; } Conn::Conn(boost::asio::io_service &_io, const boost::asio::ip::tcp::endpoint &_ep, uint32_t _connect_timeout, uint32_t _read_timeout) : io(_io), ep(_ep), sock(_io), timer(_io), ping_timer(_io) { if( _read_timeout==0 ) _read_timeout=_connect_timeout; connect_timeout=_connect_timeout; read_timeout=_read_timeout; write_queue_len=0; write_is_active=ping_enabled=true; log_func = stderr_printf; } Conn::~Conn() { if( LOG_DEBUG ) log_func("[iproto_conn] destructor"); close(); dismissCallbacks(CB_ERR); } void Conn::close() { boost::system::error_code ec = boost::asio::error::interrupted; for(int i=0; i<3 && sock.is_open() && ec == boost::asio::error::interrupted; ++i) sock.close(ec); } void Conn::disablePing() { ping_enabled=false; ping_timer.cancel(); } void Conn::setupPing(const boost::system::error_code& error) { if( error || !ping_enabled ) return; if( !sock.is_open() ) beginConnect(); //Write a ping packet into socket static const IProto::Header hdr{0xff00, 0}; static const IProto::PacketPtr pkt{hdr}; Write(IProto::Packet(&pkt), boost::bind(&Conn::pingCb, shared_from_this(), _1) ); } void Conn::pingCb(RequestResult res) { if( unlikely(res.code != CB_OK) ) { //Reconnect log_func("[iproto_conn] ping failed, code %u", res.code); if( res.code == CB_TIMEOUT ) { reconnect(); return; } } ping_timer.expires_from_now( boost::posix_time::milliseconds(300) ); ping_timer.async_wait( boost::bind(&Conn::setupPing, shared_from_this(), boost::asio::placeholders::error) ); } bool Conn::checkConnect() { if( unlikely(!sock.is_open()) ) { beginConnect(); return true; } return false; } void Conn::beginConnect() { write_is_active=false; ping_timer.cancel(); //Limit connection time timer.expires_from_now( boost::posix_time::milliseconds(connect_timeout) ); timer.async_wait( boost::bind(&Conn::reconnectByTimer, shared_from_this(), boost::asio::placeholders::error) ); sock.async_connect( ep, boost::bind(&Conn::onConnect, shared_from_this(), boost::asio::placeholders::error) ); if( LOG_DEBUG ) log_func("[iproto_conn] Connecting to %s:%d", ep.address().to_string().c_str(), ep.port() ); } void Conn::reconnect() { close(); if( LOG_DEBUG ) log_func("[iproto_conn] reconnect"); beginConnect(); } void Conn::dismissCallbacks(CB_Result res) { if( LOG_DEBUG ) log_func("[iproto_conn] dismissCallbacks"); ping_timer.cancel(); for(auto it=callbacks_map.begin(); it!=callbacks_map.end(); ) { it = invokeCallback(it, RequestResult(res)); } callbacks_map.clear(); } void Conn::reconnectByTimer(const boost::system::error_code& error) { if( !error ) reconnect(); } void Conn::onConnect(const boost::system::error_code& error) { if( likely(!error) ) { if( LOG_DEBUG ) log_func("[iproto_conn] Connected"); timer.cancel(); setupReadHandler(); sock.set_option( boost::asio::ip::tcp::no_delay(true) ); if( ping_enabled ) setupPing( boost::system::error_code() ); else ensureWriteBuffer( boost::system::error_code() ); } } void Conn::setupReadHandler() { if( likely(!rd_buf || rd_buf->size()==0) ) rd_buf.reset(new boost::asio::streambuf); onRead( boost::system::error_code() ); } void Conn::onRead(const boost::system::error_code& error) { if( unlikely(error) ) { log_func("[iproto_conn] %s:%u: read error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() ); dismissCallbacks(CB_ERR); if( error != boost::asio::error::operation_aborted ) { beginConnect(); } return; } if( LOG_DEBUG ) log_func("[iproto_conn] onRead rd_buf->size=%zu", rd_buf->size()); while( rd_buf->size() >= sizeof(Header) ) { const PacketPtr *buf = boost::asio::buffer_cast< const PacketPtr * >( rd_buf->data() ); size_t want_read = sizeof(Header)+buf->hdr.len; if( want_read <= rd_buf->size() ) { invokeCallback(buf->hdr.sync, RequestResult(CB_OK, Packet(buf)) ); rd_buf->consume( sizeof(Header) + buf->hdr.len ); }else{ boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(want_read - rd_buf->size()), boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error) ); return; } } if( likely(sock.is_open()) ) boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(sizeof(Header)-rd_buf->size()), boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error) ); } void Conn::ensureWriteBuffer(const boost::system::error_code& error, const char *wr_buf) { if( unlikely(error) ) { log_func("[iproto_conn] %s:%u: write error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() ); if( error != boost::asio::error::operation_aborted ) { if( error == boost::asio::error::broken_pipe ) { //Packet was not completely transfered, we can do a retry write_queue.push_back( wr_buf ); write_queue_len++; wr_buf=nullptr;//Prevent free } beginConnect(); }else{ dismissCallbacks(CB_ERR); } if( likely(wr_buf != nullptr) ) ::free((void*)wr_buf); return; } if( likely(wr_buf != nullptr) ) ::free((void*)wr_buf); if( likely(write_queue_len>0 && (wr_buf || !write_is_active)) ) { const char *wr = write_queue.front(); write_queue.pop_front(); write_queue_len--; const Header *hdr = reinterpret_cast< const Header * >(wr); boost::asio::async_write(sock, boost::asio::buffer(wr, sizeof(*hdr)+hdr->len), boost::bind(&Conn::ensureWriteBuffer, shared_from_this(), boost::asio::placeholders::error, wr) ); if( LOG_DEBUG ) log_func("[iproto_conn] Write packet sync=%u len=%u", hdr->sync, hdr->len); write_is_active=true; } else write_is_active=false; } bool Conn::dropPacketWrite(Packet &&pkt) { write_queue.push_back( pkt.data ); pkt.data=nullptr; write_queue_len++; if( unlikely(checkConnect()) ) { log_func("[iproto_conn] dropPacketWrite deferred (no connect)"); return false; } ensureWriteBuffer( boost::system::error_code() ); return true; } bool Conn::Write(Packet &&pkt, callbacks_func_type &&cb) { auto timer = new boost::asio::deadline_timer(io); timer->expires_from_now( boost::posix_time::milliseconds(read_timeout) ); timer->async_wait( boost::bind(&Conn::onTimeout, shared_from_this(), boost::asio::placeholders::error, pkt.hdr.sync) ); callbacks_map[pkt.hdr.sync] = std::make_pair(timer, std::forward<callbacks_func_type>(cb)); return dropPacketWrite( std::forward<Packet>(pkt) ); } void Conn::Shutdown() { if( LOG_DEBUG ) log_func("[iproto_conn] Shutdown"); close(); dismissCallbacks(CB_ERR); } bool Conn::GentleShutdown() { if( LOG_DEBUG ) log_func("[iproto_conn] GentleShutdown"); if( callbacks_map.empty() && !write_is_active ) { Shutdown(); return true; } return false; } void Conn::onTimeout(const boost::system::error_code& error, uint32_t sync) { if( unlikely(!error) ) { if( LOG_DEBUG ) log_func("[iproto_conn] Packet with sync=%u timed out", sync); invokeCallback(sync, RequestResult(CB_TIMEOUT)); } } void Conn::invokeCallback(uint32_t sync, RequestResult &&req_res) { auto it = callbacks_map.find(sync); if( it != callbacks_map.end() ) invokeCallback(it, std::forward<RequestResult>(req_res)); } Conn::callbacks_map_type::iterator Conn::invokeCallback(Conn::callbacks_map_type::iterator it, RequestResult &&req_res) { if( LOG_DEBUG ) log_func("[iproto_conn] invokeCallback sync=%u res.code=%u", it->first, req_res.code); callbacks_map_type::iterator ret_it; auto timer_and_cb = it->second; ret_it = callbacks_map.erase(it); if( likely(timer_and_cb.first) ) { timer_and_cb.first->cancel(); delete timer_and_cb.first; } if( likely(timer_and_cb.second) ) try { io.post( boost::bind(timer_and_cb.second, std::forward<RequestResult>(req_res)) ); //Scared of resume coroutines which already current } catch(std::exception &e) { log_func("[iproto_conn] invokeCallback uncatched exception: %s", e.what() ); abort(); //It's your guilt } return ret_it; } }; <commit_msg>iproto_conn: fix reconnect bug, fix logging<commit_after>#include <cstdlib> #include <cstdarg> #include <boost/asio.hpp> #include <boost/bind.hpp> #include "perf.hpp" #include "iproto.hpp" #include "iproto_conn.hpp" #define LOG_DEBUG 0 namespace IProto { int stderr_printf(char const* format, ...) { va_list args; va_start(args, format); int result = vfprintf(stderr, format, args); va_end(args); fprintf(stderr, "\n"); return result; } Conn::Conn(boost::asio::io_service &_io, const boost::asio::ip::tcp::endpoint &_ep, uint32_t _connect_timeout, uint32_t _read_timeout) : io(_io), ep(_ep), sock(_io), timer(_io), ping_timer(_io) { if( _read_timeout==0 ) _read_timeout=_connect_timeout; connect_timeout=_connect_timeout; read_timeout=_read_timeout; write_queue_len=0; write_is_active=ping_enabled=true; log_func = stderr_printf; } Conn::~Conn() { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u destructor", ep.address().to_string().c_str(), ep.port()); close(); dismissCallbacks(CB_ERR); } void Conn::close() { boost::system::error_code ec = boost::asio::error::interrupted; for(int i=0; i<3 && sock.is_open() && ec == boost::asio::error::interrupted; ++i) sock.close(ec); } void Conn::disablePing() { ping_enabled=false; ping_timer.cancel(); } void Conn::setupPing(const boost::system::error_code& error) { if( error || !ping_enabled ) return; if( !sock.is_open() ) beginConnect(); //Write a ping packet into socket static const IProto::Header hdr{0xff00, 0}; static const IProto::PacketPtr pkt{hdr}; Write(IProto::Packet(&pkt), boost::bind(&Conn::pingCb, shared_from_this(), _1) ); } void Conn::pingCb(RequestResult res) { if( unlikely(res.code != CB_OK) ) { //Reconnect log_func("[iproto_conn] %s:%u ping failed, code %u", ep.address().to_string().c_str(), ep.port(), res.code); if( res.code == CB_TIMEOUT ) { reconnect(); return; } } ping_timer.expires_from_now( boost::posix_time::milliseconds(300) ); ping_timer.async_wait( boost::bind(&Conn::setupPing, shared_from_this(), boost::asio::placeholders::error) ); } bool Conn::checkConnect() { if( unlikely(!sock.is_open()) ) { beginConnect(); return true; } return false; } void Conn::beginConnect() { write_is_active=false; ping_timer.cancel(); //Limit connection time timer.expires_from_now( boost::posix_time::milliseconds(connect_timeout) ); timer.async_wait( boost::bind(&Conn::reconnectByTimer, shared_from_this(), boost::asio::placeholders::error) ); sock.async_connect( ep, boost::bind(&Conn::onConnect, shared_from_this(), boost::asio::placeholders::error) ); if( LOG_DEBUG ) log_func("[iproto_conn] Connecting to %s:%d", ep.address().to_string().c_str(), ep.port() ); } void Conn::reconnect() { close(); if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u reconnect", ep.address().to_string().c_str(), ep.port()); beginConnect(); } void Conn::dismissCallbacks(CB_Result res) { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u dismissCallbacks", ep.address().to_string().c_str(), ep.port()); ping_timer.cancel(); for(auto it=callbacks_map.begin(); it!=callbacks_map.end(); ) { it = invokeCallback(it, RequestResult(res)); } callbacks_map.clear(); } void Conn::reconnectByTimer(const boost::system::error_code& error) { if( !error ) reconnect(); } void Conn::onConnect(const boost::system::error_code& error) { if( likely(!error) ) { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u connected", ep.address().to_string().c_str(), ep.port()); timer.cancel(); setupReadHandler(); sock.set_option( boost::asio::ip::tcp::no_delay(true) ); if( ping_enabled ) setupPing( boost::system::error_code() ); else ensureWriteBuffer( boost::system::error_code() ); }else log_func("[iproto_conn] %s:%u connect failed: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() ); } void Conn::setupReadHandler() { if( likely(!rd_buf || rd_buf->size()==0) ) rd_buf.reset(new boost::asio::streambuf); onRead( boost::system::error_code() ); } void Conn::onRead(const boost::system::error_code& error) { if( unlikely(error) ) { log_func("[iproto_conn] %s:%u read error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() ); dismissCallbacks(CB_ERR); if( error != boost::asio::error::operation_aborted ) { reconnect(); } return; } if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u onRead rd_buf->size=%zu", ep.address().to_string().c_str(), ep.port(), rd_buf->size()); while( rd_buf->size() >= sizeof(Header) ) { const PacketPtr *buf = boost::asio::buffer_cast< const PacketPtr * >( rd_buf->data() ); size_t want_read = sizeof(Header)+buf->hdr.len; if( want_read <= rd_buf->size() ) { invokeCallback(buf->hdr.sync, RequestResult(CB_OK, Packet(buf)) ); rd_buf->consume( sizeof(Header) + buf->hdr.len ); }else{ boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(want_read - rd_buf->size()), boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error) ); return; } } if( likely(sock.is_open()) ) boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(sizeof(Header)-rd_buf->size()), boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error) ); } void Conn::ensureWriteBuffer(const boost::system::error_code& error, const char *wr_buf) { if( unlikely(error) ) { log_func("[iproto_conn] %s:%u write error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() ); if( error != boost::asio::error::operation_aborted ) { if( error == boost::asio::error::broken_pipe ) { //Packet was not completely transfered, we can do a retry write_queue.push_back( wr_buf ); write_queue_len++; wr_buf=nullptr;//Prevent free } reconnect(); }else{ dismissCallbacks(CB_ERR); } if( likely(wr_buf != nullptr) ) ::free((void*)wr_buf); return; } if( likely(wr_buf != nullptr) ) ::free((void*)wr_buf); if( likely(write_queue_len>0 && (wr_buf || !write_is_active)) ) { const char *wr = write_queue.front(); write_queue.pop_front(); write_queue_len--; const Header *hdr = reinterpret_cast< const Header * >(wr); boost::asio::async_write(sock, boost::asio::buffer(wr, sizeof(*hdr)+hdr->len), boost::bind(&Conn::ensureWriteBuffer, shared_from_this(), boost::asio::placeholders::error, wr) ); if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u write packet sync=%u len=%u", ep.address().to_string().c_str(), ep.port(), hdr->sync, hdr->len); write_is_active=true; } else write_is_active=false; } bool Conn::dropPacketWrite(Packet &&pkt) { write_queue.push_back( pkt.data ); pkt.data=nullptr; write_queue_len++; if( unlikely(checkConnect()) ) { log_func("[iproto_conn] %s:%u dropPacketWrite deferred (no connect)", ep.address().to_string().c_str(), ep.port()); return false; } ensureWriteBuffer( boost::system::error_code() ); return true; } bool Conn::Write(Packet &&pkt, callbacks_func_type &&cb) { auto timer = new boost::asio::deadline_timer(io); timer->expires_from_now( boost::posix_time::milliseconds(read_timeout) ); timer->async_wait( boost::bind(&Conn::onTimeout, shared_from_this(), boost::asio::placeholders::error, pkt.hdr.sync) ); callbacks_map[pkt.hdr.sync] = std::make_pair(timer, std::forward<callbacks_func_type>(cb)); return dropPacketWrite( std::forward<Packet>(pkt) ); } void Conn::Shutdown() { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u shutdown", ep.address().to_string().c_str(), ep.port()); close(); dismissCallbacks(CB_ERR); } bool Conn::GentleShutdown() { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u GentleShutdown", ep.address().to_string().c_str(), ep.port()); if( callbacks_map.empty() && !write_is_active ) { Shutdown(); return true; } return false; } void Conn::onTimeout(const boost::system::error_code& error, uint32_t sync) { if( unlikely(!error) ) { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u Packet with sync=%u timed out", ep.address().to_string().c_str(), ep.port(), sync); invokeCallback(sync, RequestResult(CB_TIMEOUT)); } } void Conn::invokeCallback(uint32_t sync, RequestResult &&req_res) { auto it = callbacks_map.find(sync); if( it != callbacks_map.end() ) invokeCallback(it, std::forward<RequestResult>(req_res)); } Conn::callbacks_map_type::iterator Conn::invokeCallback(Conn::callbacks_map_type::iterator it, RequestResult &&req_res) { if( LOG_DEBUG ) log_func("[iproto_conn] %s:%u invokeCallback sync=%u res.code=%u", ep.address().to_string().c_str(), ep.port(), it->first, req_res.code); callbacks_map_type::iterator ret_it; auto timer_and_cb = it->second; ret_it = callbacks_map.erase(it); if( likely(timer_and_cb.first) ) { timer_and_cb.first->cancel(); delete timer_and_cb.first; } if( likely(timer_and_cb.second) ) try { io.post( boost::bind(timer_and_cb.second, std::forward<RequestResult>(req_res)) ); //Scared of resume coroutines which already current } catch(std::exception &e) { log_func("[iproto_conn] %s:%u invokeCallback uncatched exception: %s", ep.address().to_string().c_str(), ep.port(), e.what() ); abort(); //It's your guilt } return ret_it; } }; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #include "job.h" #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <string> #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> #include <boost/uuid/uuid.hpp> #include "db/driver.h" #include "db/eq-inserter.h" #include "db/query.h" #include "db/statement-driver.h" namespace flint { namespace job { namespace { class NextJob : db::StatementDriver { public: explicit NextJob(sqlite3 *db) : db::StatementDriver(db, "SELECT rowid, ps_id FROM jobs WHERE status = 'pending' LIMIT 1") { } /* * Return 1 if a pending job is found, 0 if no more pending one, or -1 otherwise. */ int Get(int *rowid, int *ps_id) { int e; e = sqlite3_step(stmt()); if (e == SQLITE_DONE) { // no more pending row return 0; } if (e != SQLITE_ROW) { std::cerr << "failed to get a next job: " << e << std::endl; return -1; } *rowid = sqlite3_column_int(stmt(), 0); *ps_id = sqlite3_column_int(stmt(), 1); return 1; } }; class Inserter { public: Inserter(sqlite3 *db, FILE *fp) : inserter_("parameter_eqs", db) , fp_(fp) {} bool Insert(const char *name, const char *rhs) { std::fprintf(fp_, "%s=%s\n", name, rhs); std::ostringstream oss; oss << "(eq %" << name << ' ' << rhs << ')'; std::string math = oss.str(); return inserter_.Insert(math.c_str()); } bool Insert(const boost::uuids::uuid &uuid, const char *math) { return inserter_.Insert(uuid, math); } private: db::EqInserter inserter_; FILE *fp_; }; int SaveParameter(void *data, int argc, char **argv, char **names) { Inserter *inserter = static_cast<Inserter *>(data); for (int i=0;i<argc;i++) { if (!inserter->Insert(names[i], argv[i])) return 1; } return 0; } int SaveEquation(void *data, int argc, char **argv, char **names) { Inserter *inserter = static_cast<Inserter *>(data); (void)names; assert(argc == 2); boost::uuids::uuid uuid; assert(argv[0]); std::memcpy(&uuid, argv[0], uuid.size()); return (inserter->Insert(uuid, argv[1])) ? 0 : 1; } class Generator { public: Generator(sqlite3 *input, sqlite3 *output, FILE *fp) : input_(input) , inserter_(output, fp) {} bool Generate(int rowid, int ps_id) { char query[1024]; char *em; int e; /* print equations */ std::sprintf(query, "SELECT * FROM parameter_samples WHERE rowid = '%d'", ps_id); e = sqlite3_exec(input_, query, SaveParameter, &inserter_, &em); if (e != SQLITE_OK) { if (e != SQLITE_ABORT) std::cerr << "failed to select parameter_samples: " << e << ": " << em << std::endl; sqlite3_free(em); return false; } e = sqlite3_exec(input_, "SELECT uuid, body FROM equations", SaveEquation, &inserter_, &em); if (e != SQLITE_OK) { if (e != SQLITE_ABORT) std::cerr << "failed to select equations: " << e << ": " << em << std::endl; sqlite3_free(em); return false; } /* mark it generated */ std::sprintf(query, "UPDATE jobs SET status = 'generated' WHERE rowid = '%d'", rowid); e = sqlite3_exec(input_, query, nullptr, nullptr, &em); if (e != SQLITE_OK) { std::fprintf(stderr, "failed to update jobs: %d: %s\n", e, em); sqlite3_free(em); return false; } return true; } private: sqlite3 *input_; Inserter inserter_; }; } bool Generate(sqlite3 *input, const char *dir, int *job_id) { int rowid; int ps_id; { NextJob nj(input); int r = nj.Get(&rowid, &ps_id); if (r == 0) { *job_id = 0; return true; } if (r < 0) return false; } std::unique_ptr<char[]> path(BuildPath(dir, rowid)); boost::system::error_code ec; boost::filesystem::create_directories(path.get(), ec); if (ec) { std::cerr << "failed to create directories: " << path.get() << ": " << ec << std::endl; return false; } char filename[96]; std::sprintf(filename, "%s/generated.db", path.get()); db::Driver driver(filename); sqlite3 *output = driver.db(); if (!output) return false; if (!BeginTransaction(output)) return false; if (!CreateTable(output, "parameter_eqs", "(uuid BLOB, math TEXT)")) return false; std::sprintf(filename, "%s/values.txt.tmp", path.get()); FILE *fp = std::fopen(filename, "w"); if (!fp) { std::perror(filename); return false; } if (!BeginTransaction(input)) { std::fclose(fp); return false; } Generator g(input, output, fp); if (!g.Generate(rowid, ps_id)) { std::fclose(fp); return false; } if (!CommitTransaction(input)) { std::fclose(fp); return false; } std::fclose(fp); char values_file[96]; // large enough std::sprintf(values_file, "%s/values.txt", path.get()); if (std::rename(filename, values_file) != 0) { std::cerr << "failed to rename " << filename << " to " << values_file << std::endl; std::remove(filename); return false; } if (!CommitTransaction(output)) return false; *job_id = rowid; return true; } } } <commit_msg>Destruct objects earlier<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #include "job.h" #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <string> #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> #include <boost/uuid/uuid.hpp> #include "db/driver.h" #include "db/eq-inserter.h" #include "db/query.h" #include "db/statement-driver.h" namespace flint { namespace job { namespace { class NextJob : db::StatementDriver { public: explicit NextJob(sqlite3 *db) : db::StatementDriver(db, "SELECT rowid, ps_id FROM jobs WHERE status = 'pending' LIMIT 1") { } /* * Return 1 if a pending job is found, 0 if no more pending one, or -1 otherwise. */ int Get(int *rowid, int *ps_id) { int e; e = sqlite3_step(stmt()); if (e == SQLITE_DONE) { // no more pending row return 0; } if (e != SQLITE_ROW) { std::cerr << "failed to get a next job: " << e << std::endl; return -1; } *rowid = sqlite3_column_int(stmt(), 0); *ps_id = sqlite3_column_int(stmt(), 1); return 1; } }; class Inserter { public: Inserter(sqlite3 *db, FILE *fp) : inserter_("parameter_eqs", db) , fp_(fp) {} bool Insert(const char *name, const char *rhs) { std::fprintf(fp_, "%s=%s\n", name, rhs); std::ostringstream oss; oss << "(eq %" << name << ' ' << rhs << ')'; std::string math = oss.str(); return inserter_.Insert(math.c_str()); } bool Insert(const boost::uuids::uuid &uuid, const char *math) { return inserter_.Insert(uuid, math); } private: db::EqInserter inserter_; FILE *fp_; }; int SaveParameter(void *data, int argc, char **argv, char **names) { Inserter *inserter = static_cast<Inserter *>(data); for (int i=0;i<argc;i++) { if (!inserter->Insert(names[i], argv[i])) return 1; } return 0; } int SaveEquation(void *data, int argc, char **argv, char **names) { Inserter *inserter = static_cast<Inserter *>(data); (void)names; assert(argc == 2); boost::uuids::uuid uuid; assert(argv[0]); std::memcpy(&uuid, argv[0], uuid.size()); return (inserter->Insert(uuid, argv[1])) ? 0 : 1; } class Generator { public: Generator(sqlite3 *input, sqlite3 *output, FILE *fp) : input_(input) , inserter_(output, fp) {} bool Generate(int rowid, int ps_id) { char query[1024]; char *em; int e; /* print equations */ std::sprintf(query, "SELECT * FROM parameter_samples WHERE rowid = '%d'", ps_id); e = sqlite3_exec(input_, query, SaveParameter, &inserter_, &em); if (e != SQLITE_OK) { if (e != SQLITE_ABORT) std::cerr << "failed to select parameter_samples: " << e << ": " << em << std::endl; sqlite3_free(em); return false; } e = sqlite3_exec(input_, "SELECT uuid, body FROM equations", SaveEquation, &inserter_, &em); if (e != SQLITE_OK) { if (e != SQLITE_ABORT) std::cerr << "failed to select equations: " << e << ": " << em << std::endl; sqlite3_free(em); return false; } /* mark it generated */ std::sprintf(query, "UPDATE jobs SET status = 'generated' WHERE rowid = '%d'", rowid); e = sqlite3_exec(input_, query, nullptr, nullptr, &em); if (e != SQLITE_OK) { std::fprintf(stderr, "failed to update jobs: %d: %s\n", e, em); sqlite3_free(em); return false; } return true; } private: sqlite3 *input_; Inserter inserter_; }; } bool Generate(sqlite3 *input, const char *dir, int *job_id) { int rowid; int ps_id; { NextJob nj(input); int r = nj.Get(&rowid, &ps_id); if (r == 0) { *job_id = 0; return true; } if (r < 0) return false; } std::unique_ptr<char[]> path(BuildPath(dir, rowid)); boost::system::error_code ec; boost::filesystem::create_directories(path.get(), ec); if (ec) { std::cerr << "failed to create directories: " << path.get() << ": " << ec << std::endl; return false; } char filename[96]; std::sprintf(filename, "%s/generated.db", path.get()); { db::Driver driver(filename); sqlite3 *output = driver.db(); if (!output) return false; if (!BeginTransaction(output)) return false; if (!CreateTable(output, "parameter_eqs", "(uuid BLOB, math TEXT)")) return false; std::sprintf(filename, "%s/values.txt.tmp", path.get()); FILE *fp = std::fopen(filename, "w"); if (!fp) { std::perror(filename); return false; } if (!BeginTransaction(input)) { std::fclose(fp); return false; } { Generator g(input, output, fp); if (!g.Generate(rowid, ps_id)) { std::fclose(fp); return false; } } if (!CommitTransaction(input)) { std::fclose(fp); return false; } std::fclose(fp); if (!CommitTransaction(output)) return false; } char values_file[96]; // large enough std::sprintf(values_file, "%s/values.txt", path.get()); if (std::rename(filename, values_file) != 0) { std::cerr << "failed to rename " << filename << " to " << values_file << std::endl; std::remove(filename); return false; } *job_id = rowid; return true; } } } <|endoftext|>
<commit_before>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <mpl/mthread.h> #ifdef M_OS_WIN #ifdef __cplusplus extern "C" { #endif static unsigned int __stdcall thread_routine(void *arg) { mpl::MThread *self = (mpl::MThread *) arg; if (NULL != self) { self->exec(); } return 0; } #ifdef __cplusplus } #endif #else /* LINUX */ #ifdef __cplusplus extern "C" { #endif static void *thread_routine(void *arg) { mpl::MThread *self = (mpl::MThread *) arg; if (NULL != self) { self->exec(); } return NULL; } #ifdef __cplusplus } #endif #endif /* M_OS_WIN */ MPL_BEGIN_NAMESPACE MThread::MThread() { _self = 0; } MThread::~MThread() { } bool MThread::start() { int res = 0; res = pthread_create(&_self, NULL, thread_routine, this); if (0 != res) perror("create thread"); return res == 0; } void MThread::stop() { interrupt(); join(); } int MThread::join() { return pthread_join(_self, NULL); } int MThread::detach() { return pthread_detach(_self); } int MThread::cancel() { return pthread_cancel(_self); } int64_t MThread::id() { return _self; } // void MThread::setPriority(Priority priority) // { // MScopedLock locker(_mutex); // _priority = priority; // } // MThread::Priority MThread::priority() const // { // return _priority; // } void MThread::interrupt() { MScopedLock locker(_mutex); _interrupt = true; } bool MThread::isInterrupted() const { return _interrupt; } void MThread::exec() { _interrupt = false; run(); } // Begin functions // get_thread_id int64_t threadId() { return pthread_self(); } MPL_END_NAMESPACE <commit_msg>update mthread, add Windows implement<commit_after>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <mpl/mthread.h> #ifdef M_OS_WIN #ifdef __cplusplus extern "C" { #endif static unsigned int __stdcall thread_routine(void *arg) { mpl::MThread *self = (mpl::MThread *) arg; if (NULL != self) { self->exec(); } return 0; } #ifdef __cplusplus } #endif #else /* LINUX */ #ifdef __cplusplus extern "C" { #endif static void *thread_routine(void *arg) { mpl::MThread *self = (mpl::MThread *) arg; if (NULL != self) { self->exec(); } return NULL; } #ifdef __cplusplus } #endif #endif /* M_OS_WIN */ MPL_BEGIN_NAMESPACE #if defined(M_OS_WIN) || defined(_MSC_VER) MThread::MThread() : _self(0) { } MThread::~MThread() { } bool MThread::start() { LPSECURITY_ATTRIBUTES thread_attr = NULL; _self = (HANDLE) _beginthreadex(NULL, 0, thread_routine, this, 0, NULL); if (NULL == _self) { perror("can't create thread"); return false; } return true; } void MThread::stop() { interrupt(); join(); } int MThread::join() { DWORD rc = WaitForSingleObject(_self, INFINITE); if (WAIT_FAILED == rc) return -1; BOOL rc2 = CloseHandle(_self); if (!rc2) return -1; return 0; } int MThread::detach() { // TODO:: must be rewrite later return 0; } int MThread::cancel() { // TODO:: must be rewrite later BOOL res = TerminateThread(_self, 0); if (res) return 0; return -1; } int64_t MThread::id() { return _self; } void MThread::interrupt() { MScopedLock locker(_mutex); _interrupt = true; } bool MThread::isInterrupted() const { return _interrupt; } void MThread::exec() { _interrupt = false; run(); } #else MThread::MThread() { _self = 0; } MThread::~MThread() { } bool MThread::start() { int res = 0; res = pthread_create(&_self, NULL, thread_routine, this); if (0 != res) perror("create thread"); return res == 0; } void MThread::stop() { interrupt(); join(); } int MThread::join() { return pthread_join(_self, NULL); } int MThread::detach() { return pthread_detach(_self); } int MThread::cancel() { return pthread_cancel(_self); } int64_t MThread::id() { return _self; } void MThread::interrupt() { MScopedLock locker(_mutex); _interrupt = true; } bool MThread::isInterrupted() const { return _interrupt; } void MThread::exec() { _interrupt = false; run(); } #endif // Begin functions #if defined(M_OS_WIN) || defined(_MSC_VER) int64_t threadId() { return GetCurrentThreadId(); } #else // get_thread_id int64_t threadId() { return pthread_self(); } #endif MPL_END_NAMESPACE <|endoftext|>
<commit_before>#include "UpdateDialogGtkFactory.h" #include "FileUtils.h" #include "Log.h" #include "UpdateDialog.h" #include "StringUtils.h" #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> class UpdateDialogGtk; // GTK updater UI library embedded into // the updater binary extern unsigned char libupdatergtk_so[]; extern unsigned int libupdatergtk_so_len; // pointers to helper functions in the GTK updater UI library UpdateDialogGtk* (*update_dialog_gtk_new)() = 0; #if __cplusplus >= 201103L #define TYPEOF(x) decltype(x) #else #define TYPEOF(x) typeof(x) #endif #define BIND_FUNCTION(library,function) \ function = reinterpret_cast<TYPEOF(function)>(dlsym(library,#function)); bool extractFileFromBinary(int fd, const void* buffer, size_t length) { size_t count = write(fd,buffer,length); close(fd); return count >= length; } UpdateDialog* UpdateDialogGtkFactory::createDialog() { char* libPath = strdup("/tmp/mendeley-libUpdaterGtk.so.XXXXXX"); int libFd = mkostemp(libPath, O_CREAT | O_WRONLY | O_TRUNC); if (libFd == -1) { LOG(Warn,"Failed to create temporary file - " + std::string(strerror(errno))); return 0; } if (!extractFileFromBinary(libFd,libupdatergtk_so,libupdatergtk_so_len)) { LOG(Warn,"Failed to load the GTK UI library - " + std::string(strerror(errno))); return 0; } void* gtkLib = dlopen(libPath,RTLD_LAZY); if (!gtkLib) { LOG(Warn,"Failed to load the GTK UI - " + std::string(dlerror())); return 0; } BIND_FUNCTION(gtkLib,update_dialog_gtk_new); FileUtils::removeFile(libPath); return reinterpret_cast<UpdateDialog*>(update_dialog_gtk_new()); } <commit_msg>Uses stack-allocated array.<commit_after>#include "UpdateDialogGtkFactory.h" #include "FileUtils.h" #include "Log.h" #include "UpdateDialog.h" #include "StringUtils.h" #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <vector> class UpdateDialogGtk; // GTK updater UI library embedded into // the updater binary extern unsigned char libupdatergtk_so[]; extern unsigned int libupdatergtk_so_len; // pointers to helper functions in the GTK updater UI library UpdateDialogGtk* (*update_dialog_gtk_new)() = 0; #if __cplusplus >= 201103L #define TYPEOF(x) decltype(x) #else #define TYPEOF(x) typeof(x) #endif #define BIND_FUNCTION(library,function) \ function = reinterpret_cast<TYPEOF(function)>(dlsym(library,#function)); #define MAX_FILE_PATH 4096 bool extractFileFromBinary(int fd, const void* buffer, size_t length) { size_t count = write(fd,buffer,length); close(fd); return count >= length; } UpdateDialog* UpdateDialogGtkFactory::createDialog() { char libPath[MAX_FILE_PATH]; strncpy(libPath, "/tmp/mendeley-libUpdaterGtk.so.XXXXXX", MAX_FILE_PATH); int libFd = mkostemp(libPath, O_CREAT | O_WRONLY | O_TRUNC); if (libFd == -1) { LOG(Warn,"Failed to create temporary file - " + std::string(strerror(errno))); return 0; } if (!extractFileFromBinary(libFd,libupdatergtk_so,libupdatergtk_so_len)) { LOG(Warn,"Failed to load the GTK UI library - " + std::string(strerror(errno))); return 0; } void* gtkLib = dlopen(libPath,RTLD_LAZY); if (!gtkLib) { LOG(Warn,"Failed to load the GTK UI - " + std::string(dlerror())); return 0; } BIND_FUNCTION(gtkLib,update_dialog_gtk_new); FileUtils::removeFile(libPath); return reinterpret_cast<UpdateDialog*>(update_dialog_gtk_new()); } <|endoftext|>
<commit_before>/* Dorm LED Project: led_desk_anim_cmds.cpp This file contains the desk LED animation commands. These are meant to be executed using the multithreaded system. Note: First element in the var stack is to store number of complete executions (resetable). Created by: Michael Fischler 10/22/2016 @ WPI */ #include <Adafruit_NeoPixel.h> /* Template for a Command LocakStack* cmd(LocalStack* var_stack) LocakStack* cmd(LocalStack* var_stack){ // set variables int i = var_stack->getInt(0); char t = var_stack->getChar(1); // run command code ... // update variables var_stack->update(0, &i); var_stack->update(1, &t); return var_stack; } */ /* ~~~~~~ Off Commands ~~~~~~ */ // &&& Functions for Off Commands &&& void _desk1_off(){ for(int i = 0; i < DESK1_LENGTH; i++){ desk1.setPixelColor(i, desk1.Color(0,0,0)); } desk1.show(); } void _desk2_off(){ for(int i = 0; i < DESK2_LENGTH; i++){ desk2.setPixelColor(i, desk2.Color(0,0,0)); } desk2.show(); } // &&& Command Ready Functions for Off Commands &&& // Every LED for Desk 1 set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk1_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk1_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } // Every LED for Desk 2 set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk2_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk2_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } // Every LED set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desks_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk1_off(); _desk2_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } /* ~~~~~~ Static Commands ~~~~~~ */ // &&& Functions for Static Commands &&& void _desk_both_dim_ambient(){ for(int i = 0; i < DESK1_LENGTH; i++){ if(i%3 == 0){ desk1.setPixelColor(i, desk1.Color(75,45,25)); }else{ desk1.setPixelColor(i, desk1.Color(0,0,0)); } } for(int i = 0; i < DESK2_LENGTH; i++){ if(i%3 == 0){ desk2.setPixelColor(i, desk2.Color(75,45,25)); }else{ desk2.setPixelColor(i, desk2.Color(0,0,0)); } } desk1.show(); desk2.show(); } // &&& Command Ready Functions for Static Commands &&& // Every third LED gets a red tinted white // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk_both_dim_ambient(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk_both_dim_ambient(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } /* ~~~~~~ Animated Commands ~~~~~~ */ // &&& Functions for Animated Commands &&& void _desk_both_wpp_fade(int i){ for(int y = 0; y < DESK1_LENGTH; y++){ if(y%3 != 0){ desk1.setPixelColor(y, desk1.Color((int)(((float)i / 150.0) * 100), 0, i)); }else{ desk1.setPixelColor(y, desk1.Color(75,45,25)); } } for(int z = 0; z < DESK2_LENGTH; z++){ if(z%3 != 0){ desk2.setPixelColor(z, desk2.Color((int)(((float)i / 150.0) * 100), 0, i)); }else{ desk2.setPixelColor(z, desk2.Color(75,45,25)); } } desk1.show(); desk2.show(); } // &&& Command Ready Functions for Animated Commands &&& // Every third LED stays nice reddish white while the others fade in and out a calm purple // Initial input var_stack : LocalStack* stack {0,0,true} LocalStack* desk_both_wpp_fade(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); unsigned int i = var_stack->getUnsignInt(1); bool increasing = var_stack->getBool(2); // run command code _desk_both_wpp_fade(i); if(increasing){ if(i == 150){ i--; increasing = false; }else{ i++; } }else{ if(i == 0){ i++; increasing = true; fec++; }else{ i--; } } // update variables var_stack->update(0, &fec); var_stack->update(1, &i); var_stack->update(2, &increasing); return var_stack; } <commit_msg>formatting<commit_after>/* Dorm LED Project: led_desk_anim_cmds.cpp This file contains the desk LED animation commands. These are meant to be executed using the multithreaded system. Note: First element in the var stack is to store number of complete executions (resetable). Created by: Michael Fischler 10/22/2016 @ WPI */ #include <Adafruit_NeoPixel.h> /* Template for a Command LocakStack* cmd(LocalStack* var_stack) LocakStack* cmd(LocalStack* var_stack){ // set variables int i = var_stack->getInt(0); char t = var_stack->getChar(1); // run command code ... // update variables var_stack->update(0, &i); var_stack->update(1, &t); return var_stack; } */ /* ~~~~~~ Off Commands ~~~~~~ */ // &&& Functions for Off Commands &&& void _desk1_off(){ for(int i = 0; i < DESK1_LENGTH; i++){ desk1.setPixelColor(i, desk1.Color(0,0,0)); } desk1.show(); } void _desk2_off(){ for(int i = 0; i < DESK2_LENGTH; i++){ desk2.setPixelColor(i, desk2.Color(0,0,0)); } desk2.show(); } // &&& Command Ready Functions for Off Commands &&& // Every LED for Desk 1 set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk1_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk1_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } // Every LED for Desk 2 set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk2_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk2_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } // Every LED set to {0,0,0} // Initial input var_stack : LocalStack* stack [empty] LocalStack* desks_off(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk1_off(); _desk2_off(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } /* ~~~~~~ Static Commands ~~~~~~ */ // &&& Functions for Static Commands &&& void _desk_both_dim_ambient(){ for(int i = 0; i < DESK1_LENGTH; i++){ if(i%3 == 0){ desk1.setPixelColor(i, desk1.Color(75,45,25)); }else{ desk1.setPixelColor(i, desk1.Color(0,0,0)); } } for(int i = 0; i < DESK2_LENGTH; i++){ if(i%3 == 0){ desk2.setPixelColor(i, desk2.Color(75,45,25)); }else{ desk2.setPixelColor(i, desk2.Color(0,0,0)); } } desk1.show(); desk2.show(); } // &&& Command Ready Functions for Static Commands &&& // Every third LED gets a red tinted white // Initial input var_stack : LocalStack* stack [empty] LocalStack* desk_both_dim_ambient(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); // run command code _desk_both_dim_ambient(); // update variables fec++; var_stack->update(0, &fec); return var_stack; } /* ~~~~~~ Animated Commands ~~~~~~ */ // &&& Functions for Animated Commands &&& void _desk_both_wpp_fade(int i){ for(int y = 0; y < DESK1_LENGTH; y++){ if(y%3 != 0){ desk1.setPixelColor(y, desk1.Color((int)(((float)i / 150.0) * 100), 0, i)); }else{ desk1.setPixelColor(y, desk1.Color(75,45,25)); } } for(int z = 0; z < DESK2_LENGTH; z++){ if(z%3 != 0){ desk2.setPixelColor(z, desk2.Color((int)(((float)i / 150.0) * 100), 0, i)); }else{ desk2.setPixelColor(z, desk2.Color(75,45,25)); } } desk1.show(); desk2.show(); } // &&& Command Ready Functions for Animated Commands &&& // Every third LED stays nice reddish white while the others fade in and out a calm purple // Initial input var_stack : LocalStack* stack {0,0,true} LocalStack* desk_both_wpp_fade(LocalStack* var_stack){ // set variables int fec = var_stack->getInt(0); unsigned int i = var_stack->getUnsignInt(1); bool increasing = var_stack->getBool(2); // run command code _desk_both_wpp_fade(i); if(increasing){ if(i == 150){ i--; increasing = false; }else{ i++; } }else{ if(i == 0){ i++; increasing = true; fec++; }else{ i--; } } // update variables var_stack->update(0, &fec); var_stack->update(1, &i); var_stack->update(2, &increasing); return var_stack; } <|endoftext|>
<commit_before>// Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/balancebubble.h" #include "qt/pivx/forms/ui_balancebubble.h" #include "qt/pivx/qtutils.h" #include <QGraphicsOpacityEffect> #include <QPropertyAnimation> #include <QTimer> #include <qt/bitcoinunits.h> BalanceBubble::BalanceBubble(QWidget *parent) : QWidget(parent), ui(new Ui::BalanceBubble) { ui->setupUi(this); ui->frame->setProperty("cssClass", "container-popup"); setCssProperty({ui->textTransparent, ui->textShielded}, "amount-small-popup"); std::initializer_list<QWidget*> lblTitles = {ui->lblFirst, ui->lblSecond}; setCssProperty(lblTitles, "text-title-topbar"); QFont font; font.setWeight(QFont::Light); for (QWidget* w : lblTitles) { w->setFont(font); } } void BalanceBubble::updateValues(int64_t nTransparentBalance, int64_t nShieldedBalance, int unit) { QString valueTrans = BitcoinUnits::formatWithUnit(unit, nTransparentBalance, false, BitcoinUnits::separatorAlways); valueTrans = valueTrans.replace(QChar(THIN_SP_CP), QString(",")); QString valueShield = BitcoinUnits::formatWithUnit(unit, nShieldedBalance, false, BitcoinUnits::separatorAlways); valueShield = valueShield.replace(QChar(THIN_SP_CP), QString(",")); ui->textTransparent->setText(valueTrans); ui->textShielded->setText(valueShield); adjustSize(); } void BalanceBubble::showEvent(QShowEvent *event) { QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); this->setGraphicsEffect(eff); QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity"); a->setDuration(400); a->setStartValue(0.1); a->setEndValue(1); a->setEasingCurve(QEasingCurve::InBack); a->start(QPropertyAnimation::DeleteWhenStopped); if (!hideTimer) hideTimer = new QTimer(this); connect(hideTimer, &QTimer::timeout, this, &BalanceBubble::hideTimeout); hideTimer->start(7000); } void BalanceBubble::hideEvent(QHideEvent *event) { if (hideTimer) hideTimer->stop(); QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); this->setGraphicsEffect(eff); QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity"); a->setDuration(800); a->setStartValue(1); a->setEndValue(0); a->setEasingCurve(QEasingCurve::OutBack); a->start(QPropertyAnimation::DeleteWhenStopped); } void BalanceBubble::hideTimeout() { hide(); } BalanceBubble::~BalanceBubble() { delete ui; }<commit_msg>Fixes double fade-in animation when clicking the question mark next to the 'Available' label in the top bar<commit_after>// Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/balancebubble.h" #include "qt/pivx/forms/ui_balancebubble.h" #include "qt/pivx/qtutils.h" #include <QGraphicsOpacityEffect> #include <QPropertyAnimation> #include <QTimer> #include <qt/bitcoinunits.h> BalanceBubble::BalanceBubble(QWidget *parent) : QWidget(parent), ui(new Ui::BalanceBubble) { ui->setupUi(this); ui->frame->setProperty("cssClass", "container-popup"); setCssProperty({ui->textTransparent, ui->textShielded}, "amount-small-popup"); std::initializer_list<QWidget*> lblTitles = {ui->lblFirst, ui->lblSecond}; setCssProperty(lblTitles, "text-title-topbar"); QFont font; font.setWeight(QFont::Light); for (QWidget* w : lblTitles) { w->setFont(font); } } void BalanceBubble::updateValues(int64_t nTransparentBalance, int64_t nShieldedBalance, int unit) { QString valueTrans = BitcoinUnits::formatWithUnit(unit, nTransparentBalance, false, BitcoinUnits::separatorAlways); valueTrans = valueTrans.replace(QChar(THIN_SP_CP), QString(",")); QString valueShield = BitcoinUnits::formatWithUnit(unit, nShieldedBalance, false, BitcoinUnits::separatorAlways); valueShield = valueShield.replace(QChar(THIN_SP_CP), QString(",")); ui->textTransparent->setText(valueTrans); ui->textShielded->setText(valueShield); adjustSize(); } void BalanceBubble::showEvent(QShowEvent *event) { QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); this->setGraphicsEffect(eff); QPropertyAnimation *anim = new QPropertyAnimation(eff,"opacity"); anim->setDuration(400); anim->setStartValue(0); anim->setEndValue(1); anim->setEasingCurve(QEasingCurve::Linear); anim->start(QPropertyAnimation::DeleteWhenStopped); if (!hideTimer) hideTimer = new QTimer(this); connect(hideTimer, &QTimer::timeout, this, &BalanceBubble::hideTimeout); hideTimer->start(7000); } void BalanceBubble::hideEvent(QHideEvent *event) { if (hideTimer) hideTimer->stop(); QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); this->setGraphicsEffect(eff); QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity"); a->setDuration(800); a->setStartValue(1); a->setEndValue(0); a->setEasingCurve(QEasingCurve::OutBack); a->start(QPropertyAnimation::DeleteWhenStopped); } void BalanceBubble::hideTimeout() { hide(); } BalanceBubble::~BalanceBubble() { delete ui; } <|endoftext|>
<commit_before>/** * @note HEADER-ONLY IMPLEMENTATION FILE * @warn Do not include directly */ // FFNN #include <ffnn/assert.h> #include <ffnn/logging.h> #include <ffnn/layer/activation.h> namespace ffnn { namespace optimizer { template<> template<typename ValueType, template<class> class NeuronType, FFNN_SIZE_TYPE SizeAtCompileTime> class Adam<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>>: public GradientDescent<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>> { public: /// Base type standardization typedef typename GradientDescent<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>> Base; /// Layer type standardization typedef typename layer::Activation<ValueType, NeuronType, SizeAtCompileTime> LayerType; /// Scalar type standardization typedef typename LayerType::ScalarType ScalarType; /// Size type standardization typedef typename LayerType::SizeType SizeType; /// Matrix type standardization typedef typename LayerType::InputVector InputVector; /// Matrix type standardization typedef typename LayerType::OutputVector OutputVector; /// Matrix type standardization typedef typename LayerType::BiasVector BiasVector; /** * @brief Setup constructor * @param lr Learning rate */ explicit Adam(ScalarType lr, ScalarType beta1 = 0.9, ScalarType beta2 = 0.999, ScalarType eps = 1e-8) : Base(lr), beta1_(beta1), beta2_(beta2), epsilon_(eps) { Base::setName("Adam[Activation]"); FFNN_ASSERT_MSG(beta1_ > 0 && beta1_ < 1, "Beta1 should be in the range (0, 1)."); FFNN_ASSERT_MSG(beta2_ > 0 && beta2_ < 1, "Beta1 should be in the range (0, 1)."); FFNN_ASSERT_MSG(epsilon_ > 0, "Epsilon should be > 0."); } virtual ~Adam() {} /** * @brief Initializes the Optimizer * @param[in, out] layer Layer to optimize */ void initialize(LayerType& layer) { Base::initialize(layer); // Reset moment matrices mean_gradient_.setZero(layer.output_dimension_, 1); var_gradient_.setZero(layer.output_dimension_, 1); } /** * @brief Applies optimization update * @param[in, out] layer Layer to optimize * @retval true if optimization update was applied successfully * @retval false otherwise */ bool update(LayerType& layer) { FFNN_ASSERT_MSG(layer.isInitialized(), "Layer to optimize is not initialized."); // Update gradient moments mean_gradient_ += beta1_ * (gradient_ - mean_gradient_); var_gradient_ += beta2_ * (gradient_ - var_gradient_); // Compute learning rates for all weights BiasVector current_gradient = var_gradient_; current_gradient.noalias() /= (1 - beta2_); current_gradient.array() += epsilon_; current_gradient.noalias() = mean_gradient_.array() / current_gradient.array(); current_gradient.noalias() /= (1 - beta1_); current_gradient.noalias() *= Base::lr_; // Update weights layer.b_.noalias() -= current_gradient; // Reinitialize optimizer Base::reset(layer); return true; } private: /// Mean decay rate const ScalarType beta1_; /// Variance decay rate const ScalarType beta2_; /// Variance normalization value const ScalarType epsilon_; /// Running mean of error gradient BiasVector mean_gradient_; /// Uncentered variance of error gradient BiasVector var_gradient_; }; } // namespace optimizer } // namespace ffnn <commit_msg>Updates asserts in Adam[Activation] optimizer<commit_after>/** * @note HEADER-ONLY IMPLEMENTATION FILE * @warn Do not include directly */ // FFNN #include <ffnn/assert.h> #include <ffnn/logging.h> #include <ffnn/layer/activation.h> namespace ffnn { namespace optimizer { template<> template<typename ValueType, template<class> class NeuronType, FFNN_SIZE_TYPE SizeAtCompileTime> class Adam<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>>: public GradientDescent<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>> { public: /// Base type standardization typedef typename GradientDescent<layer::Activation<ValueType, NeuronType, SizeAtCompileTime>> Base; /// Layer type standardization typedef typename layer::Activation<ValueType, NeuronType, SizeAtCompileTime> LayerType; /// Scalar type standardization typedef typename LayerType::ScalarType ScalarType; /// Size type standardization typedef typename LayerType::SizeType SizeType; /// Matrix type standardization typedef typename LayerType::InputVector InputVector; /// Matrix type standardization typedef typename LayerType::OutputVector OutputVector; /// Matrix type standardization typedef typename LayerType::BiasVector BiasVector; /** * @brief Setup constructor * @param lr Learning rate */ explicit Adam(ScalarType lr, ScalarType beta1 = 0.9, ScalarType beta2 = 0.999, ScalarType eps = 1e-8) : Base(lr), beta1_(beta1), beta2_(beta2), epsilon_(eps) { Base::setName("Adam[Activation]"); FFNN_ASSERT_MSG(beta1_ > 0 && beta1_ < 1, "'beta1' should be in the range (0, 1)."); FFNN_ASSERT_MSG(beta2_ > 0 && beta2_ < 1, "'beta2' should be in the range (0, 1)."); FFNN_ASSERT_MSG(epsilon_ > 0, "Epsilon should be > 0."); } virtual ~Adam() {} /** * @brief Initializes the Optimizer * @param[in, out] layer Layer to optimize */ void initialize(LayerType& layer) { Base::initialize(layer); // Reset moment matrices mean_gradient_.setZero(layer.output_dimension_, 1); var_gradient_.setZero(layer.output_dimension_, 1); } /** * @brief Applies optimization update * @param[in, out] layer Layer to optimize * @retval true if optimization update was applied successfully * @retval false otherwise */ bool update(LayerType& layer) { FFNN_ASSERT_MSG(layer.isInitialized(), "Layer to optimize is not initialized."); // Update gradient moments mean_gradient_ += beta1_ * (gradient_ - mean_gradient_); var_gradient_ += beta2_ * (gradient_ - var_gradient_); // Compute learning rates for all weights BiasVector current_gradient = var_gradient_; current_gradient.noalias() /= (1 - beta2_); current_gradient.array() += epsilon_; current_gradient.noalias() = mean_gradient_.array() / current_gradient.array(); current_gradient.noalias() /= (1 - beta1_); current_gradient.noalias() *= Base::lr_; // Update weights layer.b_.noalias() -= current_gradient; // Reinitialize optimizer Base::reset(layer); return true; } private: /// Mean decay rate const ScalarType beta1_; /// Variance decay rate const ScalarType beta2_; /// Variance normalization value const ScalarType epsilon_; /// Running mean of error gradient BiasVector mean_gradient_; /// Uncentered variance of error gradient BiasVector var_gradient_; }; } // namespace optimizer } // namespace ffnn <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik 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 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 General Public License for more details. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ // stl #include <iostream> // qt #include <QtGui> #include <QSplitter> #include <QTreeView> #include <QListView> #include <QTabWidget> #include <QList> #include <QItemDelegate> #include <QSlider> // mapnik #include <mapnik/config_error.hpp> #include <mapnik/load_map.hpp> #include <mapnik/save_map.hpp> // qt #include "mainwindow.hpp" #include "layerlistmodel.hpp" #include "styles_model.hpp" #include "layerwidget.hpp" #include "layerdelegate.hpp" #include "about_dialog.hpp" MainWindow::MainWindow() : filename_(), default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) { mapWidget_ = new MapWidget(this); QSplitter *splitter = new QSplitter(this); QTabWidget *tabWidget=new QTabWidget; layerTab_ = new LayerTab; layerTab_->setFocusPolicy(Qt::NoFocus); layerTab_->setIconSize(QSize(16,16)); //LayerDelegate *delegate = new LayerDelegate(this); //layerTab_->setItemDelegate(delegate); //layerTab_->setItemDelegate(new QItemDelegate(this)); //layerTab_->setViewMode(QListView::IconMode); layerTab_->setFlow(QListView::TopToBottom); tabWidget->addTab(layerTab_,tr("Layers")); // Styles tab styleTab_ = new StyleTab; tabWidget->addTab(styleTab_,tr("Styles")); splitter->addWidget(tabWidget); splitter->addWidget(mapWidget_); QList<int> list; list.push_back(200); list.push_back(600); splitter->setSizes(list); mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocus(); //setCentralWidget(mapWidget_); setCentralWidget(splitter); createActions(); createMenus(); createToolBars(); createContextMenu(); setWindowTitle(tr("Mapnik Viewer")); status=new QStatusBar(this); status->showMessage(tr("")); setStatusBar(status); resize(800,600); //connect mapview to layerlist connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); // slider connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); // connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); connect(layerTab_,SIGNAL(layerSelected(int)), mapWidget_,SLOT(layerSelected(int))); } MainWindow::~MainWindow() { delete mapWidget_; } void MainWindow::closeEvent(QCloseEvent* event) { event->accept(); } void MainWindow::createContextMenu() { layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu); layerTab_->addAction(openAct); layerTab_->addAction(layerInfo); } void MainWindow::open(QString const& path) { if (path.isNull()) { filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), currentPath,"*.xml"); } else { filename_ = path; } if (!filename_.isEmpty()) { load_map_file(filename_); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); } } void MainWindow::reload() { if (!filename_.isEmpty()) { mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent(); load_map_file(filename_); mapWidget_->zoomToBox(bbox); setWindowTitle(tr("%1 - *Reloaded*").arg(filename_)); } } void MainWindow::save() { QString initialPath = QDir::currentPath() + "/untitled.xml"; QString filename = QFileDialog::getSaveFileName(this, tr("Save"), initialPath, tr("%1 Files (*.xml)") .arg(QString("Mapnik definition"))); if (!filename.isEmpty()) { std::cout<<"saving "<< filename.toStdString() << std::endl; mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); } } void MainWindow::load_map_file(QString const& filename) { std::cout<<"loading "<< filename.toStdString() << std::endl; unsigned width = mapWidget_->width(); unsigned height = mapWidget_->height(); boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); mapWidget_->setMap(map); try { mapnik::load_map(*map,filename.toStdString()); } catch (mapnik::config_error & ex) { std::cout << ex.what() << "\n"; } catch (...) { std::cerr << "Exception caught in load_map\n"; } layerTab_->setModel(new LayerListModel(map,this)); styleTab_->setModel(new StyleModel(map,this)); } void MainWindow::zoom_to_box() { mapWidget_->setTool(MapWidget::ZoomToBox); } void MainWindow::pan() { mapWidget_->setTool(MapWidget::Pan); } void MainWindow::info() { mapWidget_->setTool(MapWidget::Info); } void MainWindow::pan_left() { mapWidget_->panLeft(); } void MainWindow::pan_right() { mapWidget_->panRight(); } void MainWindow::pan_up() { mapWidget_->panUp(); } void MainWindow::pan_down() { mapWidget_->panDown(); } void MainWindow::about() { about_dialog dlg; dlg.exec(); } void MainWindow::export_as() { QAction *action = qobject_cast<QAction *>(sender()); QByteArray fileFormat = action->data().toByteArray(); QString initialPath = QDir::currentPath() + "/map." + fileFormat; QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), initialPath, tr("%1 Files (*.%2);;All Files (*)") .arg(QString(fileFormat.toUpper())) .arg(QString(fileFormat))); if (!fileName.isEmpty()) { QPixmap const& pix = mapWidget_->pixmap(); pix.save(fileName); } } void MainWindow::print() { //Q_ASSERT(mapWidget_->pixmap()); //QPrintDialog dialog(&printer, this); //if (dialog.exec()) { // QPainter painter(&printer); // QRect rect = painter.viewport(); // QSize size = mapWidget_->pixmap()->size(); // size.scale(rect.size(), Qt::KeepAspectRatio); // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); // painter.setWindow(mapWidget_->pixmap()->rect()); // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); //} } void MainWindow::createActions() { //exportAct = new QAction(tr("&Export as ..."),this); //exportAct->setShortcut(tr("Ctrl+E")); //connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); zoomBoxAct->setCheckable(true); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); panAct->setCheckable(true); connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); infoAct->setCheckable(true); connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); toolsGroup=new QActionGroup(this); toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(panAct); toolsGroup->addAction(infoAct); zoomBoxAct->setChecked(true); openAct=new QAction(tr("Open Map definition"),this); connect(openAct,SIGNAL(triggered()),this,SLOT(open())); saveAct=new QAction(tr("Save Map definition"),this); connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); connect(action, SIGNAL(triggered()), this, SLOT(export_as())); exportAsActs.append(action); } printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); printAct->setShortcut(tr("Ctrl+E")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { exportMenu = new QMenu(tr("&Export As"), this); foreach (QAction *action, exportAsActs) exportMenu->addAction(action); fileMenu = new QMenu(tr("&File"),this); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addMenu(exportMenu); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); helpMenu = new QMenu(tr("&Help"), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); } void MainWindow::createToolBars() { fileToolBar = addToolBar(tr("Actions")); fileToolBar->addAction(zoomAllAct); fileToolBar->addAction(zoomBoxAct); fileToolBar->addAction(panAct); fileToolBar->addAction(panLeftAct); fileToolBar->addAction(panRightAct); fileToolBar->addAction(panUpAct); fileToolBar->addAction(panDownAct); fileToolBar->addAction(infoAct); fileToolBar->addAction(reloadAct); fileToolBar->addAction(printAct); slider_ = new QSlider(Qt::Horizontal,fileToolBar); slider_->setRange(1,18); slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickInterval(1); slider_->setTracking(false); fileToolBar->addWidget(slider_); fileToolBar->addAction(aboutAct); } void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) { try { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { mapnik::projection prj(map_ptr->srs()); prj.forward(x0,y0); prj.forward(x1,y1); default_extent_=mapnik::box2d<double>(x0,y0,x1,y1); mapWidget_->zoomToBox(default_extent_); std::cout << "SET DEFAULT EXT\n"; } } catch (...) {} } void MainWindow::set_scaling_factor(double scaling_factor) { mapWidget_->set_scaling_factor(scaling_factor); } void MainWindow::zoom_all() { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { map_ptr->zoom_all(); mapnik::box2d<double> const& ext = map_ptr->get_current_extent(); mapWidget_->zoomToBox(ext); } } <commit_msg>viewer: zoom to full extent of map when loading from xml<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik 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 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 General Public License for more details. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ // stl #include <iostream> // qt #include <QtGui> #include <QSplitter> #include <QTreeView> #include <QListView> #include <QTabWidget> #include <QList> #include <QItemDelegate> #include <QSlider> // mapnik #include <mapnik/config_error.hpp> #include <mapnik/load_map.hpp> #include <mapnik/save_map.hpp> // qt #include "mainwindow.hpp" #include "layerlistmodel.hpp" #include "styles_model.hpp" #include "layerwidget.hpp" #include "layerdelegate.hpp" #include "about_dialog.hpp" MainWindow::MainWindow() : filename_(), default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) { mapWidget_ = new MapWidget(this); QSplitter *splitter = new QSplitter(this); QTabWidget *tabWidget=new QTabWidget; layerTab_ = new LayerTab; layerTab_->setFocusPolicy(Qt::NoFocus); layerTab_->setIconSize(QSize(16,16)); //LayerDelegate *delegate = new LayerDelegate(this); //layerTab_->setItemDelegate(delegate); //layerTab_->setItemDelegate(new QItemDelegate(this)); //layerTab_->setViewMode(QListView::IconMode); layerTab_->setFlow(QListView::TopToBottom); tabWidget->addTab(layerTab_,tr("Layers")); // Styles tab styleTab_ = new StyleTab; tabWidget->addTab(styleTab_,tr("Styles")); splitter->addWidget(tabWidget); splitter->addWidget(mapWidget_); QList<int> list; list.push_back(200); list.push_back(600); splitter->setSizes(list); mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocus(); //setCentralWidget(mapWidget_); setCentralWidget(splitter); createActions(); createMenus(); createToolBars(); createContextMenu(); setWindowTitle(tr("Mapnik Viewer")); status=new QStatusBar(this); status->showMessage(tr("")); setStatusBar(status); resize(800,600); //connect mapview to layerlist connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); // slider connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); // connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); connect(layerTab_,SIGNAL(layerSelected(int)), mapWidget_,SLOT(layerSelected(int))); } MainWindow::~MainWindow() { delete mapWidget_; } void MainWindow::closeEvent(QCloseEvent* event) { event->accept(); } void MainWindow::createContextMenu() { layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu); layerTab_->addAction(openAct); layerTab_->addAction(layerInfo); } void MainWindow::open(QString const& path) { if (path.isNull()) { filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), currentPath,"*.xml"); } else { filename_ = path; } if (!filename_.isEmpty()) { load_map_file(filename_); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); } } void MainWindow::reload() { if (!filename_.isEmpty()) { mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent(); load_map_file(filename_); mapWidget_->zoomToBox(bbox); setWindowTitle(tr("%1 - *Reloaded*").arg(filename_)); } } void MainWindow::save() { QString initialPath = QDir::currentPath() + "/untitled.xml"; QString filename = QFileDialog::getSaveFileName(this, tr("Save"), initialPath, tr("%1 Files (*.xml)") .arg(QString("Mapnik definition"))); if (!filename.isEmpty()) { std::cout<<"saving "<< filename.toStdString() << std::endl; mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); } } void MainWindow::load_map_file(QString const& filename) { std::cout<<"loading "<< filename.toStdString() << std::endl; unsigned width = mapWidget_->width(); unsigned height = mapWidget_->height(); boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); mapWidget_->setMap(map); try { mapnik::load_map(*map,filename.toStdString()); } catch (mapnik::config_error & ex) { std::cout << ex.what() << "\n"; } catch (...) { std::cerr << "Exception caught in load_map\n"; } layerTab_->setModel(new LayerListModel(map,this)); styleTab_->setModel(new StyleModel(map,this)); zoom_all(); } void MainWindow::zoom_to_box() { mapWidget_->setTool(MapWidget::ZoomToBox); } void MainWindow::pan() { mapWidget_->setTool(MapWidget::Pan); } void MainWindow::info() { mapWidget_->setTool(MapWidget::Info); } void MainWindow::pan_left() { mapWidget_->panLeft(); } void MainWindow::pan_right() { mapWidget_->panRight(); } void MainWindow::pan_up() { mapWidget_->panUp(); } void MainWindow::pan_down() { mapWidget_->panDown(); } void MainWindow::about() { about_dialog dlg; dlg.exec(); } void MainWindow::export_as() { QAction *action = qobject_cast<QAction *>(sender()); QByteArray fileFormat = action->data().toByteArray(); QString initialPath = QDir::currentPath() + "/map." + fileFormat; QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), initialPath, tr("%1 Files (*.%2);;All Files (*)") .arg(QString(fileFormat.toUpper())) .arg(QString(fileFormat))); if (!fileName.isEmpty()) { QPixmap const& pix = mapWidget_->pixmap(); pix.save(fileName); } } void MainWindow::print() { //Q_ASSERT(mapWidget_->pixmap()); //QPrintDialog dialog(&printer, this); //if (dialog.exec()) { // QPainter painter(&printer); // QRect rect = painter.viewport(); // QSize size = mapWidget_->pixmap()->size(); // size.scale(rect.size(), Qt::KeepAspectRatio); // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); // painter.setWindow(mapWidget_->pixmap()->rect()); // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); //} } void MainWindow::createActions() { //exportAct = new QAction(tr("&Export as ..."),this); //exportAct->setShortcut(tr("Ctrl+E")); //connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); zoomBoxAct->setCheckable(true); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); panAct->setCheckable(true); connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); infoAct->setCheckable(true); connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); toolsGroup=new QActionGroup(this); toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(panAct); toolsGroup->addAction(infoAct); zoomBoxAct->setChecked(true); openAct=new QAction(tr("Open Map definition"),this); connect(openAct,SIGNAL(triggered()),this,SLOT(open())); saveAct=new QAction(tr("Save Map definition"),this); connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); connect(action, SIGNAL(triggered()), this, SLOT(export_as())); exportAsActs.append(action); } printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); printAct->setShortcut(tr("Ctrl+E")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { exportMenu = new QMenu(tr("&Export As"), this); foreach (QAction *action, exportAsActs) exportMenu->addAction(action); fileMenu = new QMenu(tr("&File"),this); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addMenu(exportMenu); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); helpMenu = new QMenu(tr("&Help"), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); } void MainWindow::createToolBars() { fileToolBar = addToolBar(tr("Actions")); fileToolBar->addAction(zoomAllAct); fileToolBar->addAction(zoomBoxAct); fileToolBar->addAction(panAct); fileToolBar->addAction(panLeftAct); fileToolBar->addAction(panRightAct); fileToolBar->addAction(panUpAct); fileToolBar->addAction(panDownAct); fileToolBar->addAction(infoAct); fileToolBar->addAction(reloadAct); fileToolBar->addAction(printAct); slider_ = new QSlider(Qt::Horizontal,fileToolBar); slider_->setRange(1,18); slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickInterval(1); slider_->setTracking(false); fileToolBar->addWidget(slider_); fileToolBar->addAction(aboutAct); } void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) { try { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { mapnik::projection prj(map_ptr->srs()); prj.forward(x0,y0); prj.forward(x1,y1); default_extent_=mapnik::box2d<double>(x0,y0,x1,y1); mapWidget_->zoomToBox(default_extent_); std::cout << "SET DEFAULT EXT\n"; } } catch (...) {} } void MainWindow::set_scaling_factor(double scaling_factor) { mapWidget_->set_scaling_factor(scaling_factor); } void MainWindow::zoom_all() { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { map_ptr->zoom_all(); mapnik::box2d<double> const& ext = map_ptr->get_current_extent(); mapWidget_->zoomToBox(ext); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <helper/propertysetcontainer.hxx> #include <threadhelp/resetableguard.hxx> #include <vcl/svapp.hxx> #define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!" using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace framework { PropertySetContainer::PropertySetContainer() : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject() { } PropertySetContainer::~PropertySetContainer() { } // XInterface void SAL_CALL PropertySetContainer::acquire() throw () { OWeakObject::acquire(); } void SAL_CALL PropertySetContainer::release() throw () { OWeakObject::release(); } Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( rType , (static_cast< XIndexContainer* >(this)), (static_cast< XIndexReplace* >(this)), (static_cast< XIndexAccess* >(this)), (static_cast< XElementAccess* >(this)) ); if( a.hasValue() ) { return a; } return OWeakObject::queryInterface( rType ); } // XIndexContainer void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); sal_Int32 nSize = m_aPropertySetVector.size(); if ( nSize >= Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { if ( nSize == Index ) m_aPropertySetVector.push_back( aPropertySetElement ); else { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.insert( aIter, aPropertySetElement ); } } else { throw IllegalArgumentException( OUString( WRONG_TYPE_EXCEPTION ), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.erase( aIter ); } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexReplace void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException) { if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { m_aPropertySetVector[ Index ] = aPropertySetElement; } else { throw IllegalArgumentException( OUString( WRONG_TYPE_EXCEPTION ), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexAccess sal_Int32 SAL_CALL PropertySetContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); return m_aPropertySetVector.size(); } Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Any a; a <<= m_aPropertySetVector[ Index ]; return a; } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XElementAccess sal_Bool SAL_CALL PropertySetContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aGuard( m_aLock ); return !( m_aPropertySetVector.empty() ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Bin intermediate iterator + rename parameter function<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <helper/propertysetcontainer.hxx> #include <threadhelp/resetableguard.hxx> #include <vcl/svapp.hxx> #define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!" using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace framework { PropertySetContainer::PropertySetContainer() : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject() { } PropertySetContainer::~PropertySetContainer() { } // XInterface void SAL_CALL PropertySetContainer::acquire() throw () { OWeakObject::acquire(); } void SAL_CALL PropertySetContainer::release() throw () { OWeakObject::release(); } Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( rType , (static_cast< XIndexContainer* >(this)), (static_cast< XIndexReplace* >(this)), (static_cast< XIndexAccess* >(this)), (static_cast< XElementAccess* >(this)) ); if( a.hasValue() ) { return a; } return OWeakObject::queryInterface( rType ); } // XIndexContainer void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); sal_Int32 nSize = m_aPropertySetVector.size(); if ( nSize >= Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { if ( nSize == Index ) m_aPropertySetVector.push_back( aPropertySetElement ); else { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.insert( aIter, aPropertySetElement ); } } else { throw IllegalArgumentException( OUString( WRONG_TYPE_EXCEPTION ), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 nIndex ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > nIndex ) { m_aPropertySetVector.erase(m_aPropertySetVector.begin() + nIndex); } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexReplace void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException) { if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { m_aPropertySetVector[ Index ] = aPropertySetElement; } else { throw IllegalArgumentException( OUString( WRONG_TYPE_EXCEPTION ), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexAccess sal_Int32 SAL_CALL PropertySetContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); return m_aPropertySetVector.size(); } Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Any a; a <<= m_aPropertySetVector[ Index ]; return a; } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XElementAccess sal_Bool SAL_CALL PropertySetContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aGuard( m_aLock ); return !( m_aPropertySetVector.empty() ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <nan.h> #include <node.h> #include <string> #include <cstring> #include "../include/str_array_converter.h" #include "git2/strarray.h" using namespace v8; using namespace node; git_strarray *StrArrayConverter::Convert(Local<v8::Value> val) { if (!Nan::To<bool>(val).FromJust()) { return NULL; } else if (val->IsArray()) { return ConvertArray(Array::Cast(*val)); } else if (val->IsString() || val->IsStringObject()) { return ConvertString(Nan::To<v8::String>(val).ToLocalChecked()); } else { return NULL; } } git_strarray * StrArrayConverter::AllocStrArray(const size_t count) { const size_t size = sizeof(git_strarray) + (sizeof(char*) * count); uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size)); git_strarray *result = reinterpret_cast<git_strarray *>(memory); result->count = count; result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray)); return result; } git_strarray *StrArrayConverter::ConvertArray(Array *val) { git_strarray *result = AllocStrArray(val->Length()); for(size_t i = 0; i < result->count; i++) { Nan::Utf8String entry(val->Get(i)); result->strings[i] = strdup(*entry); } return result; } git_strarray* StrArrayConverter::ConvertString(Local<String> val) { char *strings[1]; Nan::Utf8String utf8String(val); strings[0] = *utf8String; return ConstructStrArray(1, strings); } git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) { git_strarray *result = AllocStrArray(argc); for(size_t i = 0; i < result->count; i++) { result->strings[i] = strdup(argv[i]); } return result; } <commit_msg>:art: Final spacing amends for manual str_array_converter<commit_after>#include <nan.h> #include <node.h> #include <string> #include <cstring> #include "../include/str_array_converter.h" #include "git2/strarray.h" using namespace v8; using namespace node; git_strarray *StrArrayConverter::Convert(Local<v8::Value> val) { if (!Nan::To<bool>(val).FromJust()) { return NULL; } else if (val->IsArray()) { return ConvertArray(Array::Cast(*val)); } else if (val->IsString() || val->IsStringObject()) { return ConvertString(Nan::To<v8::String>(val).ToLocalChecked()); } else { return NULL; } } git_strarray * StrArrayConverter::AllocStrArray(const size_t count) { const size_t size = sizeof(git_strarray) + (sizeof(char*) * count); uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size)); git_strarray *result = reinterpret_cast<git_strarray *>(memory); result->count = count; result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray)); return result; } git_strarray *StrArrayConverter::ConvertArray(Array *val) { git_strarray *result = AllocStrArray(val->Length()); for(size_t i = 0; i < result->count; i++) { Nan::Utf8String entry(val->Get(i)); result->strings[i] = strdup(*entry); } return result; } git_strarray* StrArrayConverter::ConvertString(Local<String> val) { char *strings[1]; Nan::Utf8String utf8String(val); strings[0] = *utf8String; return ConstructStrArray(1, strings); } git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) { git_strarray *result = AllocStrArray(argc); for(size_t i = 0; i < result->count; i++) { result->strings[i] = strdup(argv[i]); } return result; } <|endoftext|>
<commit_before>/******************************************************************************/ /** @file @author Scott Fazackerley @brief Wraps the Arduino Serial object and provides a simple printf implementation for C. @copyright Copyright 2016 The University of British Columbia, IonDB Project Contributors (see AUTHORS.md) @par 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 @par 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 "serial_c_iface.h" int serial_printf_c( const char *format, ... ) { va_list args; va_start(args, format); int bufsize = vsnprintf(NULL, 0, format, args); char buf[bufsize]; va_end(args); va_start(args); vsnprintf(buf, bufsize, format, args); va_end(args); return serial_print(buf); } int serial_print( const char *buffer ) { int num; num = Serial.print(buffer); #if DEBUG Serial.flush(); #endif return num; } void serial_init( int baud_rate ) { Serial.begin(baud_rate); } void serial_close( ) { Serial.end(); } <commit_msg>Fix missing param in va_start<commit_after>/******************************************************************************/ /** @file @author Scott Fazackerley @brief Wraps the Arduino Serial object and provides a simple printf implementation for C. @copyright Copyright 2016 The University of British Columbia, IonDB Project Contributors (see AUTHORS.md) @par 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 @par 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 "serial_c_iface.h" int serial_printf_c( const char *format, ... ) { va_list args; va_start(args, format); int bufsize = vsnprintf(NULL, 0, format, args); char buf[bufsize]; va_end(args); va_start(args, format); vsnprintf(buf, bufsize, format, args); va_end(args); return serial_print(buf); } int serial_print( const char *buffer ) { int num; num = Serial.print(buffer); #if DEBUG Serial.flush(); #endif return num; } void serial_init( int baud_rate ) { Serial.begin(baud_rate); } void serial_close( ) { Serial.end(); } <|endoftext|>
<commit_before>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen 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 any later version. Ingen 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 details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <poll.h> #include <sstream> #include <thread> #include "ingen/Configuration.hpp" #include "ingen/Module.hpp" #include "ingen/World.hpp" #include "raul/Socket.hpp" #include "../server/Engine.hpp" #include "../server/EventWriter.hpp" #include "SocketListener.hpp" #include "SocketServer.hpp" namespace Ingen { namespace Server { void SocketListener::ingen_listen(Engine* engine, Raul::Socket* unix_sock, Raul::Socket* net_sock) { Ingen::World* world = engine->world(); const std::string unix_path(world->conf().option("socket").ptr<char>()); // Bind UNIX socket const Raul::URI unix_uri(unix_scheme + unix_path); if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) { world->log().error("Failed to create UNIX socket\n"); unix_sock->close(); } else { world->log().info(fmt("Listening on socket %1%\n") % unix_uri); } // Bind TCP socket const int port = world->conf().option("engine-port").get<int32_t>(); std::ostringstream ss; ss << "tcp://*:" << port; if (!net_sock->bind(Raul::URI(ss.str())) || !net_sock->listen()) { world->log().error("Failed to create TCP socket\n"); net_sock->close(); } else { world->log().info(fmt("Listening on TCP port %1%\n") % port); } if (unix_sock->fd() == -1 && net_sock->fd() == -1) { return; // No sockets to listen to, exit thread } struct pollfd pfds[2]; int nfds = 0; if (unix_sock->fd() != -1) { pfds[nfds].fd = unix_sock->fd(); pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; ++nfds; } if (net_sock->fd() != -1) { pfds[nfds].fd = net_sock->fd(); pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; ++nfds; } while (true) { // Wait for input to arrive at a socket const int ret = poll(pfds, nfds, -1); if (ret == -1) { world->log().error(fmt("Poll error: %1%\n") % strerror(errno)); break; } else if (ret == 0) { world->log().warn("Poll returned with no data\n"); continue; } else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) { break; } if (pfds[0].revents & POLLIN) { SPtr<Raul::Socket> conn = unix_sock->accept(); if (conn) { new SocketServer(*world, *engine, conn); } } if (pfds[1].revents & POLLIN) { SPtr<Raul::Socket> conn = net_sock->accept(); if (conn) { new SocketServer(*world, *engine, conn); } } } } } // namespace Server } // namespace Ingen <commit_msg>Gracefully handle UNIX socket after a crash<commit_after>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen 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 any later version. Ingen 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 details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <poll.h> #include <signal.h> #include <sys/stat.h> #include <unistd.h> #include <sstream> #include <string> #include <thread> #include "ingen/Configuration.hpp" #include "ingen/Module.hpp" #include "ingen/World.hpp" #include "raul/Socket.hpp" #include "../server/Engine.hpp" #include "../server/EventWriter.hpp" #include "SocketListener.hpp" #include "SocketServer.hpp" namespace Ingen { namespace Server { static std::string get_link_target(const char* link_path) { // Stat the link to get the required size for the target path struct stat link_stat; if (lstat(link_path, &link_stat)) { return std::string(); } // Allocate buffer and read link target char* target = (char*)calloc(1, link_stat.st_size + 1); if (readlink(link_path, target, link_stat.st_size) != -1) { const std::string result(target); free(target); return result; } return std::string(); } void SocketListener::ingen_listen(Engine* engine, Raul::Socket* unix_sock, Raul::Socket* net_sock) { Ingen::World* world = engine->world(); const std::string link_path(world->conf().option("socket").ptr<char>()); const std::string unix_path(link_path + "." + std::to_string(getpid())); // Bind UNIX socket and create PID-less symbolic link const Raul::URI unix_uri(unix_scheme + unix_path); bool make_link = true; if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) { world->log().error("Failed to create UNIX socket\n"); unix_sock->close(); make_link = false; } else { const std::string old_path = get_link_target(link_path.c_str()); if (!old_path.empty()) { const std::string suffix = old_path.substr(old_path.find_last_of(".") + 1); const pid_t pid = std::stoi(suffix); if (!kill(pid, 0)) { make_link = false; world->log().warn(fmt("Another Ingen instance is running at %1% => %2%\n") % link_path % old_path); } else { world->log().warn(fmt("Replacing old link %1% => %2%\n") % link_path % old_path); unlink(link_path.c_str()); } } if (make_link) { if (!symlink(unix_path.c_str(), link_path.c_str())) { world->log().info(fmt("Listening on %1%\n") % (unix_scheme + link_path)); } else { world->log().error(fmt("Failed to link %1% => %2% (%3%)\n") % link_path % unix_path % strerror(errno)); } } else { world->log().info(fmt("Listening on %1%\n") % unix_uri); } } // Bind TCP socket const int port = world->conf().option("engine-port").get<int32_t>(); std::ostringstream ss; ss << "tcp://*:" << port; if (!net_sock->bind(Raul::URI(ss.str())) || !net_sock->listen()) { world->log().error("Failed to create TCP socket\n"); net_sock->close(); } else { world->log().info(fmt("Listening on TCP port %1%\n") % port); } if (unix_sock->fd() == -1 && net_sock->fd() == -1) { return; // No sockets to listen to, exit thread } struct pollfd pfds[2]; int nfds = 0; if (unix_sock->fd() != -1) { pfds[nfds].fd = unix_sock->fd(); pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; ++nfds; } if (net_sock->fd() != -1) { pfds[nfds].fd = net_sock->fd(); pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; ++nfds; } while (true) { // Wait for input to arrive at a socket const int ret = poll(pfds, nfds, -1); if (ret == -1) { world->log().error(fmt("Poll error: %1%\n") % strerror(errno)); break; } else if (ret == 0) { world->log().warn("Poll returned with no data\n"); continue; } else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) { break; } if (pfds[0].revents & POLLIN) { SPtr<Raul::Socket> conn = unix_sock->accept(); if (conn) { new SocketServer(*world, *engine, conn); } } if (pfds[1].revents & POLLIN) { SPtr<Raul::Socket> conn = net_sock->accept(); if (conn) { new SocketServer(*world, *engine, conn); } } } if (make_link) { unlink(link_path.c_str()); } } } // namespace Server } // namespace Ingen <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file workarounds/dp16.H /// @brief Workarounds for the DP16 logic blocks /// Workarounds are very deivce specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Steven Glancy <sglancy@usi.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_WORKAROUNDS_DP16_H_ #define _MSS_WORKAROUNDS_DP16_H_ #include <fapi2.H> namespace mss { namespace workarounds { namespace dp16 { /// /// @brief DQS polarity workaround /// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6 /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// @note This function is called during the phy scom init procedure, after the initfile is /// processed. It is specific to the Monza module, but can be called for all modules as it /// will enforce its requirements internally /// fapi2::ReturnCode dqs_polarity( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief DP16 Read Diagnostic Configuration 5 work around /// Not in the Model 67 spydef, so we scom them. Should be removed when they are /// added to the spydef. /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode rd_dia_config5( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief DP16 DQSCLK Offset work around /// Not in the Model 67 spydef, so we scom them. Should be removed when they are /// added to the spydef. /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode dqsclk_offset( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); } // close namespace dp16 } // close namespace workarounds } // close namespace mss #endif <commit_msg>Added WR VREF workaround for error logic<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file workarounds/dp16.H /// @brief Workarounds for the DP16 logic blocks /// Workarounds are very deivce specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_WORKAROUNDS_DP16_H_ #define _MSS_WORKAROUNDS_DP16_H_ #include <fapi2.H> namespace mss { namespace workarounds { namespace dp16 { /// /// @brief DQS polarity workaround /// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6 /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// @note This function is called during the phy scom init procedure, after the initfile is /// processed. It is specific to the Monza module, but can be called for all modules as it /// will enforce its requirements internally /// fapi2::ReturnCode dqs_polarity( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief DP16 Read Diagnostic Configuration 5 work around /// Not in the Model 67 spydef, so we scom them. Should be removed when they are /// added to the spydef. /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode rd_dia_config5( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief DP16 DQSCLK Offset work around /// Not in the Model 67 spydef, so we scom them. Should be removed when they are /// added to the spydef. /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode dqsclk_offset( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); namespace wr_vref { /// /// @brief DP16 WR VREF error latching workaround /// In DD1 Nimbus in the WR VREF algorithm ,DRAM's 2/3 latch over error information from DRAM's 0/1. /// The workaround is to set the error mask for DRAM's 2/3 to be 0xFFFF (informational but not errors) /// @param[in] i_target the fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode error_dram23( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); } // close namespace wr_vref } // close namespace dp16 } // close namespace workarounds } // close namespace mss #endif <|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 "media/base/video_frame_impl.h" #include "media/filters/ffmpeg_common.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/ffmpeg_video_decoder.h" namespace media { FFmpegVideoDecoder::FFmpegVideoDecoder() : DecoderBase<VideoDecoder, VideoFrame>(NULL), width_(0), height_(0) { } FFmpegVideoDecoder::~FFmpegVideoDecoder() { } // static bool FFmpegVideoDecoder::IsMediaFormatSupported(const MediaFormat& format) { std::string mime_type; return format.GetAsString(MediaFormat::kMimeType, &mime_type) && mime_type::kFFmpegVideo == mime_type; } bool FFmpegVideoDecoder::OnInitialize(DemuxerStream* demuxer_stream) { scoped_refptr<FFmpegDemuxerStream> ffmpeg_demuxer_stream; if (!demuxer_stream->QueryInterface(&ffmpeg_demuxer_stream)) { return false; } AVStream* av_stream = ffmpeg_demuxer_stream->av_stream(); width_ = av_stream->codec->width; height_ = av_stream->codec->height; media_format_.SetAsString(MediaFormat::kMimeType, mime_type::kUncompressedVideo); media_format_.SetAsInteger(MediaFormat::kWidth, width_); media_format_.SetAsInteger(MediaFormat::kHeight, height_); codec_context_ = ffmpeg_demuxer_stream->av_stream()->codec; codec_context_->flags2 |= CODEC_FLAG2_FAST; // Enable faster H264 decode. AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); if (!codec || avcodec_open(codec_context_, codec) < 0) { host_->Error(media::PIPELINE_ERROR_DECODE); return false; } return true; } void FFmpegVideoDecoder::OnDecode(Buffer* buffer) { // Check for end of stream. // TODO(scherkus): check for end of stream. // Queue the incoming timestamp. TimeTuple times; times.timestamp = buffer->GetTimestamp(); times.duration = buffer->GetDuration(); time_queue_.push(times); // Cast everything to FFmpeg types. const uint8_t* data_in = buffer->GetData(); const size_t size_in = buffer->GetDataSize(); // We don't allocate AVFrame on the stack since different versions of FFmpeg // may change the size of AVFrame, causing stack corruption. The solution is // to let FFmpeg allocate the structure via avcodec_alloc_frame(). int decoded = 0; scoped_ptr_malloc<AVFrame, ScopedPtrAVFree> yuv_frame(avcodec_alloc_frame()); int result = avcodec_decode_video(codec_context_, yuv_frame.get(), &decoded, data_in, size_in); if (result < 0) { host_->Error(PIPELINE_ERROR_DECODE); return; } if (result == 0 || decoded == 0) { return; } // J (Motion JPEG) versions of YUV are full range 0..255. // Regular (MPEG) YUV is 16..240. // For now we will ignore the distinction and treat them the same. VideoSurface::Format surface_format; switch (codec_context_->pix_fmt) { case PIX_FMT_YUV420P: case PIX_FMT_YUVJ420P: surface_format = VideoSurface::YV12; break; case PIX_FMT_YUV422P: case PIX_FMT_YUVJ422P: surface_format = VideoSurface::YV16; break; default: // TODO(scherkus): More formats here? NOTREACHED(); host_->Error(PIPELINE_ERROR_DECODE); return; } if (!EnqueueVideoFrame(surface_format, yuv_frame.get())) { host_->Error(PIPELINE_ERROR_DECODE); } } bool FFmpegVideoDecoder::EnqueueVideoFrame(VideoSurface::Format surface_format, const AVFrame* frame) { // Dequeue the next time tuple and create a VideoFrame object with // that timestamp and duration. TimeTuple time = time_queue_.top(); time_queue_.pop(); scoped_refptr<VideoFrame> video_frame; VideoFrameImpl::CreateFrame(surface_format, width_, height_, time.timestamp, time.duration, &video_frame); if (!video_frame) { return false; } // Copy the frame data since FFmpeg reuses internal buffers for AVFrame // output, meaning the data is only valid until the next // avcodec_decode_video() call. // TODO(scherkus): figure out pre-allocation/buffer cycling scheme. // TODO(scherkus): is there a cleaner way to figure out the # of planes? VideoSurface surface; if (!video_frame->Lock(&surface)) { return false; } CopyPlane(VideoSurface::kYPlane, surface, frame); CopyPlane(VideoSurface::kUPlane, surface, frame); CopyPlane(VideoSurface::kVPlane, surface, frame); video_frame->Unlock(); EnqueueResult(video_frame); return true; } void FFmpegVideoDecoder::CopyPlane(size_t plane, const VideoSurface& surface, const AVFrame* frame) { DCHECK(surface.width % 4 == 0); DCHECK(surface.height % 2 == 0); const uint8* source = frame->data[plane]; const size_t source_stride = frame->linesize[plane]; uint8* dest = surface.data[plane]; const size_t dest_stride = surface.strides[plane]; size_t bytes_per_line = surface.width; size_t copy_lines = surface.height; if (plane != VideoSurface::kYPlane) { bytes_per_line /= 2; if (surface.format == VideoSurface::YV12) { copy_lines /= 2; } } DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride); for (size_t i = 0; i < copy_lines; ++i) { memcpy(dest, source, bytes_per_line); source += source_stride; dest += dest_stride; } } } // namespace <commit_msg>Reduce ffmpeg alignment requirement from 4x2 to 2x1. The multiple of 4 restriction on width is unnecessary and prevents some valid movies from playing. Height being any size does not cause any problems for YV12, which is half height on chroma, as long as you round up in any calcs, and in YV16 there should be no height constraint. Use uluh.mov in debug mode to test.<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 "media/base/video_frame_impl.h" #include "media/filters/ffmpeg_common.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/ffmpeg_video_decoder.h" namespace media { FFmpegVideoDecoder::FFmpegVideoDecoder() : DecoderBase<VideoDecoder, VideoFrame>(NULL), width_(0), height_(0) { } FFmpegVideoDecoder::~FFmpegVideoDecoder() { } // static bool FFmpegVideoDecoder::IsMediaFormatSupported(const MediaFormat& format) { std::string mime_type; return format.GetAsString(MediaFormat::kMimeType, &mime_type) && mime_type::kFFmpegVideo == mime_type; } bool FFmpegVideoDecoder::OnInitialize(DemuxerStream* demuxer_stream) { scoped_refptr<FFmpegDemuxerStream> ffmpeg_demuxer_stream; if (!demuxer_stream->QueryInterface(&ffmpeg_demuxer_stream)) { return false; } AVStream* av_stream = ffmpeg_demuxer_stream->av_stream(); width_ = av_stream->codec->width; height_ = av_stream->codec->height; media_format_.SetAsString(MediaFormat::kMimeType, mime_type::kUncompressedVideo); media_format_.SetAsInteger(MediaFormat::kWidth, width_); media_format_.SetAsInteger(MediaFormat::kHeight, height_); codec_context_ = ffmpeg_demuxer_stream->av_stream()->codec; codec_context_->flags2 |= CODEC_FLAG2_FAST; // Enable faster H264 decode. AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); if (!codec || avcodec_open(codec_context_, codec) < 0) { host_->Error(media::PIPELINE_ERROR_DECODE); return false; } return true; } void FFmpegVideoDecoder::OnDecode(Buffer* buffer) { // Check for end of stream. // TODO(scherkus): check for end of stream. // Queue the incoming timestamp. TimeTuple times; times.timestamp = buffer->GetTimestamp(); times.duration = buffer->GetDuration(); time_queue_.push(times); // Cast everything to FFmpeg types. const uint8_t* data_in = buffer->GetData(); const size_t size_in = buffer->GetDataSize(); // We don't allocate AVFrame on the stack since different versions of FFmpeg // may change the size of AVFrame, causing stack corruption. The solution is // to let FFmpeg allocate the structure via avcodec_alloc_frame(). int decoded = 0; scoped_ptr_malloc<AVFrame, ScopedPtrAVFree> yuv_frame(avcodec_alloc_frame()); int result = avcodec_decode_video(codec_context_, yuv_frame.get(), &decoded, data_in, size_in); if (result < 0) { host_->Error(PIPELINE_ERROR_DECODE); return; } if (result == 0 || decoded == 0) { return; } // J (Motion JPEG) versions of YUV are full range 0..255. // Regular (MPEG) YUV is 16..240. // For now we will ignore the distinction and treat them the same. VideoSurface::Format surface_format; switch (codec_context_->pix_fmt) { case PIX_FMT_YUV420P: case PIX_FMT_YUVJ420P: surface_format = VideoSurface::YV12; break; case PIX_FMT_YUV422P: case PIX_FMT_YUVJ422P: surface_format = VideoSurface::YV16; break; default: // TODO(scherkus): More formats here? NOTREACHED(); host_->Error(PIPELINE_ERROR_DECODE); return; } if (!EnqueueVideoFrame(surface_format, yuv_frame.get())) { host_->Error(PIPELINE_ERROR_DECODE); } } bool FFmpegVideoDecoder::EnqueueVideoFrame(VideoSurface::Format surface_format, const AVFrame* frame) { // Dequeue the next time tuple and create a VideoFrame object with // that timestamp and duration. TimeTuple time = time_queue_.top(); time_queue_.pop(); scoped_refptr<VideoFrame> video_frame; VideoFrameImpl::CreateFrame(surface_format, width_, height_, time.timestamp, time.duration, &video_frame); if (!video_frame) { return false; } // Copy the frame data since FFmpeg reuses internal buffers for AVFrame // output, meaning the data is only valid until the next // avcodec_decode_video() call. // TODO(scherkus): figure out pre-allocation/buffer cycling scheme. // TODO(scherkus): is there a cleaner way to figure out the # of planes? VideoSurface surface; if (!video_frame->Lock(&surface)) { return false; } CopyPlane(VideoSurface::kYPlane, surface, frame); CopyPlane(VideoSurface::kUPlane, surface, frame); CopyPlane(VideoSurface::kVPlane, surface, frame); video_frame->Unlock(); EnqueueResult(video_frame); return true; } void FFmpegVideoDecoder::CopyPlane(size_t plane, const VideoSurface& surface, const AVFrame* frame) { DCHECK(surface.width % 2 == 0); const uint8* source = frame->data[plane]; const size_t source_stride = frame->linesize[plane]; uint8* dest = surface.data[plane]; const size_t dest_stride = surface.strides[plane]; size_t bytes_per_line = surface.width; size_t copy_lines = surface.height; if (plane != VideoSurface::kYPlane) { bytes_per_line /= 2; if (surface.format == VideoSurface::YV12) { copy_lines = (copy_lines + 1) / 2; } } DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride); for (size_t i = 0; i < copy_lines; ++i) { memcpy(dest, source, bytes_per_line); source += source_stride; dest += dest_stride; } } } // namespace <|endoftext|>
<commit_before>#include <assert.h> #include <mutex> #include <chrono> #include <thread> #include <mutex> #include <condition_variable> #include "core.hpp" #include "audio.hpp" #include "dsp/samplerate.hpp" #include "dsp/ringbuffer.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsuggest-override" #include <RtAudio.h> #pragma GCC diagnostic pop #define OUTPUTS 8 #define INPUTS 8 static const auto audioTimeout = std::chrono::milliseconds(100); using namespace rack; struct AudioInterfaceIO : AudioIO { std::mutex engineMutex; std::condition_variable engineCv; std::mutex audioMutex; std::condition_variable audioCv; // Audio thread produces, engine thread consumes DoubleRingBuffer<Frame<INPUTS>, (1<<15)> inputBuffer; // Audio thread consumes, engine thread produces DoubleRingBuffer<Frame<OUTPUTS>, (1<<15)> outputBuffer; AudioInterfaceIO() { } ~AudioInterfaceIO() { // Close stream here before destructing AudioInterfaceIO, so the mutexes are still valid when waiting to close. setDevice(-1, 0); } void processStream(const float *input, float *output, int length) override { if (numInputs > 0) { // TODO Do we need to wait on the input to be consumed here? Experimentally, it works fine if we don't. for (int i = 0; i < length; i++) { if (inputBuffer.full()) break; Frame<INPUTS> f; memset(&f, 0, sizeof(f)); memcpy(&f, &input[numInputs * i], numInputs * sizeof(float)); inputBuffer.push(f); } } if (numOutputs > 0) { std::unique_lock<std::mutex> lock(audioMutex); auto cond = [&] { return outputBuffer.size() >= length; }; if (audioCv.wait_for(lock, audioTimeout, cond)) { // Consume audio block for (int i = 0; i < length; i++) { Frame<OUTPUTS> f = outputBuffer.shift(); memcpy(&output[numOutputs * i], &f, numOutputs * sizeof(float)); } } else { // Timed out, fill output with zeros memset(output, 0, length * numOutputs * sizeof(float)); } } // Notify engine when finished processing engineCv.notify_all(); } void onCloseStream() override { inputBuffer.clear(); outputBuffer.clear(); } }; struct AudioInterface : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { ENUMS(AUDIO_INPUT, INPUTS), NUM_INPUTS }; enum OutputIds { ENUMS(AUDIO_OUTPUT, OUTPUTS), NUM_OUTPUTS }; enum LightIds { ENUMS(INPUT_LIGHT, INPUTS / 2), ENUMS(OUTPUT_LIGHT, OUTPUTS / 2), NUM_LIGHTS }; AudioInterfaceIO audioIO; int lastSampleRate = 0; SampleRateConverter<INPUTS> inputSrc; SampleRateConverter<OUTPUTS> outputSrc; // in rack's sample rate DoubleRingBuffer<Frame<INPUTS>, 16> inputBuffer; DoubleRingBuffer<Frame<OUTPUTS>, 16> outputBuffer; AudioInterface() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) { onSampleRateChange(); } void step() override; json_t *toJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "audio", audioIO.toJson()); return rootJ; } void fromJson(json_t *rootJ) override { json_t *audioJ = json_object_get(rootJ, "audio"); audioIO.fromJson(audioJ); } void onSampleRateChange() override { // for (int i = 0; i < INPUTS; i++) { // inputSrc[i].setRates(audioIO.sampleRate, engineGetSampleRate()); // } // for (int i = 0; i < OUTPUTS; i++) { // outputSrc[i].setRates(engineGetSampleRate(), audioIO.sampleRate); // } inputSrc.setRates(audioIO.sampleRate, engineGetSampleRate()); outputSrc.setRates(engineGetSampleRate(), audioIO.sampleRate); } void onReset() override { audioIO.setDevice(-1, 0); } }; void AudioInterface::step() { Frame<INPUTS> inputFrame; memset(&inputFrame, 0, sizeof(inputFrame)); // Update sample rate if changed by audio driver if (audioIO.sampleRate != lastSampleRate) { onSampleRateChange(); lastSampleRate = audioIO.sampleRate; } if (audioIO.numInputs > 0) { if (inputBuffer.empty()) { int inLen = audioIO.inputBuffer.size(); int outLen = inputBuffer.capacity(); inputSrc.process(audioIO.inputBuffer.startData(), &inLen, inputBuffer.endData(), &outLen); audioIO.inputBuffer.startIncr(inLen); inputBuffer.endIncr(outLen); } } if (!inputBuffer.empty()) { inputFrame = inputBuffer.shift(); } for (int i = 0; i < INPUTS; i++) { outputs[AUDIO_OUTPUT + i].value = 10.0 * inputFrame.samples[i]; } if (audioIO.numOutputs > 0) { // Get and push output SRC frame if (!outputBuffer.full()) { Frame<OUTPUTS> f; for (int i = 0; i < audioIO.numOutputs; i++) { f.samples[i] = inputs[AUDIO_INPUT + i].value / 10.0; } outputBuffer.push(f); } if (outputBuffer.full()) { // Wait until outputs are needed std::unique_lock<std::mutex> lock(audioIO.engineMutex); auto cond = [&] { return audioIO.outputBuffer.size() < audioIO.blockSize; }; if (audioIO.engineCv.wait_for(lock, audioTimeout, cond)) { // Push converted output int inLen = outputBuffer.size(); int outLen = audioIO.outputBuffer.capacity(); outputSrc.process(outputBuffer.startData(), &inLen, audioIO.outputBuffer.endData(), &outLen); outputBuffer.startIncr(inLen); audioIO.outputBuffer.endIncr(outLen); } else { // Give up on pushing output } } } for (int i = 0; i < INPUTS / 2; i++) lights[INPUT_LIGHT + i].value = (audioIO.numInputs >= 2*i+1); for (int i = 0; i < OUTPUTS / 2; i++) lights[OUTPUT_LIGHT + i].value = (audioIO.numOutputs >= 2*i+1); audioIO.audioCv.notify_all(); } struct AudioInterfaceWidget : ModuleWidget { AudioInterfaceWidget(AudioInterface *module) : ModuleWidget(module) { setPanel(SVG::load(assetGlobal("res/Core/AudioInterface.svg"))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addInput(Port::create<PJ301MPort>(mm2px(Vec(3.7069211, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 0)); addInput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 1)); addInput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 2)); addInput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 3)); addInput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 4)); addInput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 5)); addInput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 6)); addInput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 7)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 0)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 1)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 2)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 3)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 4)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 5)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 6)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(38.506523, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 7)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 54.577202)), module, AudioInterface::INPUT_LIGHT + 0)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 54.577202)), module, AudioInterface::INPUT_LIGHT + 1)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 69.158226)), module, AudioInterface::INPUT_LIGHT + 2)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 69.158226)), module, AudioInterface::INPUT_LIGHT + 3)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 91.147583)), module, AudioInterface::OUTPUT_LIGHT + 0)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 91.147583)), module, AudioInterface::OUTPUT_LIGHT + 1)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 107.17003)), module, AudioInterface::OUTPUT_LIGHT + 2)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 107.17003)), module, AudioInterface::OUTPUT_LIGHT + 3)); AudioWidget *audioWidget = Widget::create<AudioWidget>(mm2px(Vec(3.2122073, 14.837339))); audioWidget->box.size = mm2px(Vec(44, 28)); audioWidget->audioIO = &module->audioIO; addChild(audioWidget); } }; Model *modelAudioInterface = Model::create<AudioInterface, AudioInterfaceWidget>("Core", "AudioInterface", "Audio", EXTERNAL_TAG);<commit_msg>Swap input/output LEDs in Audio Interface<commit_after>#include <assert.h> #include <mutex> #include <chrono> #include <thread> #include <mutex> #include <condition_variable> #include "core.hpp" #include "audio.hpp" #include "dsp/samplerate.hpp" #include "dsp/ringbuffer.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsuggest-override" #include <RtAudio.h> #pragma GCC diagnostic pop #define OUTPUTS 8 #define INPUTS 8 static const auto audioTimeout = std::chrono::milliseconds(100); using namespace rack; struct AudioInterfaceIO : AudioIO { std::mutex engineMutex; std::condition_variable engineCv; std::mutex audioMutex; std::condition_variable audioCv; // Audio thread produces, engine thread consumes DoubleRingBuffer<Frame<INPUTS>, (1<<15)> inputBuffer; // Audio thread consumes, engine thread produces DoubleRingBuffer<Frame<OUTPUTS>, (1<<15)> outputBuffer; AudioInterfaceIO() { } ~AudioInterfaceIO() { // Close stream here before destructing AudioInterfaceIO, so the mutexes are still valid when waiting to close. setDevice(-1, 0); } void processStream(const float *input, float *output, int length) override { if (numInputs > 0) { // TODO Do we need to wait on the input to be consumed here? Experimentally, it works fine if we don't. for (int i = 0; i < length; i++) { if (inputBuffer.full()) break; Frame<INPUTS> f; memset(&f, 0, sizeof(f)); memcpy(&f, &input[numInputs * i], numInputs * sizeof(float)); inputBuffer.push(f); } } if (numOutputs > 0) { std::unique_lock<std::mutex> lock(audioMutex); auto cond = [&] { return outputBuffer.size() >= length; }; if (audioCv.wait_for(lock, audioTimeout, cond)) { // Consume audio block for (int i = 0; i < length; i++) { Frame<OUTPUTS> f = outputBuffer.shift(); memcpy(&output[numOutputs * i], &f, numOutputs * sizeof(float)); } } else { // Timed out, fill output with zeros memset(output, 0, length * numOutputs * sizeof(float)); } } // Notify engine when finished processing engineCv.notify_all(); } void onCloseStream() override { inputBuffer.clear(); outputBuffer.clear(); } }; struct AudioInterface : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { ENUMS(AUDIO_INPUT, INPUTS), NUM_INPUTS }; enum OutputIds { ENUMS(AUDIO_OUTPUT, OUTPUTS), NUM_OUTPUTS }; enum LightIds { ENUMS(INPUT_LIGHT, INPUTS / 2), ENUMS(OUTPUT_LIGHT, OUTPUTS / 2), NUM_LIGHTS }; AudioInterfaceIO audioIO; int lastSampleRate = 0; SampleRateConverter<INPUTS> inputSrc; SampleRateConverter<OUTPUTS> outputSrc; // in rack's sample rate DoubleRingBuffer<Frame<INPUTS>, 16> inputBuffer; DoubleRingBuffer<Frame<OUTPUTS>, 16> outputBuffer; AudioInterface() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) { onSampleRateChange(); } void step() override; json_t *toJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "audio", audioIO.toJson()); return rootJ; } void fromJson(json_t *rootJ) override { json_t *audioJ = json_object_get(rootJ, "audio"); audioIO.fromJson(audioJ); } void onSampleRateChange() override { // for (int i = 0; i < INPUTS; i++) { // inputSrc[i].setRates(audioIO.sampleRate, engineGetSampleRate()); // } // for (int i = 0; i < OUTPUTS; i++) { // outputSrc[i].setRates(engineGetSampleRate(), audioIO.sampleRate); // } inputSrc.setRates(audioIO.sampleRate, engineGetSampleRate()); outputSrc.setRates(engineGetSampleRate(), audioIO.sampleRate); } void onReset() override { audioIO.setDevice(-1, 0); } }; void AudioInterface::step() { Frame<INPUTS> inputFrame; memset(&inputFrame, 0, sizeof(inputFrame)); // Update sample rate if changed by audio driver if (audioIO.sampleRate != lastSampleRate) { onSampleRateChange(); lastSampleRate = audioIO.sampleRate; } if (audioIO.numInputs > 0) { if (inputBuffer.empty()) { int inLen = audioIO.inputBuffer.size(); int outLen = inputBuffer.capacity(); inputSrc.process(audioIO.inputBuffer.startData(), &inLen, inputBuffer.endData(), &outLen); audioIO.inputBuffer.startIncr(inLen); inputBuffer.endIncr(outLen); } } if (!inputBuffer.empty()) { inputFrame = inputBuffer.shift(); } for (int i = 0; i < INPUTS; i++) { outputs[AUDIO_OUTPUT + i].value = 10.0 * inputFrame.samples[i]; } if (audioIO.numOutputs > 0) { // Get and push output SRC frame if (!outputBuffer.full()) { Frame<OUTPUTS> f; for (int i = 0; i < audioIO.numOutputs; i++) { f.samples[i] = inputs[AUDIO_INPUT + i].value / 10.0; } outputBuffer.push(f); } if (outputBuffer.full()) { // Wait until outputs are needed std::unique_lock<std::mutex> lock(audioIO.engineMutex); auto cond = [&] { return audioIO.outputBuffer.size() < audioIO.blockSize; }; if (audioIO.engineCv.wait_for(lock, audioTimeout, cond)) { // Push converted output int inLen = outputBuffer.size(); int outLen = audioIO.outputBuffer.capacity(); outputSrc.process(outputBuffer.startData(), &inLen, audioIO.outputBuffer.endData(), &outLen); outputBuffer.startIncr(inLen); audioIO.outputBuffer.endIncr(outLen); } else { // Give up on pushing output } } } for (int i = 0; i < INPUTS / 2; i++) lights[INPUT_LIGHT + i].value = (audioIO.numOutputs >= 2*i+1); for (int i = 0; i < OUTPUTS / 2; i++) lights[OUTPUT_LIGHT + i].value = (audioIO.numInputs >= 2*i+1); audioIO.audioCv.notify_all(); } struct AudioInterfaceWidget : ModuleWidget { AudioInterfaceWidget(AudioInterface *module) : ModuleWidget(module) { setPanel(SVG::load(assetGlobal("res/Core/AudioInterface.svg"))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addInput(Port::create<PJ301MPort>(mm2px(Vec(3.7069211, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 0)); addInput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 1)); addInput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 2)); addInput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 55.530807)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 3)); addInput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 4)); addInput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 5)); addInput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 6)); addInput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 70.144905)), Port::INPUT, module, AudioInterface::AUDIO_INPUT + 7)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 0)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 1)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 2)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(38.506519, 92.143906)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 3)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(3.7069209, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 4)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(15.307249, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 5)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(26.906193, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 6)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(38.506523, 108.1443)), Port::OUTPUT, module, AudioInterface::AUDIO_OUTPUT + 7)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 54.577202)), module, AudioInterface::INPUT_LIGHT + 0)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 54.577202)), module, AudioInterface::INPUT_LIGHT + 1)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 69.158226)), module, AudioInterface::INPUT_LIGHT + 2)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 69.158226)), module, AudioInterface::INPUT_LIGHT + 3)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 91.147583)), module, AudioInterface::OUTPUT_LIGHT + 0)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 91.147583)), module, AudioInterface::OUTPUT_LIGHT + 1)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(12.524985, 107.17003)), module, AudioInterface::OUTPUT_LIGHT + 2)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(mm2px(Vec(35.725647, 107.17003)), module, AudioInterface::OUTPUT_LIGHT + 3)); AudioWidget *audioWidget = Widget::create<AudioWidget>(mm2px(Vec(3.2122073, 14.837339))); audioWidget->box.size = mm2px(Vec(44, 28)); audioWidget->audioIO = &module->audioIO; addChild(audioWidget); } }; Model *modelAudioInterface = Model::create<AudioInterface, AudioInterfaceWidget>("Core", "AudioInterface", "Audio", EXTERNAL_TAG);<|endoftext|>
<commit_before>#include "chrono_parallel/collision/ChCCollisionSystemBulletParallel.h" namespace chrono { namespace collision { /* void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo); if (broad_callback) broad_callback(collisionPair, dispatcher, dispatchInfo); } */ ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(ChParallelDataManager* dc, unsigned int max_objects, double scene_size) : data_manager(dc) { // btDefaultCollisionConstructionInfo conf_info(...); ***TODO*** bt_collision_configuration = new btDefaultCollisionConfiguration(); bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration); //***OLD*** btScalar sscene_size = (btScalar)scene_size; btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size); btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size); bt_broadphase = new bt32BitAxisSweep3( worldAabbMin, worldAabbMax, max_objects, 0, true); // true for disabling raycast accelerator //***NEW*** // bt_broadphase = new btDbvtBroadphase(); bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration); // custom collision for sphere-sphere case ***OBSOLETE*** // bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new // btSphereSphereCollisionAlgorithm::CreateFunc); // register custom collision for GIMPACT mesh case too btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher); counter = 0; } ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() { if (bt_collision_world) delete bt_collision_world; if (bt_broadphase) delete bt_broadphase; if (bt_dispatcher) delete bt_dispatcher; if (bt_collision_configuration) delete bt_collision_configuration; } void ChCollisionSystemBulletParallel::Clear(void) { int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); contactManifold->clearManifold(); } } void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) { ChModelBullet* bmodel = static_cast<ChModelBullet*>(model); if (bmodel->GetBulletModel()->getCollisionShape()) { bmodel->SyncPosition(); bmodel->GetBulletModel()->setCompanionId(counter); bt_collision_world->addCollisionObject(bmodel->GetBulletModel(), bmodel->GetFamilyGroup(), bmodel->GetFamilyMask()); counter++; data_manager->num_rigid_shapes++; } } void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) { ChModelBullet* bmodel = static_cast<ChModelBullet*>(model); if (bmodel->GetBulletModel()->getCollisionShape()) { bt_collision_world->removeCollisionObject(bmodel->GetBulletModel()); } } void ChCollisionSystemBulletParallel::Run() { data_manager->system_timer.start("collision_broad"); if (bt_collision_world) { bt_collision_world->performDiscreteCollisionDetection(); } data_manager->system_timer.stop("collision_broad"); } void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) { data_manager->system_timer.start("collision_narrow"); data_manager->host_data.norm_rigid_rigid.clear(); data_manager->host_data.cpta_rigid_rigid.clear(); data_manager->host_data.cptb_rigid_rigid.clear(); data_manager->host_data.dpth_rigid_rigid.clear(); data_manager->host_data.bids_rigid_rigid.clear(); data_manager->num_rigid_contacts = 0; // mcontactcontainer->BeginAddContact(); ChCollisionInfo icontact; int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform()); icontact.modelA = (ChCollisionModel*)obA->getUserPointer(); icontact.modelB = (ChCollisionModel*)obB->getUserPointer(); double envelopeA = icontact.modelA->GetEnvelope(); double envelopeB = icontact.modelB->GetEnvelope(); double marginA = icontact.modelA->GetSafeMargin(); double marginB = icontact.modelB->GetSafeMargin(); bool activeA = ((ChBody*)(icontact.modelA->GetPhysicsItem()))->IsActive(); bool activeB = ((ChBody*)(icontact.modelB->GetPhysicsItem()))->IsActive(); if (activeA == 0 && activeB == 0) { continue; } // Execute custom broadphase callback, if any bool do_narrow_contactgeneration = true; if (this->broad_callback) do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB); if (do_narrow_contactgeneration) { int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < marginA + marginB) // to discard "too far" constraints (the Bullet engine also has its threshold) { btVector3 ptA = pt.getPositionWorldOnA(); btVector3 ptB = pt.getPositionWorldOnB(); icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ()); icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ()); icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ()); icontact.vN.Normalize(); double ptdist = pt.getDistance(); icontact.vpA = icontact.vpA - icontact.vN * envelopeA; icontact.vpB = icontact.vpB + icontact.vN * envelopeB; icontact.distance = ptdist + envelopeA + envelopeB; icontact.reaction_cache = pt.reactions_cache; // Execute some user custom callback, if any if (this->narrow_callback) this->narrow_callback->NarrowCallback(icontact); // Add to contact container // mcontactcontainer->AddContact(icontact); data_manager->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z)); data_manager->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z)); data_manager->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z)); data_manager->host_data.dpth_rigid_rigid.push_back(icontact.distance); data_manager->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId())); data_manager->num_rigid_contacts++; } } } // you can un-comment out this line, and then all points are removed // contactManifold->clearManifold(); } // mcontactcontainer->EndAddContact(); data_manager->system_timer.stop("collision_narrow"); } } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ <commit_msg>Fix for DEM-P contact.<commit_after>#include "chrono_parallel/collision/ChCCollisionSystemBulletParallel.h" namespace chrono { namespace collision { static const real edge_radius = 0.01; // default edge radius (for penalty contact) /* void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo); if (broad_callback) broad_callback(collisionPair, dispatcher, dispatchInfo); } */ ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(ChParallelDataManager* dc, unsigned int max_objects, double scene_size) : data_manager(dc) { // btDefaultCollisionConstructionInfo conf_info(...); ***TODO*** bt_collision_configuration = new btDefaultCollisionConfiguration(); bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration); //***OLD*** btScalar sscene_size = (btScalar)scene_size; btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size); btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size); bt_broadphase = new bt32BitAxisSweep3( worldAabbMin, worldAabbMax, max_objects, 0, true); // true for disabling raycast accelerator //***NEW*** // bt_broadphase = new btDbvtBroadphase(); bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration); // custom collision for sphere-sphere case ***OBSOLETE*** // bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new // btSphereSphereCollisionAlgorithm::CreateFunc); // register custom collision for GIMPACT mesh case too btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher); counter = 0; } ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() { if (bt_collision_world) delete bt_collision_world; if (bt_broadphase) delete bt_broadphase; if (bt_dispatcher) delete bt_dispatcher; if (bt_collision_configuration) delete bt_collision_configuration; } void ChCollisionSystemBulletParallel::Clear(void) { int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); contactManifold->clearManifold(); } } void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) { ChModelBullet* bmodel = static_cast<ChModelBullet*>(model); if (bmodel->GetBulletModel()->getCollisionShape()) { bmodel->SyncPosition(); bmodel->GetBulletModel()->setCompanionId(counter); bt_collision_world->addCollisionObject(bmodel->GetBulletModel(), bmodel->GetFamilyGroup(), bmodel->GetFamilyMask()); counter++; data_manager->num_rigid_shapes++; } } void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) { ChModelBullet* bmodel = static_cast<ChModelBullet*>(model); if (bmodel->GetBulletModel()->getCollisionShape()) { bt_collision_world->removeCollisionObject(bmodel->GetBulletModel()); } } void ChCollisionSystemBulletParallel::Run() { data_manager->system_timer.start("collision_broad"); if (bt_collision_world) { bt_collision_world->performDiscreteCollisionDetection(); } data_manager->system_timer.stop("collision_broad"); } void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) { data_manager->system_timer.start("collision_narrow"); data_manager->host_data.norm_rigid_rigid.clear(); data_manager->host_data.cpta_rigid_rigid.clear(); data_manager->host_data.cptb_rigid_rigid.clear(); data_manager->host_data.dpth_rigid_rigid.clear(); data_manager->host_data.bids_rigid_rigid.clear(); data_manager->num_rigid_contacts = 0; // mcontactcontainer->BeginAddContact(); ChCollisionInfo icontact; int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform()); icontact.modelA = (ChCollisionModel*)obA->getUserPointer(); icontact.modelB = (ChCollisionModel*)obB->getUserPointer(); double envelopeA = icontact.modelA->GetEnvelope(); double envelopeB = icontact.modelB->GetEnvelope(); double marginA = icontact.modelA->GetSafeMargin(); double marginB = icontact.modelB->GetSafeMargin(); bool activeA = ((ChBody*)(icontact.modelA->GetPhysicsItem()))->IsActive(); bool activeB = ((ChBody*)(icontact.modelB->GetPhysicsItem()))->IsActive(); if (activeA == 0 && activeB == 0) { continue; } // Execute custom broadphase callback, if any bool do_narrow_contactgeneration = true; if (this->broad_callback) do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB); if (do_narrow_contactgeneration) { int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < marginA + marginB) // to discard "too far" constraints (the Bullet engine also has its threshold) { btVector3 ptA = pt.getPositionWorldOnA(); btVector3 ptB = pt.getPositionWorldOnB(); icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ()); icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ()); icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ()); icontact.vN.Normalize(); double ptdist = pt.getDistance(); icontact.vpA = icontact.vpA - icontact.vN * envelopeA; icontact.vpB = icontact.vpB + icontact.vN * envelopeB; icontact.distance = ptdist + envelopeA + envelopeB; icontact.reaction_cache = pt.reactions_cache; // Execute some user custom callback, if any if (this->narrow_callback) this->narrow_callback->NarrowCallback(icontact); // Add to contact container // mcontactcontainer->AddContact(icontact); data_manager->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z)); data_manager->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z)); data_manager->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z)); data_manager->host_data.dpth_rigid_rigid.push_back(icontact.distance); data_manager->host_data.erad_rigid_rigid.push_back(edge_radius); data_manager->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId())); data_manager->num_rigid_contacts++; } } } // you can un-comment out this line, and then all points are removed // contactManifold->clearManifold(); } // mcontactcontainer->EndAddContact(); data_manager->system_timer.stop("collision_narrow"); } } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // Single cell view simulation worker //============================================================================== #include "cellmlfileruntime.h" #include "cliutils.h" #include "coredaesolver.h" #include "corenlasolver.h" #include "coreodesolver.h" #include "singlecellviewsimulation.h" #include "singlecellviewsimulationworker.h" //============================================================================== #include <QElapsedTimer> #include <QMutex> #include <QThread> //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewSimulationWorker::SingleCellViewSimulationWorker(const SolverInterfaces &pSolverInterfaces, CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulation *pSimulation, SingleCellViewSimulationWorker **pSelf) : mSolverInterfaces(pSolverInterfaces), mRuntime(pRuntime), mSimulation(pSimulation), mCurrentPoint(0.0), mProgress(0.0), mPaused(false), mStopped(false), mReset(false), mError(false), mSelf(pSelf) { // Create our thread mThread = new QThread(); // Move ourselves to our thread moveToThread(mThread); // Create a few connections connect(mThread, SIGNAL(started()), this, SLOT(started())); connect(this, SIGNAL(finished(const qint64 &)), mThread, SLOT(quit())); connect(mThread, SIGNAL(finished()), mThread, SLOT(deleteLater())); connect(mThread, SIGNAL(finished()), this, SLOT(deleteLater())); } //============================================================================== bool SingleCellViewSimulationWorker::isRunning() const { // Return whether our thread is running return mThread->isRunning() && !mPaused; } //============================================================================== bool SingleCellViewSimulationWorker::isPaused() const { // Return whether our thread is paused return mThread->isRunning() && mPaused; } //============================================================================== double SingleCellViewSimulationWorker::currentPoint() const { // Return our progress return mThread->isRunning()? mCurrentPoint: mSimulation->data()->startingPoint(); } //============================================================================== double SingleCellViewSimulationWorker::progress() const { // Return our progress return mThread->isRunning()?mProgress:0.0; } //============================================================================== bool SingleCellViewSimulationWorker::run() { // Start our thread, but only if we are not already running if (!mThread->isRunning()) { mThread->start(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::pause() { // Pause ourselves, but only if we are currently running if (isRunning()) { // Ask ourselves to pause mPaused = true; return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::resume() { // Resume ourselves, but only if are currently paused if (isPaused()) { // Ask ourselves to resume mPausedCondition.wakeOne(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::stop() { // Check that we are either running or paused if (isRunning() || isPaused()) { // Ask our thread to stop mStopped = true; // Resume our thread, if needed if (isPaused()) mPausedCondition.wakeOne(); // Ask our thread to quit and wait for it to do so mThread->quit(); mThread->wait(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::reset() { // Check that we are either running or paused if (isRunning() || isPaused()) { // Ask ourselves to reinitialise our solver mReset = true; return true; } else { return false; } } //============================================================================== void SingleCellViewSimulationWorker::started() { // Let people know that we are running emit running(false); // Reset our progress mProgress = 0.0; // Set up our ODE/DAE solver CoreSolver::CoreVoiSolver *voiSolver = 0; CoreSolver::CoreOdeSolver *odeSolver = 0; CoreSolver::CoreDaeSolver *daeSolver = 0; if (mRuntime->needOdeSolver()) { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare(mSimulation->data()->odeSolverName())) { // The requested ODE solver was found, so retrieve an instance // of it voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->solverInstance()); break; } } else { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare("IDA")) { // The requested DAE solver was found, so retrieve an instance // of it voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->solverInstance()); break; } } // Make sure that we have found our ODE/DAE solver // Note #1: this should never happen, but we never know, so... // Note #2: see the end of this method about we do before returning... if (!voiSolver) { if (mRuntime->needOdeSolver()) emitError(tr("the ODE solver could not be found")); else emitError(tr("the DAE solver could not be found")); *mSelf = 0; emit finished(-1); return; } // Set up our NLA solver, if needed CoreSolver::CoreNlaSolver *nlaSolver = 0; if (mRuntime->needNlaSolver()) { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare(mSimulation->data()->nlaSolverName())) { // The requested NLA solver was found, so retrieve an instance // of it nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->solverInstance()); // Keep track of our NLA solver, so that doNonLinearSolve() can // work as expected CoreSolver::setNlaSolver(mRuntime->address(), nlaSolver); break; } // Make sure that we have found our NLA solver // Note #1: this should never happen, but we never know, so... // Note #2: see the end of this method about we do before returning... if (!nlaSolver) { emitError(tr("the NLA solver could not be found")); delete voiSolver; *mSelf = 0; emit finished(-1); return; } } // Keep track of any error that might be reported by any of our solvers mStopped = false; mError = false; if (odeSolver) connect(odeSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); else connect(daeSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); if (nlaSolver) connect(nlaSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); // Retrieve our simulation properties double startingPoint = mSimulation->data()->startingPoint(); double endingPoint = mSimulation->data()->endingPoint(); double pointInterval = mSimulation->data()->pointInterval(); bool increasingPoints = endingPoint > startingPoint; const double oneOverPointsRange = 1.0/(endingPoint-startingPoint); quint64 pointCounter = 0; mCurrentPoint = startingPoint; // Initialise our ODE/DAE solver if (odeSolver) { odeSolver->setProperties(mSimulation->data()->odeSolverProperties()); odeSolver->initialize(mCurrentPoint, mRuntime->statesCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mRuntime->computeOdeRates()); } else { daeSolver->setProperties(mSimulation->data()->daeSolverProperties()); daeSolver->initialize(mCurrentPoint, endingPoint, mRuntime->statesCount(), mRuntime->condVarCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mSimulation->data()->condVar(), mRuntime->computeDaeEssentialVariables(), mRuntime->computeDaeResiduals(), mRuntime->computeDaeRootInformation(), mRuntime->computeDaeStateInformation()); } // Initialise our NLA solver if (nlaSolver) nlaSolver->setProperties(mSimulation->data()->nlaSolverProperties()); // Now, we are ready to compute our model, but only if no error has occurred // so far qint64 elapsedTime; if (!mError) { // Start our timer QElapsedTimer timer; elapsedTime = 0; timer.start(); // Add our first point after making sure that all the variables are up // to date mSimulation->data()->recomputeVariables(mCurrentPoint); mSimulation->results()->addPoint(mCurrentPoint); // Our main work loop // Note: for performance reasons, it is essential that the following // loop doesn't emit any signal, be it directly or indirectly, // unless it is to let people know that we are pausing or running. // Indeed, the signal/slot mechanism adds a certain level of // overhead and, here, we want things to be as fast as possible, // so... QMutex pausedMutex; while ((mCurrentPoint != endingPoint) && !mStopped) { // Determine our next point and compute our model up to it ++pointCounter; voiSolver->solve(mCurrentPoint, increasingPoints? qMin(endingPoint, startingPoint+pointCounter*pointInterval): qMax(endingPoint, startingPoint+pointCounter*pointInterval)); // Make sure that no error occurred if (mError) break; // Update our progress mProgress = (mCurrentPoint-startingPoint)*oneOverPointsRange; // Add our new point after making sure that all the variables are up // to date mSimulation->data()->recomputeVariables(mCurrentPoint); mSimulation->results()->addPoint(mCurrentPoint); // Delay things a bit, if (really) needed if (mSimulation->delay() && !mStopped) Core::doNothing(100*mSimulation->delay()); // Pause ourselves, if (really) needed if (mPaused && !mStopped) { // We should be paused, so stop our timer elapsedTime += timer.elapsed(); // Let people know that we are paused emit paused(); // Actually pause ourselves pausedMutex.lock(); mPausedCondition.wait(&pausedMutex); pausedMutex.unlock(); // We are not paused anymore mPaused = false; // Let people know that we are running again emit running(true); // Restart our timer timer.restart(); } // Reinitialise our solver, if (really) needed if (mReset && !mStopped) { if (odeSolver) odeSolver->initialize(mCurrentPoint, mRuntime->statesCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mRuntime->computeOdeRates()); else daeSolver->initialize(mCurrentPoint, endingPoint, mRuntime->statesCount(), mRuntime->condVarCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mSimulation->data()->condVar(), mRuntime->computeDaeEssentialVariables(), mRuntime->computeDaeResiduals(), mRuntime->computeDaeRootInformation(), mRuntime->computeDaeStateInformation()); mReset = false; } } // Retrieve the total elapsed time, should no error have occurred if (mError) // An error occurred, so... elapsedTime = -1; // Note: we use -1 as a way to indicate that something went wrong... else elapsedTime += timer.elapsed(); } else { // An error occurred, so... elapsedTime = -1; // Note: we use -1 as a way to indicate that something went wrong... } // Delete our solver(s) delete voiSolver; if (nlaSolver) { delete nlaSolver; CoreSolver::unsetNlaSolver(mRuntime->address()); } // Reset our simulation owner's knowledge of us // Note: if we were to do it the Qt way, our simulation owner would have a // slot for our finished() signal, but we want it to know as quickly // as possible that we are done, so... *mSelf = 0; // Let people know that we are done and give them the elapsed time emit finished(elapsedTime); } //============================================================================== void SingleCellViewSimulationWorker::emitError(const QString &pMessage) { // A solver error occurred, so keep track of it and let people know about it mError = true; emit error(pMessage); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // Single cell view simulation worker //============================================================================== #include "cellmlfileruntime.h" #include "cliutils.h" #include "coredaesolver.h" #include "corenlasolver.h" #include "coreodesolver.h" #include "singlecellviewsimulation.h" #include "singlecellviewsimulationworker.h" //============================================================================== #include <QElapsedTimer> #include <QMutex> #include <QThread> //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewSimulationWorker::SingleCellViewSimulationWorker(const SolverInterfaces &pSolverInterfaces, CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulation *pSimulation, SingleCellViewSimulationWorker **pSelf) : mSolverInterfaces(pSolverInterfaces), mRuntime(pRuntime), mSimulation(pSimulation), mCurrentPoint(0.0), mProgress(0.0), mPaused(false), mStopped(false), mReset(false), mError(false), mSelf(pSelf) { // Create our thread mThread = new QThread(); // Move ourselves to our thread moveToThread(mThread); // Create a few connections connect(mThread, SIGNAL(started()), this, SLOT(started())); connect(this, SIGNAL(finished(const qint64 &)), mThread, SLOT(quit())); connect(mThread, SIGNAL(finished()), mThread, SLOT(deleteLater())); connect(mThread, SIGNAL(finished()), this, SLOT(deleteLater())); } //============================================================================== bool SingleCellViewSimulationWorker::isRunning() const { // Return whether our thread is running return mThread->isRunning() && !mPaused; } //============================================================================== bool SingleCellViewSimulationWorker::isPaused() const { // Return whether our thread is paused return mThread->isRunning() && mPaused; } //============================================================================== double SingleCellViewSimulationWorker::currentPoint() const { // Return our progress return mThread->isRunning()? mCurrentPoint: mSimulation->data()->startingPoint(); } //============================================================================== double SingleCellViewSimulationWorker::progress() const { // Return our progress return mThread->isRunning()?mProgress:0.0; } //============================================================================== bool SingleCellViewSimulationWorker::run() { // Start our thread, but only if we are not already running if (!mThread->isRunning()) { mThread->start(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::pause() { // Pause ourselves, but only if we are currently running if (isRunning()) { // Ask ourselves to pause mPaused = true; return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::resume() { // Resume ourselves, but only if are currently paused if (isPaused()) { // Ask ourselves to resume mPausedCondition.wakeOne(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::stop() { // Check that we are either running or paused if (isRunning() || isPaused()) { // Ask our thread to stop mStopped = true; // Resume our thread, if needed if (isPaused()) mPausedCondition.wakeOne(); // Ask our thread to quit and wait for it to do so mThread->quit(); mThread->wait(); return true; } else { return false; } } //============================================================================== bool SingleCellViewSimulationWorker::reset() { // Check that we are either running or paused if (isRunning() || isPaused()) { // Ask ourselves to reinitialise our solver mReset = true; return true; } else { return false; } } //============================================================================== void SingleCellViewSimulationWorker::started() { // Let people know that we are running emit running(false); // Reset our progress mProgress = 0.0; // Set up our ODE/DAE solver CoreSolver::CoreVoiSolver *voiSolver = 0; CoreSolver::CoreOdeSolver *odeSolver = 0; CoreSolver::CoreDaeSolver *daeSolver = 0; if (mRuntime->needOdeSolver()) { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare(mSimulation->data()->odeSolverName())) { // The requested ODE solver was found, so retrieve an instance // of it voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->solverInstance()); break; } } else { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare("IDA")) { // The requested DAE solver was found, so retrieve an instance // of it voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->solverInstance()); break; } } // Make sure that we have found our ODE/DAE solver // Note: this should never happen, but we never know, so... if (!voiSolver) { if (mRuntime->needOdeSolver()) emitError(tr("the ODE solver could not be found")); else emitError(tr("the DAE solver could not be found")); *mSelf = 0; emit finished(-1); return; } // Set up our NLA solver, if needed CoreSolver::CoreNlaSolver *nlaSolver = 0; if (mRuntime->needNlaSolver()) { foreach (SolverInterface *solverInterface, mSolverInterfaces) if (!solverInterface->solverName().compare(mSimulation->data()->nlaSolverName())) { // The requested NLA solver was found, so retrieve an instance // of it nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->solverInstance()); // Keep track of our NLA solver, so that doNonLinearSolve() can // work as expected CoreSolver::setNlaSolver(mRuntime->address(), nlaSolver); break; } // Make sure that we have found our NLA solver // Note #1: this should never happen, but we never know, so... // Note #2: see the end of this method about we do before returning... if (!nlaSolver) { emitError(tr("the NLA solver could not be found")); delete voiSolver; *mSelf = 0; emit finished(-1); return; } } // Keep track of any error that might be reported by any of our solvers mStopped = false; mError = false; if (odeSolver) connect(odeSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); else connect(daeSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); if (nlaSolver) connect(nlaSolver, SIGNAL(error(const QString &)), this, SLOT(emitError(const QString &))); // Retrieve our simulation properties double startingPoint = mSimulation->data()->startingPoint(); double endingPoint = mSimulation->data()->endingPoint(); double pointInterval = mSimulation->data()->pointInterval(); bool increasingPoints = endingPoint > startingPoint; const double oneOverPointsRange = 1.0/(endingPoint-startingPoint); quint64 pointCounter = 0; mCurrentPoint = startingPoint; // Initialise our ODE/DAE solver if (odeSolver) { odeSolver->setProperties(mSimulation->data()->odeSolverProperties()); odeSolver->initialize(mCurrentPoint, mRuntime->statesCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mRuntime->computeOdeRates()); } else { daeSolver->setProperties(mSimulation->data()->daeSolverProperties()); daeSolver->initialize(mCurrentPoint, endingPoint, mRuntime->statesCount(), mRuntime->condVarCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mSimulation->data()->condVar(), mRuntime->computeDaeEssentialVariables(), mRuntime->computeDaeResiduals(), mRuntime->computeDaeRootInformation(), mRuntime->computeDaeStateInformation()); } // Initialise our NLA solver if (nlaSolver) nlaSolver->setProperties(mSimulation->data()->nlaSolverProperties()); // Now, we are ready to compute our model, but only if no error has occurred // so far qint64 elapsedTime; if (!mError) { // Start our timer QElapsedTimer timer; elapsedTime = 0; timer.start(); // Add our first point after making sure that all the variables are up // to date mSimulation->data()->recomputeVariables(mCurrentPoint); mSimulation->results()->addPoint(mCurrentPoint); // Our main work loop // Note: for performance reasons, it is essential that the following // loop doesn't emit any signal, be it directly or indirectly, // unless it is to let people know that we are pausing or running. // Indeed, the signal/slot mechanism adds a certain level of // overhead and, here, we want things to be as fast as possible, // so... QMutex pausedMutex; while ((mCurrentPoint != endingPoint) && !mStopped) { // Determine our next point and compute our model up to it ++pointCounter; voiSolver->solve(mCurrentPoint, increasingPoints? qMin(endingPoint, startingPoint+pointCounter*pointInterval): qMax(endingPoint, startingPoint+pointCounter*pointInterval)); // Make sure that no error occurred if (mError) break; // Update our progress mProgress = (mCurrentPoint-startingPoint)*oneOverPointsRange; // Add our new point after making sure that all the variables are up // to date mSimulation->data()->recomputeVariables(mCurrentPoint); mSimulation->results()->addPoint(mCurrentPoint); // Delay things a bit, if (really) needed if (mSimulation->delay() && !mStopped) Core::doNothing(100*mSimulation->delay()); // Pause ourselves, if (really) needed if (mPaused && !mStopped) { // We should be paused, so stop our timer elapsedTime += timer.elapsed(); // Let people know that we are paused emit paused(); // Actually pause ourselves pausedMutex.lock(); mPausedCondition.wait(&pausedMutex); pausedMutex.unlock(); // We are not paused anymore mPaused = false; // Let people know that we are running again emit running(true); // Restart our timer timer.restart(); } // Reinitialise our solver, if (really) needed if (mReset && !mStopped) { if (odeSolver) odeSolver->initialize(mCurrentPoint, mRuntime->statesCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mRuntime->computeOdeRates()); else daeSolver->initialize(mCurrentPoint, endingPoint, mRuntime->statesCount(), mRuntime->condVarCount(), mSimulation->data()->constants(), mSimulation->data()->rates(), mSimulation->data()->states(), mSimulation->data()->algebraic(), mSimulation->data()->condVar(), mRuntime->computeDaeEssentialVariables(), mRuntime->computeDaeResiduals(), mRuntime->computeDaeRootInformation(), mRuntime->computeDaeStateInformation()); mReset = false; } } // Retrieve the total elapsed time, should no error have occurred if (mError) // An error occurred, so... elapsedTime = -1; // Note: we use -1 as a way to indicate that something went wrong... else elapsedTime += timer.elapsed(); } else { // An error occurred, so... elapsedTime = -1; // Note: we use -1 as a way to indicate that something went wrong... } // Delete our solver(s) delete voiSolver; if (nlaSolver) { delete nlaSolver; CoreSolver::unsetNlaSolver(mRuntime->address()); } // Reset our simulation owner's knowledge of us // Note: if we were to do it the Qt way, our simulation owner would have a // slot for our finished() signal, but we want it to know as quickly // as possible that we are done, so... *mSelf = 0; // Let people know that we are done and give them the elapsed time emit finished(elapsedTime); } //============================================================================== void SingleCellViewSimulationWorker::emitError(const QString &pMessage) { // A solver error occurred, so keep track of it and let people know about it mError = true; emit error(pMessage); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include <vtkVersion.h> #include <vtkImageData.h> #include <vtkSmartPointer.h> #include <vtkImageImport.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkImageActor.h> #include <vtkInteractorStyleImage.h> #include <vtkXMLImageDataWriter.h> int main(int, char *[]) { // Create a c-style image const int width = 4; const int height = 4; unsigned char cImage[width*height]; unsigned char value = 0; for(unsigned int row = 0; row < height; ++row) { for(unsigned int col = 0; col < width; ++col) { cImage[row * width + col] = value; value += 10; } } // Convert the c-style image to a vtkImageData vtkSmartPointer<vtkImageImport> imageImport = vtkSmartPointer<vtkImageImport>::New(); imageImport->SetDataSpacing(1, 1, 1); imageImport->SetDataOrigin(0, 0, 0); imageImport->SetWholeExtent(0, width-1, 0, height-1, 0, 0); imageImport->SetDataExtentToWholeExtent(); imageImport->SetDataScalarTypeToUnsignedChar(); imageImport->SetNumberOfScalarComponents(1); imageImport->SetImportVoidPointer(cImage); imageImport->Update(); // Create an actor vtkSmartPointer<vtkImageActor> actor = vtkSmartPointer<vtkImageActor>::New(); #if VTK_MAJOR_VERSION <= 5 actor->SetInput(imageImport->GetOutput()); #else actor->SetInputData(imageImport->GetOutput()); #endif // Setup renderer vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); renderer->AddActor(actor); renderer->ResetCamera(); // Setup render window vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); // Setup render window interactor vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtkSmartPointer<vtkInteractorStyleImage> style = vtkSmartPointer<vtkInteractorStyleImage>::New(); renderWindowInteractor->SetInteractorStyle(style); // Render and start interaction renderWindowInteractor->SetRenderWindow(renderWindow); renderWindowInteractor->Initialize(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } <commit_msg>ENH: Removed old verison code<commit_after>#include <vtkSmartPointer.h> #include <vtkImageImport.h> #include <vtkImageData.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkImageActor.h> #include <vtkInteractorStyleImage.h> #include <vtkXMLImageDataWriter.h> int main(int, char *[]) { // Create a c-style image const int width = 4; const int height = 4; unsigned char cImage[width*height]; unsigned char value = 0; for(unsigned int row = 0; row < height; ++row) { for(unsigned int col = 0; col < width; ++col) { cImage[row * width + col] = value; value += 10; } } // Convert the c-style image to a vtkImageData vtkSmartPointer<vtkImageImport> imageImport = vtkSmartPointer<vtkImageImport>::New(); imageImport->SetDataSpacing(1, 1, 1); imageImport->SetDataOrigin(0, 0, 0); imageImport->SetWholeExtent(0, width-1, 0, height-1, 0, 0); imageImport->SetDataExtentToWholeExtent(); imageImport->SetDataScalarTypeToUnsignedChar(); imageImport->SetNumberOfScalarComponents(1); imageImport->SetImportVoidPointer(cImage); imageImport->Update(); // Create an actor vtkSmartPointer<vtkImageActor> actor = vtkSmartPointer<vtkImageActor>::New(); actor->SetInputData(imageImport->GetOutput()); // Setup renderer vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); renderer->AddActor(actor); renderer->ResetCamera(); // Setup render window vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); // Setup render window interactor vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtkSmartPointer<vtkInteractorStyleImage> style = vtkSmartPointer<vtkInteractorStyleImage>::New(); renderWindowInteractor->SetInteractorStyle(style); // Render and start interaction renderWindowInteractor->SetRenderWindow(renderWindow); renderWindowInteractor->Initialize(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $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 <qtest.h> #include <QTextDocument> #include <QTcpServer> #include <QTcpSocket> #include <QDir> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmlgraphicsborderimage_p.h> #include <private/qmlgraphicsimagebase_p.h> #include <private/qmlgraphicsscalegrid_p_p.h> #include <private/qmlgraphicsloader_p.h> #include <QtDeclarative/qmlcontext.h> #include "../shared/testhttpserver.h" #define SERVER_PORT 14445 #define SERVER_ADDR "http://127.0.0.1:14445" #define TRY_WAIT(expr) \ do { \ for (int ii = 0; ii < 6; ++ii) { \ if ((expr)) break; \ QTest::qWait(50); \ } \ QVERIFY((expr)); \ } while (false) class tst_qmlgraphicsborderimage : public QObject { Q_OBJECT public: tst_qmlgraphicsborderimage(); private slots: void noSource(); void imageSource(); void imageSource_data(); void clearSource(); void resized(); void smooth(); void tileModes(); void sciSource(); void sciSource_data(); void invalidSciFile(); void pendingRemoteRequest(); void pendingRemoteRequest_data(); private: QmlEngine engine; }; tst_qmlgraphicsborderimage::tst_qmlgraphicsborderimage() { } void tst_qmlgraphicsborderimage::noSource() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->source(), QUrl()); QCOMPARE(obj->width(), 0.); QCOMPARE(obj->height(), 0.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::imageSource() { QFETCH(QString, source); QFETCH(bool, valid); bool remote = source.startsWith("http"); TestHTTPServer *server = 0; if (remote) { server = new TestHTTPServer(SERVER_PORT); QVERIFY(server->isValid()); server->serveDirectory(SRCDIR "/data"); } QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); if (remote) TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Loading); QCOMPARE(obj->source(), remote ? source : QUrl::fromLocalFile(source)); if (valid) { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->width(), 120.); QCOMPARE(obj->height(), 120.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); } else { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Error); } delete obj; delete server; } void tst_qmlgraphicsborderimage::clearSource() { QString componentStr = "import Qt 4.6\nBorderImage { source: srcImage }"; QmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty("srcImage", SRCDIR "/data/colors.png"); QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QVERIFY(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->width(), 120.); QCOMPARE(obj->height(), 120.); ctxt->setContextProperty("srcImage", ""); QVERIFY(obj->source().isEmpty()); QVERIFY(obj->status() == QmlGraphicsBorderImage::Null); QCOMPARE(obj->width(), 0.); QCOMPARE(obj->height(), 0.); } void tst_qmlgraphicsborderimage::imageSource_data() { QTest::addColumn<QString>("source"); QTest::addColumn<bool>("valid"); QTest::newRow("local") << SRCDIR "/data/colors.png" << true; QTest::newRow("local not found") << SRCDIR "/data/no-such-file.png" << false; QTest::newRow("remote") << SERVER_ADDR "/colors.png" << true; QTest::newRow("remote not found") << SERVER_ADDR "/no-such-file.png" << false; } void tst_qmlgraphicsborderimage::resized() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::smooth() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; smooth: true; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->smooth(), true); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::tileModes() { { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 100; height: 300; horizontalTileMode: BorderImage.Repeat; verticalTileMode: BorderImage.Repeat }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 100.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Repeat); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Repeat); delete obj; } { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 300; height: 150; horizontalTileMode: BorderImage.Round; verticalTileMode: BorderImage.Round }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 150.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Round); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Round); delete obj; } } void tst_qmlgraphicsborderimage::sciSource() { QFETCH(QString, source); QFETCH(bool, valid); bool remote = source.startsWith("http"); TestHTTPServer *server = 0; if (remote) { server = new TestHTTPServer(SERVER_PORT); QVERIFY(server->isValid()); server->serveDirectory(SRCDIR "/data"); } QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); if (remote) TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Loading); QCOMPARE(obj->source(), remote ? source : QUrl::fromLocalFile(source)); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); if (valid) { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->border()->left(), 10); QCOMPARE(obj->border()->top(), 20); QCOMPARE(obj->border()->right(), 30); QCOMPARE(obj->border()->bottom(), 40); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Round); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Repeat); } else { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Error); } delete obj; delete server; } void tst_qmlgraphicsborderimage::sciSource_data() { QTest::addColumn<QString>("source"); QTest::addColumn<bool>("valid"); QTest::newRow("local") << SRCDIR "/data/colors-round.sci" << true; QTest::newRow("local not found") << SRCDIR "/data/no-such-file.sci" << false; QTest::newRow("remote") << SERVER_ADDR "/colors-round.sci" << true; QTest::newRow("remote not found") << SERVER_ADDR "/no-such-file.sci" << false; } void tst_qmlgraphicsborderimage::invalidSciFile() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/invalid.sci\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->status(), QmlGraphicsImageBase::Error); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::pendingRemoteRequest() { QFETCH(QString, source); QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->status(), QmlGraphicsBorderImage::Loading); // verify no crash // This will cause a delayed "QThread: Destroyed while thread is still running" warning delete obj; QTest::qWait(50); } void tst_qmlgraphicsborderimage::pendingRemoteRequest_data() { QTest::addColumn<QString>("source"); QTest::newRow("png file") << "http://no-such-qt-server-like-this/none.png"; QTest::newRow("sci file") << "http://no-such-qt-server-like-this/none.sci"; } QTEST_MAIN(tst_qmlgraphicsborderimage) #include "tst_qmlgraphicsborderimage.moc" <commit_msg>check warnings<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $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 <qtest.h> #include <QTextDocument> #include <QTcpServer> #include <QTcpSocket> #include <QDir> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmlgraphicsborderimage_p.h> #include <private/qmlgraphicsimagebase_p.h> #include <private/qmlgraphicsscalegrid_p_p.h> #include <private/qmlgraphicsloader_p.h> #include <QtDeclarative/qmlcontext.h> #include "../shared/testhttpserver.h" #define SERVER_PORT 14445 #define SERVER_ADDR "http://127.0.0.1:14445" #define TRY_WAIT(expr) \ do { \ for (int ii = 0; ii < 6; ++ii) { \ if ((expr)) break; \ QTest::qWait(50); \ } \ QVERIFY((expr)); \ } while (false) class tst_qmlgraphicsborderimage : public QObject { Q_OBJECT public: tst_qmlgraphicsborderimage(); private slots: void noSource(); void imageSource(); void imageSource_data(); void clearSource(); void resized(); void smooth(); void tileModes(); void sciSource(); void sciSource_data(); void invalidSciFile(); void pendingRemoteRequest(); void pendingRemoteRequest_data(); private: QmlEngine engine; }; tst_qmlgraphicsborderimage::tst_qmlgraphicsborderimage() { } void tst_qmlgraphicsborderimage::noSource() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->source(), QUrl()); QCOMPARE(obj->width(), 0.); QCOMPARE(obj->height(), 0.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::imageSource_data() { QTest::addColumn<QString>("source"); QTest::addColumn<bool>("remote"); QTest::addColumn<QString>("error"); QTest::newRow("local") << SRCDIR "/data/colors.png" << false << ""; QTest::newRow("local not found") << SRCDIR "/data/no-such-file.png" << false << "Cannot open QUrl( \"file://" SRCDIR "/data/no-such-file.png\" ) "; QTest::newRow("remote") << SERVER_ADDR "/colors.png" << true << ""; QTest::newRow("remote not found") << SERVER_ADDR "/no-such-file.png" << true << "Network error loading QUrl( \"" SERVER_ADDR "/no-such-file.png\" ) " "\"Error downloading " SERVER_ADDR "/no-such-file.png - server replied: Not found\" "; } void tst_qmlgraphicsborderimage::imageSource() { QFETCH(QString, source); QFETCH(bool, remote); QFETCH(QString, error); TestHTTPServer *server = 0; if (remote) { server = new TestHTTPServer(SERVER_PORT); QVERIFY(server->isValid()); server->serveDirectory(SRCDIR "/data"); } if (!error.isEmpty()) QTest::ignoreMessage(QtWarningMsg, error.toUtf8()); QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); if (remote) TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Loading); QCOMPARE(obj->source(), remote ? source : QUrl::fromLocalFile(source)); if (error.isEmpty()) { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->width(), 120.); QCOMPARE(obj->height(), 120.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); } else { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Error); } delete obj; delete server; } void tst_qmlgraphicsborderimage::clearSource() { QString componentStr = "import Qt 4.6\nBorderImage { source: srcImage }"; QmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty("srcImage", SRCDIR "/data/colors.png"); QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QVERIFY(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->width(), 120.); QCOMPARE(obj->height(), 120.); ctxt->setContextProperty("srcImage", ""); QVERIFY(obj->source().isEmpty()); QVERIFY(obj->status() == QmlGraphicsBorderImage::Null); QCOMPARE(obj->width(), 0.); QCOMPARE(obj->height(), 0.); } void tst_qmlgraphicsborderimage::resized() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::smooth() { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; smooth: true; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->smooth(), true); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::tileModes() { { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 100; height: 300; horizontalTileMode: BorderImage.Repeat; verticalTileMode: BorderImage.Repeat }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 100.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Repeat); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Repeat); delete obj; } { QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/colors.png\"; width: 300; height: 150; horizontalTileMode: BorderImage.Round; verticalTileMode: BorderImage.Round }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 150.); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Round); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Round); delete obj; } } void tst_qmlgraphicsborderimage::sciSource() { QFETCH(QString, source); QFETCH(bool, valid); bool remote = source.startsWith("http"); TestHTTPServer *server = 0; if (remote) { server = new TestHTTPServer(SERVER_PORT); QVERIFY(server->isValid()); server->serveDirectory(SRCDIR "/data"); } QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); if (remote) TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Loading); QCOMPARE(obj->source(), remote ? source : QUrl::fromLocalFile(source)); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); if (valid) { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Ready); QCOMPARE(obj->border()->left(), 10); QCOMPARE(obj->border()->top(), 20); QCOMPARE(obj->border()->right(), 30); QCOMPARE(obj->border()->bottom(), 40); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Round); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Repeat); } else { TRY_WAIT(obj->status() == QmlGraphicsBorderImage::Error); } delete obj; delete server; } void tst_qmlgraphicsborderimage::sciSource_data() { QTest::addColumn<QString>("source"); QTest::addColumn<bool>("valid"); QTest::newRow("local") << SRCDIR "/data/colors-round.sci" << true; QTest::newRow("local not found") << SRCDIR "/data/no-such-file.sci" << false; QTest::newRow("remote") << SERVER_ADDR "/colors-round.sci" << true; QTest::newRow("remote not found") << SERVER_ADDR "/no-such-file.sci" << false; } void tst_qmlgraphicsborderimage::invalidSciFile() { QTest::ignoreMessage(QtWarningMsg, "Unknown tile rule specified. Using Stretch "); // for "Roun" QTest::ignoreMessage(QtWarningMsg, "Unknown tile rule specified. Using Stretch "); // for "Repea" QString componentStr = "import Qt 4.6\nBorderImage { source: \"" SRCDIR "/data/invalid.sci\"; width: 300; height: 300 }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->width(), 300.); QCOMPARE(obj->height(), 300.); QCOMPARE(obj->status(), QmlGraphicsImageBase::Error); QCOMPARE(obj->horizontalTileMode(), QmlGraphicsBorderImage::Stretch); QCOMPARE(obj->verticalTileMode(), QmlGraphicsBorderImage::Stretch); delete obj; } void tst_qmlgraphicsborderimage::pendingRemoteRequest() { QFETCH(QString, source); QString componentStr = "import Qt 4.6\nBorderImage { source: \"" + source + "\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlGraphicsBorderImage *obj = qobject_cast<QmlGraphicsBorderImage*>(component.create()); QVERIFY(obj != 0); QCOMPARE(obj->status(), QmlGraphicsBorderImage::Loading); // verify no crash // This will cause a delayed "QThread: Destroyed while thread is still running" warning delete obj; QTest::qWait(50); } void tst_qmlgraphicsborderimage::pendingRemoteRequest_data() { QTest::addColumn<QString>("source"); QTest::newRow("png file") << "http://no-such-qt-server-like-this/none.png"; QTest::newRow("sci file") << "http://no-such-qt-server-like-this/none.sci"; } QTEST_MAIN(tst_qmlgraphicsborderimage) #include "tst_qmlgraphicsborderimage.moc" <|endoftext|>
<commit_before>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Transform.h" DC_BEGIN_DREEMCHEST namespace Scene { // ------------------------------------------- MoveTo ------------------------------------------- // // ** MoveTo::target Vec3 MoveTo::target( void ) const { return m_target->get(); } // ** MoveTo::isContinuous bool MoveTo::isContinuous( void ) const { return m_isContinuous; } // ** MoveTo::type MoveTo::Type MoveTo::type( void ) const { return m_type; } // ** MoveTo::damping f32 MoveTo::damping( void ) const { return m_damping; } // ** MoveTo::springForce f32 MoveTo::springForce( void ) const { return m_springForce; } // ------------------------------------------ Transform ------------------------------------------ // // ** Transform::matrix const Matrix4& Transform::matrix( void ) const { return m_transform; } // ** Transform::setMatrix void Transform::setMatrix( const Matrix4& value ) { m_transform = value; } // ** Transform::parent const TransformWPtr& Transform::parent( void ) const { return m_parent; } // ** Transform::setParent void Transform::setParent( const TransformWPtr& value ) { m_parent = value; } // ** Transform::worldSpacePosition Vec3 Transform::worldSpacePosition( void ) const { return matrix() * Vec3( 0.0f, 0.0f, 0.0f ); } // ** Transform::position const Vec3& Transform::position( void ) const { return m_position; } // ** Transform::setPosition void Transform::setPosition( const Vec3& value ) { m_position = value; } // ** Transform::axisX Vec3 Transform::axisX( void ) const { return m_rotation.rotate( Vec3( 1.0f, 0.0f, 0.0f ) ); } // ** Transform::axisY Vec3 Transform::axisY( void ) const { return m_rotation.rotate( Vec3( 0.0f, 1.0f, 0.0f ) ); } // ** Transform::axisZ Vec3 Transform::axisZ( void ) const { return m_rotation.rotate( Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::x f32 Transform::x( void ) const { return m_position.x; } // ** Transform::setX void Transform::setX( f32 value ) { m_position.x = value; } // ** Transform::y f32 Transform::y( void ) const { return m_position.y; } // ** Transform::setY void Transform::setY( f32 value ) { m_position.y = value; } // ** Transform::rotation const Quat& Transform::rotation( void ) const { return m_rotation; } // ** Transform::rotate void Transform::rotate( f32 angle, f32 x, f32 y, f32 z ) { Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) ); m_rotation = r * m_rotation; } // ** Transform::setRotation void Transform::setRotation( const Quat& value ) { m_rotation = value; } // ** Transform::rotationX f32 Transform::rotationX( void ) const { return m_rotation.x; } // ** Transform::setRotationX void Transform::setRotationX( f32 value ) { m_rotation.x = value; } // ** Transform::rotationY f32 Transform::rotationY( void ) const { return m_rotation.y; } // ** Transform::setRotationY void Transform::setRotationY( f32 value ) { m_rotation.y = value; } // ** Transform::rotationZ f32 Transform::rotationZ( void ) const { return m_rotation.z; } // ** Transform::setRotationZ void Transform::setRotationZ( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::setScale void Transform::setScale( const Vec3& value ) { m_scale = value; } // ** Transform::scale const Vec3& Transform::scale( void ) const { return m_scale; } // ** Transform::scaleX f32 Transform::scaleX( void ) const { return m_scale.x; } // ** Transform::setScaleX void Transform::setScaleX( f32 value ) { m_scale.x = value; } // ** Transform::scaleY f32 Transform::scaleY( void ) const { return m_scale.y; } // ** Transform::setScaleY void Transform::setScaleY( f32 value ) { m_scale.y = value; } // ** Transform::scaleZ f32 Transform::scaleZ( void ) const { return m_scale.z; } // ** Transform::setScaleZ void Transform::setScaleZ( f32 value ) { m_scale.z = value; } // ----------------------------------------------- Identifier ------------------------------------------------ // // ** Identifier::name const String& Identifier::name( void ) const { return m_name; } // ** Identifier::setName void Identifier::setName( const String& value ) { m_name = value; } // --------------------------------------------- MoveAlongAxes --------------------------------------------- // // ** MoveAlongAxes::speed f32 MoveAlongAxes::speed( void ) const { return m_speed; } // ** MoveAlongAxes::coordinateSystem u8 MoveAlongAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** MoveAlongAxes::delta Vec3 MoveAlongAxes::delta( void ) const { return m_delta->get(); } // ** MoveAlongAxes::rangeForAxis const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** MoveAlongAxes::setRangeForAxis void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // --------------------------------------------- RotateAroundAxes --------------------------------------------- // // ** RotateAroundAxes::speed f32 RotateAroundAxes::speed( void ) const { return m_speed; } // ** RotateAroundAxes::setSpeed void RotateAroundAxes::setSpeed( f32 value ) { m_speed = value; } // ** RotateAroundAxes::coordinateSystem u8 RotateAroundAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** RotateAroundAxes::delta Vec3 RotateAroundAxes::delta( void ) const { return m_delta->get(); } // ** RotateAroundAxes::binding Vec3BindingWPtr RotateAroundAxes::binding( void ) const { return m_delta; } // ** RotateAroundAxes::setBinding void RotateAroundAxes::setBinding( const Vec3BindingPtr& value ) { m_delta = value; } // ** RotateAroundAxes::rangeForAxis const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** RotateAroundAxes::setRangeForAxis void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // ** RotateAroundAxes::rotationForAxis f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const { return m_rotation[axis]; } // ** RotateAroundAxes::setRotationForAxis void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value ) { m_rotation[axis] = value; } } // namespace Scene DC_END_DREEMCHEST<commit_msg>Implemented: Transform z property accessors<commit_after>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Transform.h" DC_BEGIN_DREEMCHEST namespace Scene { // ------------------------------------------- MoveTo ------------------------------------------- // // ** MoveTo::target Vec3 MoveTo::target( void ) const { return m_target->get(); } // ** MoveTo::isContinuous bool MoveTo::isContinuous( void ) const { return m_isContinuous; } // ** MoveTo::type MoveTo::Type MoveTo::type( void ) const { return m_type; } // ** MoveTo::damping f32 MoveTo::damping( void ) const { return m_damping; } // ** MoveTo::springForce f32 MoveTo::springForce( void ) const { return m_springForce; } // ------------------------------------------ Transform ------------------------------------------ // // ** Transform::matrix const Matrix4& Transform::matrix( void ) const { return m_transform; } // ** Transform::setMatrix void Transform::setMatrix( const Matrix4& value ) { m_transform = value; } // ** Transform::parent const TransformWPtr& Transform::parent( void ) const { return m_parent; } // ** Transform::setParent void Transform::setParent( const TransformWPtr& value ) { m_parent = value; } // ** Transform::worldSpacePosition Vec3 Transform::worldSpacePosition( void ) const { return matrix() * Vec3( 0.0f, 0.0f, 0.0f ); } // ** Transform::position const Vec3& Transform::position( void ) const { return m_position; } // ** Transform::setPosition void Transform::setPosition( const Vec3& value ) { m_position = value; } // ** Transform::axisX Vec3 Transform::axisX( void ) const { return m_rotation.rotate( Vec3( 1.0f, 0.0f, 0.0f ) ); } // ** Transform::axisY Vec3 Transform::axisY( void ) const { return m_rotation.rotate( Vec3( 0.0f, 1.0f, 0.0f ) ); } // ** Transform::axisZ Vec3 Transform::axisZ( void ) const { return m_rotation.rotate( Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::x f32 Transform::x( void ) const { return m_position.x; } // ** Transform::setX void Transform::setX( f32 value ) { m_position.x = value; } // ** Transform::y f32 Transform::y( void ) const { return m_position.y; } // ** Transform::setY void Transform::setY( f32 value ) { m_position.y = value; } // ** Transform::z f32 Transform::z( void ) const { return m_position.z; } // ** Transform::setZ void Transform::setZ( f32 value ) { m_position.z = value; } // ** Transform::rotation const Quat& Transform::rotation( void ) const { return m_rotation; } // ** Transform::rotate void Transform::rotate( f32 angle, f32 x, f32 y, f32 z ) { Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) ); m_rotation = r * m_rotation; } // ** Transform::setRotation void Transform::setRotation( const Quat& value ) { m_rotation = value; } // ** Transform::rotationX f32 Transform::rotationX( void ) const { return m_rotation.x; } // ** Transform::setRotationX void Transform::setRotationX( f32 value ) { m_rotation.x = value; } // ** Transform::rotationY f32 Transform::rotationY( void ) const { return m_rotation.y; } // ** Transform::setRotationY void Transform::setRotationY( f32 value ) { m_rotation.y = value; } // ** Transform::rotationZ f32 Transform::rotationZ( void ) const { return m_rotation.z; } // ** Transform::setRotationZ void Transform::setRotationZ( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::setScale void Transform::setScale( const Vec3& value ) { m_scale = value; } // ** Transform::scale const Vec3& Transform::scale( void ) const { return m_scale; } // ** Transform::scaleX f32 Transform::scaleX( void ) const { return m_scale.x; } // ** Transform::setScaleX void Transform::setScaleX( f32 value ) { m_scale.x = value; } // ** Transform::scaleY f32 Transform::scaleY( void ) const { return m_scale.y; } // ** Transform::setScaleY void Transform::setScaleY( f32 value ) { m_scale.y = value; } // ** Transform::scaleZ f32 Transform::scaleZ( void ) const { return m_scale.z; } // ** Transform::setScaleZ void Transform::setScaleZ( f32 value ) { m_scale.z = value; } // ----------------------------------------------- Identifier ------------------------------------------------ // // ** Identifier::name const String& Identifier::name( void ) const { return m_name; } // ** Identifier::setName void Identifier::setName( const String& value ) { m_name = value; } // --------------------------------------------- MoveAlongAxes --------------------------------------------- // // ** MoveAlongAxes::speed f32 MoveAlongAxes::speed( void ) const { return m_speed; } // ** MoveAlongAxes::coordinateSystem u8 MoveAlongAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** MoveAlongAxes::delta Vec3 MoveAlongAxes::delta( void ) const { return m_delta->get(); } // ** MoveAlongAxes::rangeForAxis const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** MoveAlongAxes::setRangeForAxis void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // --------------------------------------------- RotateAroundAxes --------------------------------------------- // // ** RotateAroundAxes::speed f32 RotateAroundAxes::speed( void ) const { return m_speed; } // ** RotateAroundAxes::setSpeed void RotateAroundAxes::setSpeed( f32 value ) { m_speed = value; } // ** RotateAroundAxes::coordinateSystem u8 RotateAroundAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** RotateAroundAxes::delta Vec3 RotateAroundAxes::delta( void ) const { return m_delta->get(); } // ** RotateAroundAxes::binding Vec3BindingWPtr RotateAroundAxes::binding( void ) const { return m_delta; } // ** RotateAroundAxes::setBinding void RotateAroundAxes::setBinding( const Vec3BindingPtr& value ) { m_delta = value; } // ** RotateAroundAxes::rangeForAxis const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** RotateAroundAxes::setRangeForAxis void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // ** RotateAroundAxes::rotationForAxis f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const { return m_rotation[axis]; } // ** RotateAroundAxes::setRotationForAxis void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value ) { m_rotation[axis] = value; } } // namespace Scene DC_END_DREEMCHEST<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxillary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> #define TRIGGER_PIN_DEFAULT 1 extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Set the trigger on / off */ void control(bool on); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int _pin; private: struct hrt_call _engagecall; struct hrt_call _disengagecall; static struct work_s _work; int _gpio_fd; int _polarity; float _activation_time; float _interval; uint32_t _trigger_seq; bool _trigger_enabled; int _vcommand_sub; orb_advert_t _trigger_pub; param_t polarity; param_t activation_time; param_t interval; param_t transfer_time ; static constexpr uint32_t _gpios[6] = { GPIO_GPIO0_OUTPUT, GPIO_GPIO1_OUTPUT, GPIO_GPIO2_OUTPUT, GPIO_GPIO3_OUTPUT, GPIO_GPIO4_OUTPUT, GPIO_GPIO5_OUTPUT }; /** * Vehicle command handler */ static void cycle_trampoline(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; struct work_s CameraTrigger::_work; constexpr uint32_t CameraTrigger::_gpios[6]; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : _pin(TRIGGER_PIN_DEFAULT), _engagecall {}, _disengagecall {}, _gpio_fd(-1), _polarity(0), _activation_time(0.5f /* ms */), _interval(100.0f /* ms */), _trigger_seq(0), _trigger_enabled(false), _vcommand_sub(-1), _trigger_pub(nullptr) { memset(&_work, 0, sizeof(_work)); memset(&_engagecall, 0, sizeof(_engagecall)); memset(&_disengagecall, 0, sizeof(_disengagecall)); // Parameters polarity = param_find("TRIG_POLARITY"); interval = param_find("TRIG_INTERVAL"); activation_time = param_find("TRIG_ACT_TIME"); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::control(bool on) { // always execute, even if already on // to reset timings if necessary // schedule trigger on and off calls hrt_call_every(&_engagecall, 500, (_interval * 1000), (hrt_callout)&CameraTrigger::engage, this); // schedule trigger on and off calls hrt_call_every(&_disengagecall, 500 + (_activation_time * 1000), (_interval * 1000), (hrt_callout)&CameraTrigger::disengage, this); _trigger_enabled = on; } void CameraTrigger::start() { param_get(polarity, &_polarity); param_get(activation_time, &_activation_time); param_get(interval, &_interval); stm32_configgpio(_gpios[_pin - 1]); if (_polarity == 0) { stm32_gpiowrite(_gpios[_pin - 1], 1); // GPIO pin pull high } else if (_polarity == 1) { stm32_gpiowrite(_gpios[_pin - 1], 0); // GPIO pin pull low } else { warnx(" invalid trigger polarity setting. stopping."); stop(); } // start to monitor at high rate for trigger enable command work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, this, USEC2TICK(1)); } void CameraTrigger::stop() { work_cancel(LPWORK, &_work); hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::cycle_trampoline(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); if (trig->_vcommand_sub < 0) { trig->_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); } bool updated; orb_check(trig->_vcommand_sub, &updated); // while the trigger is inactive it has to be ready // to become active instantaneously int poll_interval_usec = 5000; if (updated) { struct vehicle_command_s cmd; orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &cmd); if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { // Set trigger rate from command if (cmd.param2 > 0) { trig->_interval = cmd.param2; param_set(trig->interval, &(trig->_interval)); } if (cmd.param1 < 1.0f) { trig->control(false); } else if (cmd.param1 >= 1.0f) { trig->control(true); // while the trigger is active there is no // need to poll at a very high rate poll_interval_usec = 100000; } } } work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, camera_trigger::g_camera_trigger, USEC2TICK(poll_interval_usec)); } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->_pin - 1]); struct camera_trigger_s trigger; /* set timestamp the instant before the trigger goes off */ trigger.timestamp = hrt_absolute_time(); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 0); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 1); } trigger.seq = trig->_trigger_seq++; orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trigger); } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->_pin - 1]); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 1); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 0); } } void CameraTrigger::info() { warnx("state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("pin : %i, polarity : %s", _pin, _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("interval : %.2f", (double)_interval); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n" "\t-p <n>\tUse specified AUX OUT pin number (default: %d)", TRIGGER_PIN_DEFAULT ); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } if (argc > 3) { camera_trigger::g_camera_trigger->_pin = (int)argv[3]; if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) { warnx("starting trigger on pin : %li ", atoi(argv[3])); camera_trigger::g_camera_trigger->_pin = atoi(argv[3]); } else { usage(); } } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else if (!strcmp(argv[1], "enable")) { camera_trigger::g_camera_trigger->control(true); } else if (!strcmp(argv[1], "disable")) { camera_trigger::g_camera_trigger->control(false); } else { usage(); } return 0; } <commit_msg>Camera trigger: Launch publication in correct thread<commit_after>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxillary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> #define TRIGGER_PIN_DEFAULT 1 extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Set the trigger on / off */ void control(bool on); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int _pin; private: struct hrt_call _engagecall; struct hrt_call _disengagecall; static struct work_s _work; int _gpio_fd; int _polarity; float _activation_time; float _interval; uint32_t _trigger_seq; bool _trigger_enabled; int _vcommand_sub; orb_advert_t _trigger_pub; param_t polarity; param_t activation_time; param_t interval; param_t transfer_time ; static constexpr uint32_t _gpios[6] = { GPIO_GPIO0_OUTPUT, GPIO_GPIO1_OUTPUT, GPIO_GPIO2_OUTPUT, GPIO_GPIO3_OUTPUT, GPIO_GPIO4_OUTPUT, GPIO_GPIO5_OUTPUT }; /** * Vehicle command handler */ static void cycle_trampoline(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; struct work_s CameraTrigger::_work; constexpr uint32_t CameraTrigger::_gpios[6]; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : _pin(TRIGGER_PIN_DEFAULT), _engagecall {}, _disengagecall {}, _gpio_fd(-1), _polarity(0), _activation_time(0.5f /* ms */), _interval(100.0f /* ms */), _trigger_seq(0), _trigger_enabled(false), _vcommand_sub(-1), _trigger_pub(nullptr) { memset(&_work, 0, sizeof(_work)); // Parameters polarity = param_find("TRIG_POLARITY"); interval = param_find("TRIG_INTERVAL"); activation_time = param_find("TRIG_ACT_TIME"); struct camera_trigger_s trigger = {}; _trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trigger); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::control(bool on) { // always execute, even if already on // to reset timings if necessary // schedule trigger on and off calls hrt_call_every(&_engagecall, 500, (_interval * 1000), (hrt_callout)&CameraTrigger::engage, this); // schedule trigger on and off calls hrt_call_every(&_disengagecall, 500 + (_activation_time * 1000), (_interval * 1000), (hrt_callout)&CameraTrigger::disengage, this); _trigger_enabled = on; } void CameraTrigger::start() { param_get(polarity, &_polarity); param_get(activation_time, &_activation_time); param_get(interval, &_interval); stm32_configgpio(_gpios[_pin - 1]); if (_polarity == 0) { stm32_gpiowrite(_gpios[_pin - 1], 1); // GPIO pin pull high } else if (_polarity == 1) { stm32_gpiowrite(_gpios[_pin - 1], 0); // GPIO pin pull low } else { warnx(" invalid trigger polarity setting. stopping."); stop(); } // start to monitor at high rate for trigger enable command work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, this, USEC2TICK(1)); } void CameraTrigger::stop() { work_cancel(LPWORK, &_work); hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::cycle_trampoline(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); if (trig->_vcommand_sub < 0) { trig->_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); } bool updated; orb_check(trig->_vcommand_sub, &updated); // while the trigger is inactive it has to be ready // to become active instantaneously int poll_interval_usec = 5000; if (updated) { struct vehicle_command_s cmd; orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &cmd); if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { // Set trigger rate from command if (cmd.param2 > 0) { trig->_interval = cmd.param2; param_set(trig->interval, &(trig->_interval)); } if (cmd.param1 < 1.0f) { trig->control(false); } else if (cmd.param1 >= 1.0f) { trig->control(true); // while the trigger is active there is no // need to poll at a very high rate poll_interval_usec = 100000; } } } work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, camera_trigger::g_camera_trigger, USEC2TICK(poll_interval_usec)); } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->_pin - 1]); struct camera_trigger_s trigger; /* set timestamp the instant before the trigger goes off */ trigger.timestamp = hrt_absolute_time(); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 0); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 1); } trigger.seq = trig->_trigger_seq++; orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trigger); } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->_pin - 1]); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 1); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->_pin - 1], 0); } } void CameraTrigger::info() { warnx("state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("pin : %i, polarity : %s", _pin, _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("interval : %.2f", (double)_interval); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n" "\t-p <n>\tUse specified AUX OUT pin number (default: %d)", TRIGGER_PIN_DEFAULT ); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } if (argc > 3) { camera_trigger::g_camera_trigger->_pin = (int)argv[3]; if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) { warnx("starting trigger on pin : %li ", atoi(argv[3])); camera_trigger::g_camera_trigger->_pin = atoi(argv[3]); } else { usage(); } } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else if (!strcmp(argv[1], "enable")) { camera_trigger::g_camera_trigger->control(true); } else if (!strcmp(argv[1], "disable")) { camera_trigger::g_camera_trigger->control(false); } else { usage(); } return 0; } <|endoftext|>
<commit_before>#include "training/graph_group_sync.h" namespace marian { SyncGraphGroup::SyncGraphGroup(Ptr<Config> config) : GraphGroup(config), ExponentialSmoothing{options_->get<float>("exponential-smoothing")}, delay_{options_->get<size_t>("optimizer-delay")} { // @TODO: rename to something else; delay means delayed updated, not accumulation mpi_ = initMPI(/*multiThreaded=*/false); // when not running under MPI, this will be a fake object that represents a one-MPI-process setup devices_ = options_->getDevices(mpi_->myMPIRank(), mpi_->numMPIProcesses()); for(auto device : devices_) { auto graph = New<ExpressionGraph>(); graph->setDevice(device); graph->reserveWorkspaceMB(options_->get<size_t>("workspace")); graph->getBackend()->setClip(options_->get<float>("clip-gemm")); graphs_.push_back(graph); shardOpt_.push_back(Optimizer(options_)); builders_.push_back(models::from_config(options_, models::usage::training)); } // Note: We may well end up with only one MPI process or only one graph per worker. // This part of the code will not special-case any of this here. // Rather, it is assumed that the communicator knows to reduce unnecessary transfers to no-ops. comm_ = createCommunicator(graphs_, /*noNccl=*/options_->get<bool>("no-nccl", false), /*mpi=*/mpi_); } void SyncGraphGroup::setScheduler(Ptr<Scheduler> scheduler) /*override*/ { scheduler_ = scheduler; // optimizer has to be registered last to see changes of learning rate // @TODO: ^^Fix this comment. Either it refers to the scheduler, or it should be moved. Which one? scheduler_->registerTrainingObserver(scheduler_); for(auto opt : shardOpt_) scheduler_->registerTrainingObserver(opt); } void SyncGraphGroup::initialize(const Ptr<data::Batch>& exampleBatch) { // Initialize 0th graph with random weights in one forward step // @TODO: Why do we need the THREAD_GUARD here? Why not run this on the main thread? THREAD_GUARD({ builders_[0]->build(graphs_[0], exampleBatch); graphs_[0]->forward(); }); // Copy weights from 0th graph to all other graphs // to have equal weights across devices ThreadPool pool(graphs_.size() - 1, graphs_.size() - 1); for(size_t i = 1; i < graphs_.size(); ++i) { auto init = [&](size_t i) { // initialize t-th graph and weights builders_[i]->build(graphs_[i], exampleBatch); graphs_[i]->forward(); // overwrite weights of t-th graph with weights from 0th graph graphs_[i]->params()->vals()->copyFrom(graphs_[0]->params()->vals()); }; pool.enqueue(init, i); } // ThreadPool destructor waits until completion of all tasks. // @TODO: can we use comm_->foreach()? } void SyncGraphGroup::initializeAvg() { Ptr<ExpressionGraph> graphAvg; // CPU-side temp std::string name = options_->get<std::string>("model"); if(filesystem::exists(name + ".orig.npz")) { // Load the averaged parameters into a temporary graph graphAvg = New<ExpressionGraph>(); graphAvg->setDevice({0, DeviceType::cpu}); graphAvg->load(name, false); graphAvg->forward(); // initialize parameters if needed } auto init = [&](size_t localDeviceIndex, size_t begin, size_t end) { size_t size = end-begin; // get the device-specific allocator auto paramsAllocator = New<TensorAllocator>(graphs_[localDeviceIndex]->getBackend()); paramsAllocs_[localDeviceIndex] = paramsAllocator; paramsAllocator->reserveExact(size * sizeof(float)); Tensor paramAvg; paramsAllocator->allocate(paramAvg, {1, (int)size}); paramsAvg_[localDeviceIndex] = paramAvg; if(graphAvg) paramAvg->copyFrom(graphAvg ->params()->vals()->subtensor(begin, size)); else paramAvg->copyFrom(graphs_[0]->params()->vals()->subtensor(begin, size)); // note: for multi-node, graphAvg and graphs_[0] contain a complete copy, from which // each MPI process copies only part into its respective shard(s) }; paramsAllocs_.resize(graphs_.size()); // allocators paramsAvg_.resize(graphs_.size()); // averaged parameters (shards; distributed over MPI processes if applicable) comm_->foreach(init, /*parallel=*/false); // @TODO: is sequential operation necessary here? (is the allocation stuff sufficiently reentrant or thread-separated?) } Ptr<data::BatchStats> SyncGraphGroup::collectStats() { size_t multiplier = devices_.size() * mpi_->numMPIProcesses() * delay_; return GraphGroup::collectStats(graphs_[0], builders_[0], multiplier); } void SyncGraphGroup::update(Ptr<data::Batch> batch) /*override*/ { ABORT_IF(finalized_, "Training has already finished."); // distribute the batch over (delay, local device, MPI rank) size_t numSubBatches = delay_ * devices_.size() * mpi_->numMPIProcesses(); auto subBatches = batch->split(numSubBatches); subBatches.resize(numSubBatches); // pad with nullptrs if out of data // Helper to access the subBatches array auto getSubBatch = [&](size_t t, size_t localDeviceIndex, size_t rank) { // 't' (the delay) should be slowest changing dimension. If subBatches are sorted by // length, then grouping sentences of similar length into the same delay step can // reduce unnecessary time spent in padding. return subBatches[(t * mpi_->numMPIProcesses() + rank) * devices_.size() + localDeviceIndex]; }; // Upon very first execution, reset everything if(first_) { LOG(info, "[{}] Processing first minibatch. Batches are processed as {} processes x {} GPUs/process x {} delay steps.", mpi_->idStr(), mpi_->numMPIProcesses(), devices_.size(), delay_); initialize(subBatches.front()); if(mvAvg_ && paramsAvg_.empty()) initializeAvg(); first_ = false; } // Compute gradients // This happens in multiple steps in case of delay_ > 1. std::vector<float> localDeviceCosts(devices_.size(), 0.f); // [local device index] aggregate cost for each local device for (size_t t = 0; t < delay_; t++) { // Execute single forward/backward step auto forwardBackward = [&](size_t localDeviceIndex, size_t /*begin*/, size_t /*end*/) { auto graph = graphs_[localDeviceIndex]; auto subBatch = getSubBatch(t, localDeviceIndex, mpi_->myMPIRank()); if(subBatch) { timer::Timer timer; auto costNode = builders_[localDeviceIndex]->build(graph, subBatch); LOG(info, timer.format(2, "after build: %ws")); graph->forward(); LOG(info, timer.format(2, "after forward (no sync): %ws")); //localDeviceCosts[localDeviceIndex] += costNode->scalar(); graph->backward(/*zero=*/t == 0); // only reset gradients to 0 if t = 0 LOG(info, timer.format(2, "after backward (no sync): %ws")); localDeviceCosts[localDeviceIndex] += costNode->scalar(); // moved here for time measurements; @TODO: move this back LOG(info, timer.format(2, "after scalar() (that's a sync): %ws")); } else { // empty batch: execute do-nothing fw-bw step for proper inits and resets graph->forward(); graph->backward(/*zero=*/t == 0); } }; comm_->foreach(forwardBackward); // compute gradients in parallel on each device. Aggregate if delay_ > 1. } // At this point, each device on each MPI process has a gradient aggregated over a subset of the sub-batches. // Update parameter shard with gradient shard auto update = [&](size_t idx, size_t begin, size_t end) { auto curGrad = graphs_[idx]->params()->grads()->subtensor(begin, end-begin); auto curParam = graphs_[idx]->params()->vals()->subtensor(begin, end-begin); // if individual gradients were averages, then need to average again over all subBatches auto div = subBatches.size(); if (options_->get<std::string>("cost-type") == "ce-sum") div = 1; if(div != 1) { using namespace functional; Element(_1 = _1 / (float)div, curGrad); } // actual model update shardOpt_[idx]->update(curParam, curGrad); if(mvAvg_) updateAvgParams( paramsAvg_[idx], curParam, scheduler_->numberOfBatches()); }; timer::Timer timer; comm_->scatterReduce(); // reduce gradients across all devices (globally) into shards LOG(info, timer.format(2, "after scatterReduce (has sync): %ws")); comm_->foreach(update); // per-shard model-update LOG(info, timer.format(2, "after model update (no sync): %ws")); comm_->allGather(); // distribute param value shards back LOG(info, timer.format(2, "after allGather (has sync): %ws")); // cost across all local devices (scheduler will aggregate cross-process) float localCost = 0; for(auto& c : localDeviceCosts) // localDeviceCosts is already summed up over delay steps localCost += c; // if localCost is average-based, we need to turn the sum over devices into an average as well if(options_->get<std::string>("cost-type") != "ce-sum") localCost /= numSubBatches; if(scheduler_) { // track and log localCost scheduler_->update(localCost, subBatches, mpi_); // save intermediate model (and optimizer state) to file if(scheduler_->saving()) save(); // process valid data set // This may save a model as well. if(scheduler_->validating()) { swapParamsAvg(); if (isMainProcess()) scheduler_->validate(graphs_); swapParamsAvg(); } } } void SyncGraphGroup::load() /*override*/ { if(!options_->get<bool>("no-reload")) { std::string name = options_->get<std::string>("model"); if(filesystem::exists(name)) { if(scheduler_) scheduler_->load(name); std::string nameGraph = name; if(mvAvg_ && filesystem::exists(name + ".orig.npz")) // Load the original parameters from model.npz.orig.npz nameGraph += ".orig.npz"; size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameGraph); // we just load it N times from disk (it'll be in disk cache after the first) // @TODO: probably we want to have the list of DeviceIds as an attribute std::vector<Ptr<Backend>> backends; for(auto graph : graphs_) backends.push_back(graph->getBackend()); shardOpt_[0]->load(name + ".optimizer.npz", shardOpt_, backends, [&](const std::vector<float>& optimizerStateVector, const OptimizerBase::ScatterStateSetFunc& setShardFn) { comm_->scatterState(optimizerStateVector, setShardFn); }); } else if(options_->has("pretrained-model")) { std::string nameInit = options_->get<std::string>("pretrained-model"); LOG(info, "Initialize model weights with the pre-trained model {}", nameInit); size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameInit, false); } } } void SyncGraphGroup::save(bool final) /*override*/ { barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}!", this->mpi_->idStr(), __LINE__); // do final validation if(final && scheduler_) { // bring the smoothed model in // Note that it is sharded. For multi-node, it is sharded over multiple machines, so this is a network access. // Also note that the swap must run on all MPI processes concurrently, although only one actually validates. LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if (isMainProcess()) // in multi-node, only first MPI process saves the model (they are all identical) scheduler_->validate(graphs_, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } std::string name = options_->get<std::string>("model"); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // if smoothing then save original (unsmoothed) parameters as well // @TODO: Check whether we are reloading the correct file (the unsmoothed one). if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) // only save from one MPI process // Save the original parameters in model.npz.orig.npz builders_[0]->save(graphs_[0], name + ".orig.npz", true); // Temporarily switch to the averaged parameters // Note: the smoothed model is sharded across GPUs, and across MPI processes if applicable. This brings it into MPI process[*].device[*] LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file if (isMainProcess()) { // only save from one MPI process // if not overwrite then save a copy with number of updates in the model pathname LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if(!options_->get<bool>("overwrite") && !final) { std::string numberOfBatches = scheduler_ ? std::to_string(scheduler_->numberOfBatches()) : "unknown"; std::string nameOverwrite = name; nameOverwrite.replace(name.size() - 4, 4, ".iter" + numberOfBatches + ".npz"); // @TODO: use insert? builders_[0]->save(graphs_[0], nameOverwrite); } LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file builders_[0]->save(graphs_[0], name, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save scheduler-related state if (scheduler_) scheduler_->save(name); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } // Switch back to the original parameters LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); #if 1 // temporary, for testing of saving distributed models; must be identical to .orig.npz if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) builders_[0]->save(graphs_[0], name + ".orig_after_swapping.npz", true); #endif LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // persist optimizer state LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); shardOpt_[0]->save(name + ".optimizer.npz", shardOpt_, [&](const OptimizerBase::GatherStateGetFunc& getShardFn) { return comm_->gatherState(getShardFn); }, isMainProcess()); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } } // namespace marian <commit_msg>(added a comment)<commit_after>#include "training/graph_group_sync.h" namespace marian { SyncGraphGroup::SyncGraphGroup(Ptr<Config> config) : GraphGroup(config), ExponentialSmoothing{options_->get<float>("exponential-smoothing")}, delay_{options_->get<size_t>("optimizer-delay")} { // @TODO: rename to something else; delay means delayed updated, not accumulation mpi_ = initMPI(/*multiThreaded=*/false); // when not running under MPI, this will be a fake object that represents a one-MPI-process setup devices_ = options_->getDevices(mpi_->myMPIRank(), mpi_->numMPIProcesses()); for(auto device : devices_) { auto graph = New<ExpressionGraph>(); graph->setDevice(device); graph->reserveWorkspaceMB(options_->get<size_t>("workspace")); graph->getBackend()->setClip(options_->get<float>("clip-gemm")); graphs_.push_back(graph); shardOpt_.push_back(Optimizer(options_)); builders_.push_back(models::from_config(options_, models::usage::training)); } // Note: We may well end up with only one MPI process or only one graph per worker. // This part of the code will not special-case any of this here. // Rather, it is assumed that the communicator knows to reduce unnecessary transfers to no-ops. comm_ = createCommunicator(graphs_, /*noNccl=*/options_->get<bool>("no-nccl", false), /*mpi=*/mpi_); } void SyncGraphGroup::setScheduler(Ptr<Scheduler> scheduler) /*override*/ { scheduler_ = scheduler; // optimizer has to be registered last to see changes of learning rate // @TODO: ^^Fix this comment. Either it refers to the scheduler, or it should be moved. Which one? scheduler_->registerTrainingObserver(scheduler_); for(auto opt : shardOpt_) scheduler_->registerTrainingObserver(opt); } void SyncGraphGroup::initialize(const Ptr<data::Batch>& exampleBatch) { // Initialize 0th graph with random weights in one forward step // @TODO: Why do we need the THREAD_GUARD here? Why not run this on the main thread? THREAD_GUARD({ builders_[0]->build(graphs_[0], exampleBatch); graphs_[0]->forward(); }); // Copy weights from 0th graph to all other graphs // to have equal weights across devices ThreadPool pool(graphs_.size() - 1, graphs_.size() - 1); for(size_t i = 1; i < graphs_.size(); ++i) { auto init = [&](size_t i) { // initialize t-th graph and weights builders_[i]->build(graphs_[i], exampleBatch); graphs_[i]->forward(); // overwrite weights of t-th graph with weights from 0th graph graphs_[i]->params()->vals()->copyFrom(graphs_[0]->params()->vals()); }; pool.enqueue(init, i); } // ThreadPool destructor waits until completion of all tasks. // @TODO: can we use comm_->foreach()? } void SyncGraphGroup::initializeAvg() { Ptr<ExpressionGraph> graphAvg; // CPU-side temp std::string name = options_->get<std::string>("model"); if(filesystem::exists(name + ".orig.npz")) { // Load the averaged parameters into a temporary graph graphAvg = New<ExpressionGraph>(); graphAvg->setDevice({0, DeviceType::cpu}); graphAvg->load(name, false); graphAvg->forward(); // initialize parameters if needed } auto init = [&](size_t localDeviceIndex, size_t begin, size_t end) { size_t size = end-begin; // get the device-specific allocator auto paramsAllocator = New<TensorAllocator>(graphs_[localDeviceIndex]->getBackend()); paramsAllocs_[localDeviceIndex] = paramsAllocator; paramsAllocator->reserveExact(size * sizeof(float)); Tensor paramAvg; paramsAllocator->allocate(paramAvg, {1, (int)size}); paramsAvg_[localDeviceIndex] = paramAvg; if(graphAvg) paramAvg->copyFrom(graphAvg ->params()->vals()->subtensor(begin, size)); else paramAvg->copyFrom(graphs_[0]->params()->vals()->subtensor(begin, size)); // note: for multi-node, graphAvg and graphs_[0] contain a complete copy, from which // each MPI process copies only part into its respective shard(s) }; paramsAllocs_.resize(graphs_.size()); // allocators paramsAvg_.resize(graphs_.size()); // averaged parameters (shards; distributed over MPI processes if applicable) comm_->foreach(init, /*parallel=*/false); // @TODO: is sequential operation necessary here? (is the allocation stuff sufficiently reentrant or thread-separated?) } Ptr<data::BatchStats> SyncGraphGroup::collectStats() { // @TODO: This should only run on MPI process 0. Also we can share vv this vv expression with update(). size_t multiplier = devices_.size() * mpi_->numMPIProcesses() * delay_; return GraphGroup::collectStats(graphs_[0], builders_[0], multiplier); } void SyncGraphGroup::update(Ptr<data::Batch> batch) /*override*/ { ABORT_IF(finalized_, "Training has already finished."); // distribute the batch over (delay, local device, MPI rank) size_t numSubBatches = delay_ * devices_.size() * mpi_->numMPIProcesses(); auto subBatches = batch->split(numSubBatches); subBatches.resize(numSubBatches); // pad with nullptrs if out of data // Helper to access the subBatches array auto getSubBatch = [&](size_t t, size_t localDeviceIndex, size_t rank) { // 't' (the delay) should be slowest changing dimension. If subBatches are sorted by // length, then grouping sentences of similar length into the same delay step can // reduce unnecessary time spent in padding. return subBatches[(t * mpi_->numMPIProcesses() + rank) * devices_.size() + localDeviceIndex]; }; // Upon very first execution, reset everything if(first_) { LOG(info, "[{}] Processing first minibatch. Batches are processed as {} processes x {} GPUs/process x {} delay steps.", mpi_->idStr(), mpi_->numMPIProcesses(), devices_.size(), delay_); initialize(subBatches.front()); if(mvAvg_ && paramsAvg_.empty()) initializeAvg(); first_ = false; } // Compute gradients // This happens in multiple steps in case of delay_ > 1. std::vector<float> localDeviceCosts(devices_.size(), 0.f); // [local device index] aggregate cost for each local device for (size_t t = 0; t < delay_; t++) { // Execute single forward/backward step auto forwardBackward = [&](size_t localDeviceIndex, size_t /*begin*/, size_t /*end*/) { auto graph = graphs_[localDeviceIndex]; auto subBatch = getSubBatch(t, localDeviceIndex, mpi_->myMPIRank()); if(subBatch) { timer::Timer timer; auto costNode = builders_[localDeviceIndex]->build(graph, subBatch); LOG(info, timer.format(2, "after build: %ws")); graph->forward(); LOG(info, timer.format(2, "after forward (no sync): %ws")); //localDeviceCosts[localDeviceIndex] += costNode->scalar(); graph->backward(/*zero=*/t == 0); // only reset gradients to 0 if t = 0 LOG(info, timer.format(2, "after backward (no sync): %ws")); localDeviceCosts[localDeviceIndex] += costNode->scalar(); // moved here for time measurements; @TODO: move this back LOG(info, timer.format(2, "after scalar() (that's a sync): %ws")); } else { // empty batch: execute do-nothing fw-bw step for proper inits and resets graph->forward(); graph->backward(/*zero=*/t == 0); } }; comm_->foreach(forwardBackward); // compute gradients in parallel on each device. Aggregate if delay_ > 1. } // At this point, each device on each MPI process has a gradient aggregated over a subset of the sub-batches. // Update parameter shard with gradient shard auto update = [&](size_t idx, size_t begin, size_t end) { auto curGrad = graphs_[idx]->params()->grads()->subtensor(begin, end-begin); auto curParam = graphs_[idx]->params()->vals()->subtensor(begin, end-begin); // if individual gradients were averages, then need to average again over all subBatches auto div = subBatches.size(); if (options_->get<std::string>("cost-type") == "ce-sum") div = 1; if(div != 1) { using namespace functional; Element(_1 = _1 / (float)div, curGrad); } // actual model update shardOpt_[idx]->update(curParam, curGrad); if(mvAvg_) updateAvgParams( paramsAvg_[idx], curParam, scheduler_->numberOfBatches()); }; timer::Timer timer; comm_->scatterReduce(); // reduce gradients across all devices (globally) into shards LOG(info, timer.format(2, "after scatterReduce (has sync): %ws")); comm_->foreach(update); // per-shard model-update LOG(info, timer.format(2, "after model update (no sync): %ws")); comm_->allGather(); // distribute param value shards back LOG(info, timer.format(2, "after allGather (has sync): %ws")); // cost across all local devices (scheduler will aggregate cross-process) float localCost = 0; for(auto& c : localDeviceCosts) // localDeviceCosts is already summed up over delay steps localCost += c; // if localCost is average-based, we need to turn the sum over devices into an average as well if(options_->get<std::string>("cost-type") != "ce-sum") localCost /= numSubBatches; if(scheduler_) { // track and log localCost scheduler_->update(localCost, subBatches, mpi_); // save intermediate model (and optimizer state) to file if(scheduler_->saving()) save(); // process valid data set // This may save a model as well. if(scheduler_->validating()) { swapParamsAvg(); if (isMainProcess()) scheduler_->validate(graphs_); swapParamsAvg(); } } } void SyncGraphGroup::load() /*override*/ { if(!options_->get<bool>("no-reload")) { std::string name = options_->get<std::string>("model"); if(filesystem::exists(name)) { if(scheduler_) scheduler_->load(name); std::string nameGraph = name; if(mvAvg_ && filesystem::exists(name + ".orig.npz")) // Load the original parameters from model.npz.orig.npz nameGraph += ".orig.npz"; size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameGraph); // we just load it N times from disk (it'll be in disk cache after the first) // @TODO: probably we want to have the list of DeviceIds as an attribute std::vector<Ptr<Backend>> backends; for(auto graph : graphs_) backends.push_back(graph->getBackend()); shardOpt_[0]->load(name + ".optimizer.npz", shardOpt_, backends, [&](const std::vector<float>& optimizerStateVector, const OptimizerBase::ScatterStateSetFunc& setShardFn) { comm_->scatterState(optimizerStateVector, setShardFn); }); } else if(options_->has("pretrained-model")) { std::string nameInit = options_->get<std::string>("pretrained-model"); LOG(info, "Initialize model weights with the pre-trained model {}", nameInit); size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameInit, false); } } } void SyncGraphGroup::save(bool final) /*override*/ { barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}!", this->mpi_->idStr(), __LINE__); // do final validation if(final && scheduler_) { // bring the smoothed model in // Note that it is sharded. For multi-node, it is sharded over multiple machines, so this is a network access. // Also note that the swap must run on all MPI processes concurrently, although only one actually validates. LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if (isMainProcess()) // in multi-node, only first MPI process saves the model (they are all identical) scheduler_->validate(graphs_, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } std::string name = options_->get<std::string>("model"); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // if smoothing then save original (unsmoothed) parameters as well // @TODO: Check whether we are reloading the correct file (the unsmoothed one). if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) // only save from one MPI process // Save the original parameters in model.npz.orig.npz builders_[0]->save(graphs_[0], name + ".orig.npz", true); // Temporarily switch to the averaged parameters // Note: the smoothed model is sharded across GPUs, and across MPI processes if applicable. This brings it into MPI process[*].device[*] LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file if (isMainProcess()) { // only save from one MPI process // if not overwrite then save a copy with number of updates in the model pathname LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if(!options_->get<bool>("overwrite") && !final) { std::string numberOfBatches = scheduler_ ? std::to_string(scheduler_->numberOfBatches()) : "unknown"; std::string nameOverwrite = name; nameOverwrite.replace(name.size() - 4, 4, ".iter" + numberOfBatches + ".npz"); // @TODO: use insert? builders_[0]->save(graphs_[0], nameOverwrite); } LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file builders_[0]->save(graphs_[0], name, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save scheduler-related state if (scheduler_) scheduler_->save(name); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } // Switch back to the original parameters LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); #if 1 // temporary, for testing of saving distributed models; must be identical to .orig.npz if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) builders_[0]->save(graphs_[0], name + ".orig_after_swapping.npz", true); #endif LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // persist optimizer state LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); shardOpt_[0]->save(name + ".optimizer.npz", shardOpt_, [&](const OptimizerBase::GatherStateGetFunc& getShardFn) { return comm_->gatherState(getShardFn); }, isMainProcess()); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } } // namespace marian <|endoftext|>
<commit_before>// // // inline bool no_such_file() { return no_file; }; <commit_msg>Delete file_system__no_such_file.cpp<commit_after><|endoftext|>
<commit_before>#include "videosourcefactory.h" namespace gg { VideoSourceFactory VideoSourceFactory::_factory_singleton; VideoSourceFactory::VideoSourceFactory() { // TODO } VideoSourceFactory::~VideoSourceFactory() { // TODO } VideoSourceFactory & VideoSourceFactory::get_instance() { return _factory_singleton; } IVideoSource * VideoSourceFactory::get_device(Device device, ColourSpace colour) { // TODO return nullptr; } } <commit_msg>Issue #121: implemented free_device function of VideoSourceFactory<commit_after>#include "videosourcefactory.h" namespace gg { VideoSourceFactory VideoSourceFactory::_factory_singleton; VideoSourceFactory::VideoSourceFactory() { // TODO } VideoSourceFactory::~VideoSourceFactory() { // TODO } VideoSourceFactory & VideoSourceFactory::get_instance() { return _factory_singleton; } IVideoSource * VideoSourceFactory::get_device(Device device, ColourSpace colour) { // TODO } void VideoSourceFactory::free_device(Device device) { if (_devices[(int) device] != nullptr) delete _devices[(int) device]; _devices[(int) device] = nullptr; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "SemanticalException.hpp" #include "VisitorUtils.hpp" #include "mangling.hpp" #include "Options.hpp" #include "Type.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "Variable.hpp" #include "ast/FunctionsAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/TypeTransformer.hpp" #include "ast/ASTVisitor.hpp" #include "ast/GetTypeVisitor.hpp" using namespace eddic; namespace { class MemberFunctionAnnotator : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> context; std::string parent_struct; ast::Struct current_struct; public: void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::Struct& struct_){ current_struct = struct_; parent_struct = struct_.Content->name; visit_each_non_variant(*this, struct_.Content->constructors); visit_each_non_variant(*this, struct_.Content->destructors); visit_each_non_variant(*this, struct_.Content->functions); parent_struct = ""; } template<typename T> void annotate(T& declaration){ if(!declaration.Content->marked){ declaration.Content->struct_name = parent_struct; declaration.Content->struct_type = current_struct.Content->struct_type; ast::PointerType paramType; if(current_struct.Content->template_types.empty()){ ast::SimpleType struct_type; struct_type.type = parent_struct; struct_type.const_ = false; paramType.type = struct_type; } else { ast::TemplateType struct_type; struct_type.type = parent_struct; struct_type.template_types = current_struct.Content->template_types; struct_type.resolved = true; paramType.type = struct_type; } ast::FunctionParameter param; param.parameterName = "this"; param.parameterType = paramType; declaration.Content->parameters.insert(declaration.Content->parameters.begin(), param); } } void operator()(ast::Constructor& constructor){ annotate(constructor); } void operator()(ast::Destructor& destructor){ annotate(destructor); } void operator()(ast::FunctionDeclaration& declaration){ if(!parent_struct.empty()){ annotate(declaration); } } AUTO_IGNORE_OTHERS() }; class FunctionInserterVisitor : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> context; public: AUTO_RECURSE_STRUCT() void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::FunctionDeclaration& declaration){ if(!declaration.Content->marked){ auto return_type = visit(ast::TypeTransformer(context), declaration.Content->returnType); auto signature = std::make_shared<Function>(return_type, declaration.Content->functionName); if(return_type->is_array()){ throw SemanticalException("Cannot return array from function", declaration.Content->position); } if(return_type->is_custom_type()){ throw SemanticalException("Cannot return struct from function", declaration.Content->position); } for(auto& param : declaration.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = declaration.Content->struct_name; signature->struct_type = declaration.Content->struct_type; signature->context = declaration.Content->context; declaration.Content->mangledName = signature->mangledName = mangle(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("The function " + signature->mangledName + " has already been defined", declaration.Content->position); } context->addFunction(signature); } } void operator()(ast::Constructor& constructor){ if(!constructor.Content->marked){ auto signature = std::make_shared<Function>(VOID, "ctor"); for(auto& param : constructor.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = constructor.Content->struct_name; signature->struct_type = constructor.Content->struct_type; constructor.Content->mangledName = signature->mangledName = mangle_ctor(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("The constructor " + signature->name + " has already been defined", constructor.Content->position); } context->addFunction(signature); context->getFunction(signature->mangledName)->context = constructor.Content->context; } } void operator()(ast::Destructor& destructor){ if(!destructor.Content->marked){ auto signature = std::make_shared<Function>(VOID, "dtor"); for(auto& param : destructor.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = destructor.Content->struct_name; signature->struct_type = destructor.Content->struct_type; destructor.Content->mangledName = signature->mangledName = mangle_dtor(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("Only one destructor per struct is allowed", destructor.Content->position); } context->addFunction(signature); context->getFunction(signature->mangledName)->context = destructor.Content->context; } } AUTO_IGNORE_OTHERS() private: std::string parent_struct; }; class FunctionCheckerVisitor : public boost::static_visitor<> { private: std::shared_ptr<Function> currentFunction; std::shared_ptr<GlobalContext> context; public: AUTO_RECURSE_GLOBAL_DECLARATION() AUTO_RECURSE_MEMBER_VALUE() AUTO_RECURSE_STRUCT() void operator()(ast::Constructor& function){ check_each(function.Content->instructions); } void operator()(ast::Destructor& function){ check_each(function.Content->instructions); } void operator()(ast::DefaultCase& default_case){ check_each(default_case.instructions); } void operator()(ast::Foreach& foreach_){ check_each(foreach_.Content->instructions); } void operator()(ast::ForeachIn& foreach_){ check_each(foreach_.Content->instructions); } void operator()(ast::If& if_){ check_value(if_.Content->condition); check_each(if_.Content->instructions); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ check_value(elseIf.condition); check_each(elseIf.instructions); } void operator()(ast::Else& else_){ check_each(else_.instructions); } template<typename T> void check_each(std::vector<T>& values){ for(std::size_t i = 0; i < values.size(); ++i){ check_value(values[i]); } } template<typename V> void check_value(V& value){ if(auto* ptr = boost::get<ast::FunctionCall>(&value)){ auto functionCall = *ptr; if(functionCall.Content->template_types.empty() || functionCall.Content->resolved){ check_each(functionCall.Content->values); std::string name = functionCall.Content->function_name; auto types = get_types(functionCall); auto mangled = mangle(name, types); auto original_mangled = mangled; //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); functionCall.Content->mangled_name = mangled; functionCall.Content->function = context->getFunction(mangled); } else { auto local_context = functionCall.Content->context->function(); if(local_context && local_context->struct_type && context->struct_exists(local_context->struct_type->mangle())){ auto struct_type = local_context->struct_type; mangled = mangle(name, types, struct_type); //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm, struct_type); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); ast::MemberFunctionCall member_function_call; member_function_call.Content->function = context->getFunction(mangled); member_function_call.Content->context = functionCall.Content->context; member_function_call.Content->mangled_name = mangled; member_function_call.Content->position = functionCall.Content->position; member_function_call.Content->object_name = "this"; member_function_call.Content->function_name = functionCall.Content->function_name; member_function_call.Content->resolved = functionCall.Content->resolved; member_function_call.Content->template_types = functionCall.Content->template_types; member_function_call.Content->values = functionCall.Content->values; value = member_function_call; return; } } throw SemanticalException("The function \"" + unmangle(original_mangled) + "\" does not exists", functionCall.Content->position); } } } else { visit(*this, value); } } void operator()(ast::For& for_){ if(for_.Content->start){ check_value(*for_.Content->start); } if(for_.Content->condition){ check_value(*for_.Content->condition); } if(for_.Content->repeat){ check_value(*for_.Content->repeat); } check_each(for_.Content->instructions); } void operator()(ast::While& while_){ check_value(while_.Content->condition); check_each(while_.Content->instructions); } void operator()(ast::DoWhile& while_){ check_value(while_.Content->condition); check_each(while_.Content->instructions); } void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::FunctionDeclaration& declaration){ currentFunction = context->getFunction(declaration.Content->mangledName); check_each(declaration.Content->instructions); } void permute(std::vector<std::vector<std::shared_ptr<const Type>>>& perms, std::vector<std::shared_ptr<const Type>>& types, int start){ for(std::size_t i = start; i < types.size(); ++i){ if(!types[i]->is_pointer() && !types[i]->is_array()){ std::vector<std::shared_ptr<const Type>> copy = types; copy[i] = new_pointer_type(types[i]); perms.push_back(copy); permute(perms, copy, i + 1); } } } std::vector<std::vector<std::shared_ptr<const Type>>> permutations(std::vector<std::shared_ptr<const Type>>& types){ std::vector<std::vector<std::shared_ptr<const Type>>> perms; permute(perms, types, 0); return perms; } template<typename T> std::vector<std::shared_ptr<const Type>> get_types(T& functionCall){ std::vector<std::shared_ptr<const Type>> types; ast::GetTypeVisitor visitor; for(auto& value : functionCall.Content->values){ types.push_back(visit(visitor, value)); } return types; } void operator()(ast::FunctionCall&){ ASSERT_PATH_NOT_TAKEN("Should be handled by check_value"); } void operator()(ast::MemberFunctionCall& functionCall){ if(functionCall.Content->template_types.empty() || functionCall.Content->resolved){ auto var = functionCall.Content->context->getVariable(functionCall.Content->object_name); auto type = var->type(); auto struct_type = type->is_pointer() ? type->data_type() : type; check_each(functionCall.Content->values); std::string name = functionCall.Content->function_name; auto types = get_types(functionCall); std::string mangled = mangle(name, types, struct_type); //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm, struct_type); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); functionCall.Content->mangled_name = mangled; functionCall.Content->function = context->getFunction(mangled); } else { throw SemanticalException("The member function \"" + unmangle(mangled) + "\" does not exists", functionCall.Content->position); } } } void operator()(ast::Switch& switch_){ check_value(switch_.Content->value); visit_each_non_variant(*this, switch_.Content->cases); visit_optional_non_variant(*this, switch_.Content->default_case); } void operator()(ast::SwitchCase& switch_case){ check_value(switch_case.value); visit_each(*this, switch_case.instructions); } void operator()(ast::Assignment& assignment){ visit(*this, assignment.Content->left_value); check_value(assignment.Content->value); } void operator()(ast::VariableDeclaration& declaration){ if(declaration.Content->value){ check_value(*declaration.Content->value); } } void operator()(ast::Unary& value){ check_value(value.Content->value); } void operator()(ast::BuiltinOperator& builtin){ check_each(builtin.Content->values); } void operator()(ast::Expression& value){ check_value(value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ check_value(operation.get<1>()); }); } void operator()(ast::Return& return_){ return_.Content->function = currentFunction; check_value(return_.Content->value); } AUTO_IGNORE_OTHERS() }; } //end of anonymous namespace void ast::defineMemberFunctions(ast::SourceFile& program){ MemberFunctionAnnotator annotator; annotator(program); } void ast::defineFunctions(ast::SourceFile& program){ //First phase : Collect functions FunctionInserterVisitor inserterVisitor; inserterVisitor(program); //Second phase : Verify calls FunctionCheckerVisitor checkerVisitor; checkerVisitor(program); } <commit_msg>Fix recursion<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "SemanticalException.hpp" #include "VisitorUtils.hpp" #include "mangling.hpp" #include "Options.hpp" #include "Type.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "Variable.hpp" #include "ast/FunctionsAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/TypeTransformer.hpp" #include "ast/ASTVisitor.hpp" #include "ast/GetTypeVisitor.hpp" using namespace eddic; namespace { class MemberFunctionAnnotator : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> context; std::string parent_struct; ast::Struct current_struct; public: void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::Struct& struct_){ current_struct = struct_; parent_struct = struct_.Content->name; visit_each_non_variant(*this, struct_.Content->constructors); visit_each_non_variant(*this, struct_.Content->destructors); visit_each_non_variant(*this, struct_.Content->functions); parent_struct = ""; } template<typename T> void annotate(T& declaration){ if(!declaration.Content->marked){ declaration.Content->struct_name = parent_struct; declaration.Content->struct_type = current_struct.Content->struct_type; ast::PointerType paramType; if(current_struct.Content->template_types.empty()){ ast::SimpleType struct_type; struct_type.type = parent_struct; struct_type.const_ = false; paramType.type = struct_type; } else { ast::TemplateType struct_type; struct_type.type = parent_struct; struct_type.template_types = current_struct.Content->template_types; struct_type.resolved = true; paramType.type = struct_type; } ast::FunctionParameter param; param.parameterName = "this"; param.parameterType = paramType; declaration.Content->parameters.insert(declaration.Content->parameters.begin(), param); } } void operator()(ast::Constructor& constructor){ annotate(constructor); } void operator()(ast::Destructor& destructor){ annotate(destructor); } void operator()(ast::FunctionDeclaration& declaration){ if(!parent_struct.empty()){ annotate(declaration); } } AUTO_IGNORE_OTHERS() }; class FunctionInserterVisitor : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> context; public: AUTO_RECURSE_STRUCT() void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::FunctionDeclaration& declaration){ if(!declaration.Content->marked){ auto return_type = visit(ast::TypeTransformer(context), declaration.Content->returnType); auto signature = std::make_shared<Function>(return_type, declaration.Content->functionName); if(return_type->is_array()){ throw SemanticalException("Cannot return array from function", declaration.Content->position); } if(return_type->is_custom_type()){ throw SemanticalException("Cannot return struct from function", declaration.Content->position); } for(auto& param : declaration.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = declaration.Content->struct_name; signature->struct_type = declaration.Content->struct_type; signature->context = declaration.Content->context; declaration.Content->mangledName = signature->mangledName = mangle(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("The function " + signature->mangledName + " has already been defined", declaration.Content->position); } context->addFunction(signature); } } void operator()(ast::Constructor& constructor){ if(!constructor.Content->marked){ auto signature = std::make_shared<Function>(VOID, "ctor"); for(auto& param : constructor.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = constructor.Content->struct_name; signature->struct_type = constructor.Content->struct_type; constructor.Content->mangledName = signature->mangledName = mangle_ctor(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("The constructor " + signature->name + " has already been defined", constructor.Content->position); } context->addFunction(signature); context->getFunction(signature->mangledName)->context = constructor.Content->context; } } void operator()(ast::Destructor& destructor){ if(!destructor.Content->marked){ auto signature = std::make_shared<Function>(VOID, "dtor"); for(auto& param : destructor.Content->parameters){ auto paramType = visit(ast::TypeTransformer(context), param.parameterType); signature->parameters.push_back(ParameterType(param.parameterName, paramType)); } signature->struct_ = destructor.Content->struct_name; signature->struct_type = destructor.Content->struct_type; destructor.Content->mangledName = signature->mangledName = mangle_dtor(signature); if(context->exists(signature->mangledName)){ throw SemanticalException("Only one destructor per struct is allowed", destructor.Content->position); } context->addFunction(signature); context->getFunction(signature->mangledName)->context = destructor.Content->context; } } AUTO_IGNORE_OTHERS() private: std::string parent_struct; }; class FunctionCheckerVisitor : public boost::static_visitor<> { private: std::shared_ptr<Function> currentFunction; std::shared_ptr<GlobalContext> context; public: AUTO_RECURSE_GLOBAL_DECLARATION() AUTO_RECURSE_MEMBER_VALUE() AUTO_RECURSE_STRUCT() void operator()(ast::Constructor& function){ check_each(function.Content->instructions); } void operator()(ast::Destructor& function){ check_each(function.Content->instructions); } void operator()(ast::DefaultCase& default_case){ check_each(default_case.instructions); } void operator()(ast::Foreach& foreach_){ check_each(foreach_.Content->instructions); } void operator()(ast::ForeachIn& foreach_){ check_each(foreach_.Content->instructions); } void operator()(ast::If& if_){ check_value(if_.Content->condition); check_each(if_.Content->instructions); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ check_value(elseIf.condition); check_each(elseIf.instructions); } void operator()(ast::Else& else_){ check_each(else_.instructions); } template<typename T> void check_each(std::vector<T>& values){ for(std::size_t i = 0; i < values.size(); ++i){ check_value(values[i]); } } template<typename V> void check_value(V& value){ if(auto* ptr = boost::get<ast::FunctionCall>(&value)){ auto functionCall = *ptr; if(functionCall.Content->template_types.empty() || functionCall.Content->resolved){ check_each(functionCall.Content->values); std::string name = functionCall.Content->function_name; auto types = get_types(functionCall); auto mangled = mangle(name, types); auto original_mangled = mangled; //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); functionCall.Content->mangled_name = mangled; functionCall.Content->function = context->getFunction(mangled); } else { auto local_context = functionCall.Content->context->function(); if(local_context && local_context->struct_type && context->struct_exists(local_context->struct_type->mangle())){ auto struct_type = local_context->struct_type; mangled = mangle(name, types, struct_type); //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm, struct_type); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); ast::MemberFunctionCall member_function_call; member_function_call.Content->function = context->getFunction(mangled); member_function_call.Content->context = functionCall.Content->context; member_function_call.Content->mangled_name = mangled; member_function_call.Content->position = functionCall.Content->position; member_function_call.Content->object_name = "this"; member_function_call.Content->function_name = functionCall.Content->function_name; member_function_call.Content->resolved = functionCall.Content->resolved; member_function_call.Content->template_types = functionCall.Content->template_types; member_function_call.Content->values = functionCall.Content->values; value = member_function_call; return; } } throw SemanticalException("The function \"" + unmangle(original_mangled) + "\" does not exists", functionCall.Content->position); } } } else { visit(*this, value); } } void operator()(ast::For& for_){ if(for_.Content->start){ check_value(*for_.Content->start); } if(for_.Content->condition){ check_value(*for_.Content->condition); } if(for_.Content->repeat){ check_value(*for_.Content->repeat); } check_each(for_.Content->instructions); } void operator()(ast::While& while_){ check_value(while_.Content->condition); check_each(while_.Content->instructions); } void operator()(ast::DoWhile& while_){ check_value(while_.Content->condition); check_each(while_.Content->instructions); } void operator()(ast::SourceFile& program){ context = program.Content->context; visit_each(*this, program.Content->blocks); } void operator()(ast::FunctionDeclaration& declaration){ currentFunction = context->getFunction(declaration.Content->mangledName); check_each(declaration.Content->instructions); } void permute(std::vector<std::vector<std::shared_ptr<const Type>>>& perms, std::vector<std::shared_ptr<const Type>>& types, int start){ for(std::size_t i = start; i < types.size(); ++i){ if(!types[i]->is_pointer() && !types[i]->is_array()){ std::vector<std::shared_ptr<const Type>> copy = types; copy[i] = new_pointer_type(types[i]); perms.push_back(copy); permute(perms, copy, i + 1); } } } std::vector<std::vector<std::shared_ptr<const Type>>> permutations(std::vector<std::shared_ptr<const Type>>& types){ std::vector<std::vector<std::shared_ptr<const Type>>> perms; permute(perms, types, 0); return perms; } template<typename T> std::vector<std::shared_ptr<const Type>> get_types(T& functionCall){ std::vector<std::shared_ptr<const Type>> types; ast::GetTypeVisitor visitor; for(auto& value : functionCall.Content->values){ types.push_back(visit(visitor, value)); } return types; } void operator()(ast::FunctionCall&){ ASSERT_PATH_NOT_TAKEN("Should be handled by check_value"); } void operator()(ast::MemberFunctionCall& functionCall){ if(functionCall.Content->template_types.empty() || functionCall.Content->resolved){ auto var = functionCall.Content->context->getVariable(functionCall.Content->object_name); auto type = var->type(); auto struct_type = type->is_pointer() ? type->data_type() : type; check_each(functionCall.Content->values); std::string name = functionCall.Content->function_name; auto types = get_types(functionCall); std::string mangled = mangle(name, types, struct_type); //If the function does not exists, try implicit conversions to pointers if(!context->exists(mangled)){ auto perms = permutations(types); for(auto& perm : perms){ mangled = mangle(name, perm, struct_type); if(context->exists(mangled)){ break; } } } if(context->exists(mangled)){ context->addReference(mangled); functionCall.Content->mangled_name = mangled; functionCall.Content->function = context->getFunction(mangled); } else { throw SemanticalException("The member function \"" + unmangle(mangled) + "\" does not exists", functionCall.Content->position); } } } void operator()(ast::Switch& switch_){ check_value(switch_.Content->value); visit_each_non_variant(*this, switch_.Content->cases); visit_optional_non_variant(*this, switch_.Content->default_case); } void operator()(ast::SwitchCase& switch_case){ check_value(switch_case.value); check_each(switch_case.instructions); } void operator()(ast::Assignment& assignment){ visit(*this, assignment.Content->left_value); check_value(assignment.Content->value); } void operator()(ast::VariableDeclaration& declaration){ if(declaration.Content->value){ check_value(*declaration.Content->value); } } void operator()(ast::Unary& value){ check_value(value.Content->value); } void operator()(ast::BuiltinOperator& builtin){ check_each(builtin.Content->values); } void operator()(ast::Expression& value){ check_value(value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ check_value(operation.get<1>()); }); } void operator()(ast::Return& return_){ return_.Content->function = currentFunction; check_value(return_.Content->value); } AUTO_IGNORE_OTHERS() }; } //end of anonymous namespace void ast::defineMemberFunctions(ast::SourceFile& program){ MemberFunctionAnnotator annotator; annotator(program); } void ast::defineFunctions(ast::SourceFile& program){ //First phase : Collect functions FunctionInserterVisitor inserterVisitor; inserterVisitor(program); //Second phase : Verify calls FunctionCheckerVisitor checkerVisitor; checkerVisitor(program); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include <QLabel> #include <QDockWidget> #include <QSettings> #include <QAction> #include <QMenuBar> #include <QMenu> #include <QFile> #include <QMessageBox> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // menu - file QMenu *menuFile = new QMenu("File", this); this->menuBar()->addMenu(menuFile); // action - new block QAction *actNewBlock = new QAction("new block", this); menuFile->addAction(actNewBlock); actNewBlock->setShortcut(Qt::Key_N | Qt::CTRL); connect(actNewBlock, SIGNAL(triggered(bool)), this, SLOT(slotActionNewBlock())); // action - save QAction *actSave = new QAction("save block", this); menuFile->addAction(actSave); actSave->setShortcut(Qt::Key_S | Qt::CTRL); connect(actSave, SIGNAL(triggered(bool)), this, SLOT(slotActionSave())); // action - quit QAction *actQuit = new QAction("quit", this); menuFile->addAction(actQuit); actQuit->setShortcut(Qt::Key_Q | Qt::CTRL); connect(actQuit, SIGNAL(triggered(bool)), this, SLOT(slotActionQuit())); // central widget this->widgetMain = new QTabWidget(this); this->setCentralWidget(this->widgetMain); // block browser this->blockBrowser = new BlockBrowser(this); connect(this->blockBrowser, SIGNAL(signalFileOpen(QString)), this, SLOT(slotFileOpen(QString))); // block browser dock QDockWidget *dock = new QDockWidget("", this); dock->setObjectName("BlockBrowser"); dock->setAllowedAreas(Qt::LeftDockWidgetArea); dock->setWidget(this->blockBrowser); dock->setFloating(false); dock->setFeatures(QDockWidget::NoDockWidgetFeatures); this->addDockWidget(Qt::LeftDockWidgetArea, dock); // restore window state QSettings s; this->restoreState(s.value("Mainwindow/State").toByteArray()); this->restoreGeometry(s.value("MainWindow/Geometry").toByteArray()); } MainWindow::~MainWindow() { // save window state QSettings s; s.setValue("MainWindow/State", this->saveState()); s.setValue("MainWindow/Geometry", this->saveGeometry()); } void MainWindow::slotFileOpen(QString filePath) { // open file QFile f(filePath); if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Cannot open file!"); return; } // parse block libblockdia::Block * block = libblockdia::Block::parseBlockDef(&f); f.close(); if (!block) { QMessageBox::critical(this, "Error", "Error on parsing file!"); return; } // remember opened file this->openFilePathHash[block] = filePath; // Ignore the first change signal for just created block // Because instantiating the block causes the signal. this->ignoreChangedBlocks.append(block); // open new tab for block QTabWidget *tw = (QTabWidget *) this->centralWidget(); int index = tw->addTab(new libblockdia::ViewBlockEditor(block), block->typeId()); tw->setCurrentIndex(index); // catch changes inside the block connect(block, SIGNAL(signalSomethingChanged(libblockdia::Block*)), this, SLOT(slotBlockChanged(libblockdia::Block*))); } void MainWindow::slotActionNewBlock() { // create new block libblockdia::Block *block = new libblockdia::Block(this); block->setTypeName("New Block Type *"); block->setTypeId("NBT"); // create new block editor libblockdia::ViewBlockEditor *bEditor = new libblockdia::ViewBlockEditor(block); // add block editor to central widget QTabWidget *tw = (QTabWidget *) this->centralWidget(); int index = tw->addTab(bEditor, block->typeId() + "*"); tw->setCurrentIndex(index); // catch changes inside the block connect(block, SIGNAL(signalSomethingChanged(libblockdia::Block*)), this, SLOT(slotBlockChanged(libblockdia::Block*))); } void MainWindow::slotActionSave() { // get objects QTabWidget *tw = (QTabWidget *) this->centralWidget(); int currentIndex = tw->currentIndex(); libblockdia::ViewBlockEditor *editor = static_cast<libblockdia::ViewBlockEditor*>(tw->currentWidget()); libblockdia::Block *block = editor->block(); QFile *f = Q_NULLPTR; // file path is already known if (this->openFilePathHash.contains(block)) { f = new QFile(this->openFilePathHash[block]); } // open file dialog else { QString fileName = QFileDialog::getSaveFileName(this, "Save Block", this->blockBrowser->currentRootPath(), "XML (*.xml)"); this->openFilePathHash[block] = fileName; f = new QFile(fileName); } // check if file is valid if (!f || !f->open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Cannot open file for writing!"); } // export block block->exportBlockDef(f); // close file if (f) { f->close(); f->deleteLater(); f = Q_NULLPTR; } // update tab text tw->setTabText(currentIndex, block->typeId()); } void MainWindow::slotActionQuit() { this->close(); } void MainWindow::slotBlockChanged(libblockdia::Block *block) { // check if the block was just created // In this case ignore the change signal // because it is emitted because of instantiating the block if (this->ignoreChangedBlocks.contains(block)) { this->ignoreChangedBlocks.removeAll(block); return; } // add astresik to tab name if it contains unsaved changes QTabWidget *tw = (QTabWidget *) this->centralWidget(); for (int i=0; i < tw->count(); ++i) { libblockdia::ViewBlockEditor *editor = static_cast<libblockdia::ViewBlockEditor*>(tw->widget(i)); if (editor->block() == block) { tw->setTabText(i, block->typeId() + "*"); } } } <commit_msg>catch situation when saving no open blocks<commit_after>#include "mainwindow.h" #include <QLabel> #include <QDockWidget> #include <QSettings> #include <QAction> #include <QMenuBar> #include <QMenu> #include <QFile> #include <QMessageBox> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // menu - file QMenu *menuFile = new QMenu("File", this); this->menuBar()->addMenu(menuFile); // action - new block QAction *actNewBlock = new QAction("new block", this); menuFile->addAction(actNewBlock); actNewBlock->setShortcut(Qt::Key_N | Qt::CTRL); connect(actNewBlock, SIGNAL(triggered(bool)), this, SLOT(slotActionNewBlock())); // action - save QAction *actSave = new QAction("save block", this); menuFile->addAction(actSave); actSave->setShortcut(Qt::Key_S | Qt::CTRL); connect(actSave, SIGNAL(triggered(bool)), this, SLOT(slotActionSave())); // action - quit QAction *actQuit = new QAction("quit", this); menuFile->addAction(actQuit); actQuit->setShortcut(Qt::Key_Q | Qt::CTRL); connect(actQuit, SIGNAL(triggered(bool)), this, SLOT(slotActionQuit())); // central widget this->widgetMain = new QTabWidget(this); this->setCentralWidget(this->widgetMain); // block browser this->blockBrowser = new BlockBrowser(this); connect(this->blockBrowser, SIGNAL(signalFileOpen(QString)), this, SLOT(slotFileOpen(QString))); // block browser dock QDockWidget *dock = new QDockWidget("", this); dock->setObjectName("BlockBrowser"); dock->setAllowedAreas(Qt::LeftDockWidgetArea); dock->setWidget(this->blockBrowser); dock->setFloating(false); dock->setFeatures(QDockWidget::NoDockWidgetFeatures); this->addDockWidget(Qt::LeftDockWidgetArea, dock); // restore window state QSettings s; this->restoreState(s.value("Mainwindow/State").toByteArray()); this->restoreGeometry(s.value("MainWindow/Geometry").toByteArray()); } MainWindow::~MainWindow() { // save window state QSettings s; s.setValue("MainWindow/State", this->saveState()); s.setValue("MainWindow/Geometry", this->saveGeometry()); } void MainWindow::slotFileOpen(QString filePath) { // open file QFile f(filePath); if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Cannot open file!"); return; } // parse block libblockdia::Block * block = libblockdia::Block::parseBlockDef(&f); f.close(); if (!block) { QMessageBox::critical(this, "Error", "Error on parsing file!"); return; } // remember opened file this->openFilePathHash[block] = filePath; // Ignore the first change signal for just created block // Because instantiating the block causes the signal. this->ignoreChangedBlocks.append(block); // open new tab for block QTabWidget *tw = (QTabWidget *) this->centralWidget(); int index = tw->addTab(new libblockdia::ViewBlockEditor(block), block->typeId()); tw->setCurrentIndex(index); // catch changes inside the block connect(block, SIGNAL(signalSomethingChanged(libblockdia::Block*)), this, SLOT(slotBlockChanged(libblockdia::Block*))); } void MainWindow::slotActionNewBlock() { // create new block libblockdia::Block *block = new libblockdia::Block(this); block->setTypeName("New Block Type *"); block->setTypeId("NBT"); // create new block editor libblockdia::ViewBlockEditor *bEditor = new libblockdia::ViewBlockEditor(block); // add block editor to central widget QTabWidget *tw = (QTabWidget *) this->centralWidget(); int index = tw->addTab(bEditor, block->typeId() + "*"); tw->setCurrentIndex(index); // catch changes inside the block connect(block, SIGNAL(signalSomethingChanged(libblockdia::Block*)), this, SLOT(slotBlockChanged(libblockdia::Block*))); } void MainWindow::slotActionSave() { // get tab widget QTabWidget *tw = (QTabWidget *) this->centralWidget(); if (tw->count() == 0) return; // get objects int currentIndex = tw->currentIndex(); libblockdia::ViewBlockEditor *editor = static_cast<libblockdia::ViewBlockEditor*>(tw->currentWidget()); libblockdia::Block *block = editor->block(); QFile *f = Q_NULLPTR; // file path is already known if (this->openFilePathHash.contains(block)) { f = new QFile(this->openFilePathHash[block]); } // open file dialog else { QString fileName = QFileDialog::getSaveFileName(this, "Save Block", this->blockBrowser->currentRootPath(), "XML (*.xml)"); this->openFilePathHash[block] = fileName; f = new QFile(fileName); } // check if file is valid if (!f || !f->open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Cannot open file for writing!"); } // export block block->exportBlockDef(f); // close file if (f) { f->close(); f->deleteLater(); f = Q_NULLPTR; } // update tab text tw->setTabText(currentIndex, block->typeId()); } void MainWindow::slotActionQuit() { this->close(); } void MainWindow::slotBlockChanged(libblockdia::Block *block) { // check if the block was just created // In this case ignore the change signal // because it is emitted because of instantiating the block if (this->ignoreChangedBlocks.contains(block)) { this->ignoreChangedBlocks.removeAll(block); return; } // add astresik to tab name if it contains unsaved changes QTabWidget *tw = (QTabWidget *) this->centralWidget(); for (int i=0; i < tw->count(); ++i) { libblockdia::ViewBlockEditor *editor = static_cast<libblockdia::ViewBlockEditor*>(tw->widget(i)); if (editor->block() == block) { tw->setTabText(i, block->typeId() + "*"); } } } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <algorithm> #include <limits> using namespace std; #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "treehash/boosted-treehash.hh" extern "C" { #include "timers.h" } void fill_random(uint64_t * data, size_t n) { const int rfd = open("/dev/urandom", O_RDONLY); if (-1 == rfd) { const int err = errno; fprintf(stderr, "%s\n", strerror(err)); exit(err); } char * const cdata = (char *)data; for (size_t i = 0; i < n; i += read(rfd, &cdata[i], sizeof(uint64_t)*n-i)); (void)close(rfd); } uint64_t * alloc_random(size_t n) { uint64_t * ans = (uint64_t *)malloc(sizeof(uint64_t) * n); if (!ans) { fprintf(stderr, "Failed allocation of %zd words\n", n); exit(1); } fill_random(ans, n); return ans; } uint64_t sum = 0; template<size_t N> ticks bench(const void * r, const uint64_t * data, const size_t i) { const ticks start = startRDTSC(); sum += boosted_treehash<N>(r, data, i); const ticks finish = startRDTSC(); return finish-start; } int main() { size_t max_len = 2048; const uint64_t * const data = alloc_random(max_len); const void * const r64 = alloc_random(128); size_t iters = 10000; const size_t max_depth = 9; vector<vector<ticks> > cycles(max_depth, vector<ticks>(iters)); size_t samples = 100; cout << "# length percentile optimal-treeboost " << endl; for (size_t i = 1; i < max_len; i = 1 + 1.001*i) { for (size_t j = 0; j < iters; ++j) { cycles[0][j] = bench<1>(r64, data, i); cycles[1][j] = bench<2>(r64, data, i); cycles[2][j] = bench<3>(r64, data, i); cycles[3][j] = bench<4>(r64, data, i); cycles[4][j] = bench<5>(r64, data, i); cycles[5][j] = bench<6>(r64, data, i); cycles[6][j] = bench<7>(r64, data, i); cycles[7][j] = bench<8>(r64, data, i); cycles[8][j] = bench<9>(r64, data, i); } for (size_t j = 0; j < max_depth; ++j) { sort(cycles[j].begin(), cycles[j].end(), std::greater<ticks>()); } for (size_t j = 0; j <= samples; ++j) { size_t loc = (iters * j)/samples; if (loc >= iters) loc = iters-1; ticks min_val = numeric_limits<ticks>::max(); int min_idx = -1; for (size_t k = 0; k < max_depth; ++k) { if (cycles[k][loc] < min_val) { min_val = cycles[k][loc]; min_idx = k; } } cout << i << " " << j << " " << 1+min_idx << endl; } cout << endl; } cerr << "# ignore " << sum << endl; }; <commit_msg>Force computation without producing output<commit_after>#include <vector> #include <iostream> #include <algorithm> #include <limits> using namespace std; #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "treehash/boosted-treehash.hh" extern "C" { #include "timers.h" } void fill_random(uint64_t * data, size_t n) { const int rfd = open("/dev/urandom", O_RDONLY); if (-1 == rfd) { const int err = errno; fprintf(stderr, "%s\n", strerror(err)); exit(err); } char * const cdata = (char *)data; for (size_t i = 0; i < n; i += read(rfd, &cdata[i], sizeof(uint64_t)*n-i)); (void)close(rfd); } uint64_t * alloc_random(size_t n) { uint64_t * ans = (uint64_t *)malloc(sizeof(uint64_t) * n); if (!ans) { fprintf(stderr, "Failed allocation of %zd words\n", n); exit(1); } fill_random(ans, n); return ans; } uint64_t sum = 0; template<size_t N> ticks bench(const void * r, const uint64_t * data, const size_t i) { const ticks start = startRDTSC(); sum += boosted_treehash<N>(r, data, i); const ticks finish = startRDTSC(); return finish-start; } int main() { size_t max_len = 2048; const uint64_t * const data = alloc_random(max_len); const void * const r64 = alloc_random(128); size_t iters = 10000; const size_t max_depth = 9; vector<vector<ticks> > cycles(max_depth, vector<ticks>(iters)); size_t samples = 100; cout << "# length percentile optimal-treeboost " << endl; for (size_t i = 1; i < max_len; i = 1 + 1.001*i) { for (size_t j = 0; j < iters; ++j) { cycles[0][j] = bench<1>(r64, data, i); cycles[1][j] = bench<2>(r64, data, i); cycles[2][j] = bench<3>(r64, data, i); cycles[3][j] = bench<4>(r64, data, i); cycles[4][j] = bench<5>(r64, data, i); cycles[5][j] = bench<6>(r64, data, i); cycles[6][j] = bench<7>(r64, data, i); cycles[7][j] = bench<8>(r64, data, i); cycles[8][j] = bench<9>(r64, data, i); } for (size_t j = 0; j < max_depth; ++j) { sort(cycles[j].begin(), cycles[j].end(), std::greater<ticks>()); } for (size_t j = 0; j <= samples; ++j) { size_t loc = (iters * j)/samples; if (loc >= iters) loc = iters-1; ticks min_val = numeric_limits<ticks>::max(); int min_idx = -1; for (size_t k = 0; k < max_depth; ++k) { if (cycles[k][loc] < min_val) { min_val = cycles[k][loc]; min_idx = k; } } cout << i << " " << j << " " << 1+min_idx << endl; } cout << endl; } if (0 == sum) { cerr << "# Magic happens: sum of all hashes is 0!" << endl; return 1; } }; <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif #include "common.h" /* system implementation headers */ #include <iostream> #include <math.h> #include <sstream> #include <string.h> /* common implementation headers */ #include "Pack.h" #include "WorldFileObject.h" #include "WorldFileLocation.h" #include "MeshTransform.h" WorldFileLocation::WorldFileLocation() { pos[0] = pos[1] = pos[2] = 0.0f; rotation = 0.0f; size[0] = size[1] = size[2] = 1.0f; } bool WorldFileLocation::read(const char *cmd, std::istream& input) { // // Position, Size, and Rotation // if ((strcasecmp(cmd, "pos") == 0) || (strcasecmp(cmd, "position") == 0)) { if (!(input >> pos[0] >> pos[1] >> pos[2])) { return false; } } else if (strcasecmp(cmd, "size") == 0){ if (!(input >> size[0] >> size[1] >> size[2])) { return false; } } else if ((strcasecmp(cmd, "rot") == 0) || (strcasecmp(cmd, "rotation") == 0)) { if (!(input >> rotation)) { return false; } // convert to radians rotation = (float)(rotation * (M_PI / 180.0)); } else if (strcasecmp ("shift", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addShift(data); } else if (strcasecmp ("scale", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addScale(data); } else if (strcasecmp ("shear", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addShear(data); } else if (strcasecmp ("spin", cmd) == 0) { float angle, normal[3]; if (!(input >> angle >> normal[0] >> normal[1] >> normal[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addSpin(angle, normal); } else if (strcasecmp ("xform", cmd) == 0) { std::string _name; if (!(input >> _name)) { std::cout << "parameters errors " << std::endl; return false; } int xform = TRANSFORMMGR.findTransform(_name); if (xform == -1) { std::cout << "couldn't find Transform: " << _name << std::endl; } else { transform.addReference(xform); } } else { return WorldFileObject::read(cmd, input); } return true; } void * WorldFileLocation::pack(void *buf) const { buf = nboPackFloatVector (buf, pos); buf = nboPackFloatVector (buf, size); buf = nboPackFloat (buf, rotation); return buf; } // Local variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Whitespace<commit_after>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif #include "common.h" /* system implementation headers */ #include <iostream> #include <math.h> #include <sstream> #include <string.h> /* common implementation headers */ #include "Pack.h" #include "WorldFileObject.h" #include "WorldFileLocation.h" #include "MeshTransform.h" WorldFileLocation::WorldFileLocation() { pos[0] = pos[1] = pos[2] = 0.0f; rotation = 0.0f; size[0] = size[1] = size[2] = 1.0f; } bool WorldFileLocation::read(const char *cmd, std::istream& input) { // // Position, Size, and Rotation // if ((strcasecmp(cmd, "pos") == 0) || (strcasecmp(cmd, "position") == 0)) { if (!(input >> pos[0] >> pos[1] >> pos[2])) { return false; } } else if (strcasecmp(cmd, "size") == 0) { if (!(input >> size[0] >> size[1] >> size[2])) { return false; } } else if ((strcasecmp(cmd, "rot") == 0) || (strcasecmp(cmd, "rotation") == 0)) { if (!(input >> rotation)) { return false; } // convert to radians rotation = (float)(rotation * (M_PI / 180.0)); } else if (strcasecmp ("shift", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addShift(data); } else if (strcasecmp ("scale", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addScale(data); } else if (strcasecmp ("shear", cmd) == 0) { float data[3]; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addShear(data); } else if (strcasecmp ("spin", cmd) == 0) { float angle, normal[3]; if (!(input >> angle >> normal[0] >> normal[1] >> normal[2])) { std::cout << "parameters errors " << std::endl; return false; } transform.addSpin(angle, normal); } else if (strcasecmp ("xform", cmd) == 0) { std::string _name; if (!(input >> _name)) { std::cout << "parameters errors " << std::endl; return false; } int xform = TRANSFORMMGR.findTransform(_name); if (xform == -1) { std::cout << "couldn't find Transform: " << _name << std::endl; } else { transform.addReference(xform); } } else { return WorldFileObject::read(cmd, input); } return true; } void * WorldFileLocation::pack(void *buf) const { buf = nboPackFloatVector (buf, pos); buf = nboPackFloatVector (buf, size); buf = nboPackFloat (buf, rotation); return buf; } // Local variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif #include "WorldFileObstacle.h" WorldFileObstacle::WorldFileObstacle() { pos[0] = pos[1] = pos[2] = 0.0f; rotation = 0.0f; size[0] = size[1] = size[2] = 1.0f; driveThrough = false; shootThrough = false; flipZ = false; } bool WorldFileObstacle::read(const char *cmd, std::istream& input) { if (strcasecmp(cmd, "position") == 0) input >> pos[0] >> pos[1] >> pos[2]; else if (strcasecmp(cmd, "rotation") == 0) { input >> rotation; rotation = rotation * M_PI / 180.0f; } else if (strcasecmp(cmd, "size") == 0){ input >> size[0] >> size[1] >> size[2]; if (size[2] < 0) flipZ = true; size[0] = fabs(size[0]); // make sure they are postive, no more tricks size[1] = fabs(size[1]); size[2] = fabs(size[2]); } else if (strcasecmp(cmd, "drivethrough") == 0) driveThrough = true; else if (strcasecmp(cmd, "shootthrough") == 0) shootThrough = true; else if (strcasecmp(cmd, "pasable") == 0) driveThrough = shootThrough = true; else if (strcasecmp(cmd, "flipz") == 0) flipZ = true; else return WorldFileObject::read(cmd, input); return true; } // Local variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>pasable -> passable<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif #include "WorldFileObstacle.h" WorldFileObstacle::WorldFileObstacle() { pos[0] = pos[1] = pos[2] = 0.0f; rotation = 0.0f; size[0] = size[1] = size[2] = 1.0f; driveThrough = false; shootThrough = false; flipZ = false; } bool WorldFileObstacle::read(const char *cmd, std::istream& input) { if (strcasecmp(cmd, "position") == 0) input >> pos[0] >> pos[1] >> pos[2]; else if (strcasecmp(cmd, "rotation") == 0) { input >> rotation; rotation = rotation * M_PI / 180.0f; } else if (strcasecmp(cmd, "size") == 0){ input >> size[0] >> size[1] >> size[2]; if (size[2] < 0) flipZ = true; size[0] = fabs(size[0]); // make sure they are postive, no more tricks size[1] = fabs(size[1]); size[2] = fabs(size[2]); } else if (strcasecmp(cmd, "drivethrough") == 0) driveThrough = true; else if (strcasecmp(cmd, "shootthrough") == 0) shootThrough = true; else if (strcasecmp(cmd, "passable") == 0) driveThrough = shootThrough = true; else if (strcasecmp(cmd, "flipz") == 0) flipZ = true; else return WorldFileObject::read(cmd, input); return true; } // Local variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "Value.h" #include <sstream> #include <cassert> namespace libol { Value Value::create(Object &val) { Value value; value.type = OBJECT; value.value = new Object(val); return value; } Value Value::create(Array &val) { Value value; value.type = ARRAY; value.value = new Array(val); return value; } Value Value::create(float &val) { Value value; value.type = FLOAT; value.value = new float(val); return value; } Value Value::create(bool &val) { Value value; value.type = BOOL; value.value = new bool(val); return value; } Value Value::create(uint64_t &val) { assert(!(val & ((uint64_t) 1 << 61))); // assert that the msb is not set return create((int64_t &) val); } Value Value::create(uint32_t &val) { if (val >= 2147483648) { int64_t large = (int64_t) val; return create(large); } return create((int32_t &) val); } Value Value::create(uint16_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(uint8_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(int64_t &val) { Value value; value.type = LARGE_INTEGER; value.value = new int64_t(val); return value; } Value Value::create(int32_t &val) { Value value; value.type = INTEGER; value.value = new int32_t(val); return value; } Value Value::create(int16_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(int8_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(std::string &val) { Value value; value.type = STRING; value.value = new std::string(val); return value; } Value Value::create(const char *&val) { std::string str = std::string(val); return create(str); } std::string Value::toString(size_t indent) { std::stringstream result, tabs; for (size_t i = 0; i < indent; i++) tabs << "\t"; std::string indentation = tabs.str(); switch (type) { case OBJECT: { Object &obj = this->as<Object>(); result << "{" << std::endl; for (auto it = obj.begin(); it != obj.end();) { result << indentation << "\t\"" << it->first << "\": "; result << it->second.toString(indent + 1); if (++it != obj.end()) result << ","; result << std::endl; } if (obj.size()) result << indentation; result << "}"; break; } case ARRAY: { Array &arr = this->as<Array>(); result << "["; for (size_t i = 0; i < arr.size(); i++) { result << arr.at(i).toString(indent); if (i + 1 < arr.size()) result << ","; } result << "]"; break; } case STRING: result << "\"" << this->as<std::string>() << "\""; break; case INTEGER: result << this->as<int32_t>(); break; case LARGE_INTEGER: result << this->as<int64_t>(); break; case FLOAT: result << this->as<float>(); break; case BOOL: result << (this->as<bool>() ? "true" : "false"); break; default: result << "undefined"; break; case UNDEFINED: break; } return result.str(); } void Value::destroy() { switch (type) { case OBJECT: { Object &obj = this->as<Object>(); for (auto it = obj.begin(); it != obj.end(); it++) { it->second.destroy(); } delete &obj; break; } case ARRAY: { Array &arr = this->as<Array>(); for (size_t i = 0; i < arr.size(); i++) { arr.at(i).destroy(); } delete &arr; break; } case STRING: delete &this->as<std::string>(); break; case INTEGER: delete &this->as<int32_t>(); break; case LARGE_INTEGER: delete &this->as<int64_t>(); break; case FLOAT: delete &this->as<float>(); break; case BOOL: delete &this->as<bool>(); break; case UNDEFINED: break; } type = UNDEFINED; value = nullptr; } void Object::set(std::string name, Value value) { map.insert(std::pair<std::string, Value> {name, value}); } Value Object::get(std::string name) { return map.at(name); } size_t Object::size() { return map.size(); } void Array::push(Value value) { vector.push_back(value); } size_t Array::size() { return vector.size(); } Value Array::at(size_t index) { return vector.at(index); } } <commit_msg>Fix JSON formatting<commit_after>#include "Value.h" #include <sstream> #include <cassert> namespace libol { Value Value::create(Object &val) { Value value; value.type = OBJECT; value.value = new Object(val); return value; } Value Value::create(Array &val) { Value value; value.type = ARRAY; value.value = new Array(val); return value; } Value Value::create(float &val) { Value value; value.type = FLOAT; value.value = new float(val); return value; } Value Value::create(bool &val) { Value value; value.type = BOOL; value.value = new bool(val); return value; } Value Value::create(uint64_t &val) { assert(!(val & ((uint64_t) 1 << 61))); // assert that the msb is not set return create((int64_t &) val); } Value Value::create(uint32_t &val) { if (val >= 2147483648) { int64_t large = (int64_t) val; return create(large); } return create((int32_t &) val); } Value Value::create(uint16_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(uint8_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(int64_t &val) { Value value; value.type = LARGE_INTEGER; value.value = new int64_t(val); return value; } Value Value::create(int32_t &val) { Value value; value.type = INTEGER; value.value = new int32_t(val); return value; } Value Value::create(int16_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(int8_t &val) { int32_t intval = (int32_t) val; return create(intval); } Value Value::create(std::string &val) { Value value; value.type = STRING; value.value = new std::string(val); return value; } Value Value::create(const char *&val) { std::string str = std::string(val); return create(str); } std::string Value::toString(size_t indent) { std::stringstream result, tabs; for (size_t i = 0; i < indent; i++) tabs << "\t"; std::string indentation = tabs.str(); switch (type) { case OBJECT: { Object &obj = this->as<Object>(); result << "{"; if(obj.size()) result << std::endl; for (auto it = obj.begin(); it != obj.end();) { result << indentation << "\t\"" << it->first << "\": "; result << it->second.toString(indent + 1); if (++it != obj.end()) result << ","; result << std::endl; } if (obj.size()) result << indentation; result << "}"; break; } case ARRAY: { Array &arr = this->as<Array>(); result << "["; for (size_t i = 0; i < arr.size(); i++) { result << arr.at(i).toString(indent); if (i + 1 < arr.size()) result << ","; } result << "]"; break; } case STRING: result << "\"" << this->as<std::string>() << "\""; break; case INTEGER: result << this->as<int32_t>(); break; case LARGE_INTEGER: result << this->as<int64_t>(); break; case FLOAT: result << this->as<float>(); break; case BOOL: result << (this->as<bool>() ? "true" : "false"); break; default: result << "undefined"; break; case UNDEFINED: break; } return result.str(); } void Value::destroy() { switch (type) { case OBJECT: { Object &obj = this->as<Object>(); for (auto it = obj.begin(); it != obj.end(); it++) { it->second.destroy(); } delete &obj; break; } case ARRAY: { Array &arr = this->as<Array>(); for (size_t i = 0; i < arr.size(); i++) { arr.at(i).destroy(); } delete &arr; break; } case STRING: delete &this->as<std::string>(); break; case INTEGER: delete &this->as<int32_t>(); break; case LARGE_INTEGER: delete &this->as<int64_t>(); break; case FLOAT: delete &this->as<float>(); break; case BOOL: delete &this->as<bool>(); break; case UNDEFINED: break; } type = UNDEFINED; value = nullptr; } void Object::set(std::string name, Value value) { map.insert(std::pair<std::string, Value> {name, value}); } Value Object::get(std::string name) { return map.at(name); } size_t Object::size() { return map.size(); } void Array::push(Value value) { vector.push_back(value); } size_t Array::size() { return vector.size(); } Value Array::at(size_t index) { return vector.at(index); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sddlgfact.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:18:42 $ * * 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 _SD_DLGFACT_HXX #define _SD_DLGFACT_HXX // include --------------------------------------------------------------- #include "sdabstdlg.hxx" #define DECL_ABSTDLG_BASE(Class,DialogClass) \ DialogClass* pDlg; \ public: \ Class( DialogClass* p) \ : pDlg(p) \ {} \ virtual ~Class(); \ virtual USHORT Execute() ; #define IMPL_ABSTDLG_BASE(Class) \ Class::~Class() \ { \ delete pDlg; \ } \ USHORT Class::Execute() \ { \ return pDlg->Execute(); \ } namespace sd { class MorphDlg; class CopyDlg; class BreakDlg; class OutlineBulletDlg; class HeaderFooterDialog; } // add for BreakDlg class Dialog; class VclAbstractDialog_Impl : public VclAbstractDialog { DECL_ABSTDLG_BASE(VclAbstractDialog_Impl,Dialog); }; // add for CopyDlg class AbstractCopyDlg_Impl : public AbstractCopyDlg { DECL_ABSTDLG_BASE(AbstractCopyDlg_Impl,::sd::CopyDlg); virtual void GetAttr( SfxItemSet& rOutAttrs ); }; // add for SdCustomShowDlg class SdCustomShowDlg; class AbstractSdCustomShowDlg_Impl : public AbstractSdCustomShowDlg { DECL_ABSTDLG_BASE(AbstractSdCustomShowDlg_Impl,SdCustomShowDlg); virtual BOOL IsModified() const ; virtual BOOL IsCustomShow() const ; }; //add for SdCharDlg begin class SfxTabDialog; class AbstractTabDialog_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( AbstractTabDialog_Impl,SfxTabDialog ); virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); //add by CHINA001 virtual void SetInputSet( const SfxItemSet* pInSet ); //add by CHINA001 //From class Window. virtual void SetText( const XubString& rStr ); //add by CHINA001 virtual String GetText() const; //add by CHINA001 }; //add for SdCharDlg end //add for OutlineBulletDlg begin class SfxTabDialog; class AbstractBulletDialog_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( AbstractBulletDialog_Impl,SfxTabDialog ); virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); virtual void SetInputSet( const SfxItemSet* pInSet ); //From class Window. virtual void SetText( const XubString& rStr ); virtual String GetText() const; }; //add for OutlineBulletDlg end class SdPresLayoutTemplateDlg; class SdPresLayoutTemplateDlg_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( SdPresLayoutTemplateDlg_Impl,SdPresLayoutTemplateDlg ); virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); //add by CHINA001 virtual void SetInputSet( const SfxItemSet* pInSet ); //add by CHINA001 //From class Window. virtual void SetText( const XubString& rStr ); //add by CHINA001 virtual String GetText() const; //add by CHINA001 }; // add for AssistentDlg class AssistentDlg; class AbstractAssistentDlg_Impl : public AbstractAssistentDlg { DECL_ABSTDLG_BASE(AbstractAssistentDlg_Impl,AssistentDlg); virtual SfxObjectShellLock GetDocument(); virtual OutputType GetOutputMedium() const; virtual BOOL IsSummary() const; virtual StartType GetStartType() const; virtual String GetDocPath() const; virtual BOOL GetStartWithFlag() const; virtual BOOL IsDocEmpty() const; virtual String GetPassword(); }; // add for SdModifyFieldDlg class SdModifyFieldDlg; class AbstractSdModifyFieldDlg_Impl : public AbstractSdModifyFieldDlg { DECL_ABSTDLG_BASE(AbstractSdModifyFieldDlg_Impl,SdModifyFieldDlg); virtual SvxFieldData* GetField(); virtual SfxItemSet GetItemSet(); }; // add for SdSnapLineDlg class SdSnapLineDlg; class AbstractSdSnapLineDlg_Impl : public AbstractSdSnapLineDlg { DECL_ABSTDLG_BASE(AbstractSdSnapLineDlg_Impl,SdSnapLineDlg); virtual void GetAttr(SfxItemSet& rOutAttrs); virtual void HideRadioGroup(); virtual void HideDeleteBtn(); virtual void SetInputFields(BOOL bEnableX, BOOL bEnableY); //from class Window virtual void SetText( const XubString& rStr ); }; // add for SdInsertLayerDlg class SdInsertLayerDlg; class AbstractSdInsertLayerDlg_Impl : public AbstractSdInsertLayerDlg { DECL_ABSTDLG_BASE(AbstractSdInsertLayerDlg_Impl,SdInsertLayerDlg); virtual void GetAttr( SfxItemSet& rOutAttrs ) ; //from class Window virtual void SetHelpId( ULONG nHelpId ) ; }; // add for SdInsertPasteDlg class SdInsertPasteDlg; class AbstractSdInsertPasteDlg_Impl : public AbstractSdInsertPasteDlg { DECL_ABSTDLG_BASE(AbstractSdInsertPasteDlg_Impl,SdInsertPasteDlg); virtual BOOL IsInsertBefore() const; }; // add for SdInsertPagesObjsDlg class SdInsertPagesObjsDlg; class AbstractSdInsertPagesObjsDlg_Impl : public AbstractSdInsertPagesObjsDlg { DECL_ABSTDLG_BASE(AbstractSdInsertPagesObjsDlg_Impl,SdInsertPagesObjsDlg); virtual ::Window * GetWindow(); //this method is added for return a Window type pointer virtual List* GetList( USHORT nType ); virtual BOOL IsLink(); virtual BOOL IsRemoveUnnessesaryMasterPages() const; }; // add for MorphDlg class AbstractMorphDlg_Impl : public AbstractMorphDlg { DECL_ABSTDLG_BASE(AbstractMorphDlg_Impl,::sd::MorphDlg); virtual void SaveSettings() const; virtual USHORT GetFadeSteps() const; virtual BOOL IsAttributeFade() const ; virtual BOOL IsOrientationFade() const ; }; // add for SdNewFoilDlg class SdNewFoilDlg; class AbstractSdNewFoilDlg_Impl : public AbstractSdNewFoilDlg { DECL_ABSTDLG_BASE(AbstractSdNewFoilDlg_Impl,SdNewFoilDlg); virtual void GetAttr( SfxItemSet& rOutAttrs ); }; // add for SdStartPresentationDlg class SdStartPresentationDlg; class AbstractSdStartPresDlg_Impl : public AbstractSdStartPresDlg { DECL_ABSTDLG_BASE(AbstractSdStartPresDlg_Impl,SdStartPresentationDlg); virtual void GetAttr( SfxItemSet& rOutAttrs ); }; // add for SdPrintDlg class SdPrintDlg; class AbstractSdPrintDlg_Impl : public AbstractSdPrintDlg { DECL_ABSTDLG_BASE(AbstractSdPrintDlg_Impl,SdPrintDlg); virtual USHORT GetAttr(); }; // add for SdPresLayoutDlg class SdPresLayoutDlg; class AbstractSdPresLayoutDlg_Impl : public AbstractSdPresLayoutDlg { DECL_ABSTDLG_BASE(AbstractSdPresLayoutDlg_Impl,SdPresLayoutDlg); virtual void GetAttr(SfxItemSet& rOutAttrs); }; // add for SdActionDlg class SfxSingleTabDialog; class AbstractSfxSingleTabDialog_Impl :public AbstractSfxSingleTabDialog { DECL_ABSTDLG_BASE(AbstractSfxSingleTabDialog_Impl,SfxSingleTabDialog); virtual const SfxItemSet* GetOutputItemSet() const; }; // add for SdVectorizeDlg class SdVectorizeDlg; class AbstractSdVectorizeDlg_Impl :public AbstractSdVectorizeDlg { DECL_ABSTDLG_BASE(AbstractSdVectorizeDlg_Impl,SdVectorizeDlg); virtual const GDIMetaFile& GetGDIMetaFile() const ; }; // add for SdPublishingDlg class SdPublishingDlg; class AbstractSdPublishingDlg_Impl :public AbstractSdPublishingDlg { DECL_ABSTDLG_BASE(AbstractSdPublishingDlg_Impl,SdPublishingDlg); virtual void GetParameterSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rParams ); }; // add for HeaderFooterDialog class AbstractHeaderFooterDialog_Impl :public AbstractHeaderFooterDialog { DECL_ABSTDLG_BASE(AbstractHeaderFooterDialog_Impl,::sd::HeaderFooterDialog); virtual void ApplyToAll( TabPage* pPage ); virtual void Apply( TabPage* pPage ); virtual void Cancel( TabPage* pPage ); }; //------------------------------------------------------------------------ //AbstractDialogFactory_Impl implementations class SdAbstractDialogFactory_Impl : public SdAbstractDialogFactory { public: virtual VclAbstractDialog* CreateBreakDlg( const ResId& rResId, ::Window* pWindow, ::sd::DrawView* pDrView, ::sd::DrawDocShell* pShell, ULONG nSumActionCount, ULONG nObjCount ); //add for BreakDlg virtual AbstractCopyDlg* CreateCopyDlg( const ResId& rResId, ::Window* pWindow, const SfxItemSet& rInAttrs, XColorTable* pColTab, ::sd::View* pView ); //add for CopyDlg virtual AbstractSdCustomShowDlg* CreateSdCustomShowDlg( const ResId& rResId, ::Window* pWindow, SdDrawDocument& rDrawDoc ); //add for SdCustomShowDlg virtual SfxAbstractTabDialog* CreateSdTabDialog( const ResId& rResId, ::Window* pParent, const SfxItemSet* pAttr, SfxObjectShell* pDocShell, BOOL bAreaPage = TRUE ); //add for SdCharDlg, SdPageDlg virtual AbstractAssistentDlg* CreateAssistentDlg( const ResId& rResId, ::Window* pParent, BOOL bAutoPilot); //add for AssistentDlg virtual AbstractSdModifyFieldDlg* CreateSdModifyFieldDlg( const ResId& rResId, ::Window* pWindow, const SvxFieldData* pInField, const SfxItemSet& rSet ); //add for SdModifyFieldDlg virtual AbstractSdSnapLineDlg* CreateSdSnapLineDlg( const ResId& rResId, ::Window* pWindow, const SfxItemSet& rInAttrs, ::sd::View* pView); //add for SdSnapLineDlg virtual AbstractSdInsertLayerDlg* CreateSdInsertLayerDlg( const ResId& rResId, ::Window* pWindow, const SfxItemSet& rInAttrs, BOOL bDeletable, String aStr ); //add for SdInsertLayerDlg virtual AbstractSdInsertPasteDlg* CreateSdInsertPasteDlg( const ResId& rResId, ::Window* pWindow ); //add for SdInsertPasteDlg virtual AbstractSdInsertPagesObjsDlg* CreateSdInsertPagesObjsDlg( const ResId& rResId, ::Window* pParent, const SdDrawDocument* pDoc, SfxMedium* pSfxMedium, const String& rFileName ); //add for SdInsertPagesObjsDlg virtual AbstractMorphDlg* CreateMorphDlg( const ResId& rResId, ::Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2); //add for MorphDlg virtual AbstractSdNewFoilDlg* CreateSdNewFoilDlg( const ResId& rResId, ::Window* pWindow, const SfxItemSet& rInAttrs, PageKind ePgKind, ::sd::DrawDocShell* pDocShell, BOOL bChangeFoil ); //add for SdNewFoilDlg virtual SfxAbstractTabDialog* CreateSdItemSetTabDlg ( const ResId& rResId, ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView = NULL ); //add for OutlineBulletDlg,SdParagraphDlg virtual AbstractSdStartPresDlg* CreateSdStartPresentationDlg( const ResId& rResId, ::Window* pWindow, const SfxItemSet& rInAttrs, List& rPageNames, List* pCSList ); //add for SdStartPresentationDlg virtual AbstractSdPrintDlg* CreateSdPrintDlg( const ResId& rResId, ::Window* pWindow ); //add for SdPrintDlg virtual SfxAbstractTabDialog* CreateSdPresLayoutTemplateDlg( const ResId& rResId, SfxObjectShell* pDocSh, ::Window* pParent, SdResId DlgId, SfxStyleSheetBase& rStyleBase, PresentationObjects ePO, SfxStyleSheetBasePool* pSSPool ); //add for SdPresLayoutTemplateDlg virtual AbstractSdPresLayoutDlg* CreateSdPresLayoutDlg( const ResId& rResId, ::sd::DrawDocShell* pDocShell, ::sd::ViewShell* pViewShell, ::Window* pWindow, const SfxItemSet& rInAttrs); //add for SdPresLayoutDlg virtual SfxAbstractTabDialog* CreateSdTabTemplateDlg( const ResId& rResId, ::Window* pParent, const SfxObjectShell* pDocShell, SfxStyleSheetBase& rStyleBase, SdrModel* pModel, SdrView* pView ); //add for SdTabTemplateDlg virtual AbstractSfxSingleTabDialog* CreateSfxSingleTabDialog( const ResId& rResId, ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView ); //add for SdActionDlg virtual AbstractSdVectorizeDlg* CreateSdVectorizeDlg( const ResId& rResId, ::Window* pParent, const Bitmap& rBmp, ::sd::DrawDocShell* pDocShell ); //add for SdVectorizeDlg virtual AbstractSdPublishingDlg* CreateSdPublishingDlg( const ResId& rResId, ::Window* pWindow, DocumentType eDocType); //add for SdPublishingDlg virtual VclAbstractDialog* CreateMasterLayoutDialog( ::Window* pParent, SdDrawDocument* pDoc, SdPage* ); // add for MasterLayoutDialog virtual AbstractHeaderFooterDialog* CreateHeaderFooterDialog( ViewShell* pViewShell, ::Window* pParent, SdDrawDocument* pDoc, SdPage* pCurrentPage ); // add for HeaderFooterDialog // For TabPage virtual CreateTabPage GetTabPageCreatorFunc( USHORT nId ); virtual GetTabPageRanges GetTabPageRangesFunc( USHORT nId ); }; #endif <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.6.316); FILE MERGED 2006/11/27 13:47:59 cl 1.6.316.2: #i69285# warning free code changes for sd project 2006/11/22 12:41:48 cl 1.6.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sddlgfact.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:09:17 $ * * 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 _SD_DLGFACT_HXX #define _SD_DLGFACT_HXX // include --------------------------------------------------------------- #include "sdabstdlg.hxx" #define DECL_ABSTDLG_BASE(Class,DialogClass) \ DialogClass* pDlg; \ public: \ Class( DialogClass* p) \ : pDlg(p) \ {} \ virtual ~Class(); \ virtual USHORT Execute() ; #define IMPL_ABSTDLG_BASE(Class) \ Class::~Class() \ { \ delete pDlg; \ } \ USHORT Class::Execute() \ { \ return pDlg->Execute(); \ } namespace sd { class MorphDlg; class CopyDlg; class BreakDlg; class OutlineBulletDlg; class HeaderFooterDialog; } // add for BreakDlg class Dialog; class VclAbstractDialog_Impl : public VclAbstractDialog { DECL_ABSTDLG_BASE(VclAbstractDialog_Impl,Dialog) }; // add for CopyDlg class AbstractCopyDlg_Impl : public AbstractCopyDlg { DECL_ABSTDLG_BASE(AbstractCopyDlg_Impl,::sd::CopyDlg) virtual void GetAttr( SfxItemSet& rOutAttrs ); }; // add for SdCustomShowDlg class SdCustomShowDlg; class AbstractSdCustomShowDlg_Impl : public AbstractSdCustomShowDlg { DECL_ABSTDLG_BASE(AbstractSdCustomShowDlg_Impl,SdCustomShowDlg) virtual BOOL IsModified() const ; virtual BOOL IsCustomShow() const ; }; //add for SdCharDlg begin class SfxTabDialog; class AbstractTabDialog_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( AbstractTabDialog_Impl,SfxTabDialog ) virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); virtual void SetInputSet( const SfxItemSet* pInSet ); //From class Window. virtual void SetText( const XubString& rStr ); virtual String GetText() const; }; //add for SdCharDlg end //add for OutlineBulletDlg begin class SfxTabDialog; class AbstractBulletDialog_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( AbstractBulletDialog_Impl,SfxTabDialog ) virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); virtual void SetInputSet( const SfxItemSet* pInSet ); //From class Window. virtual void SetText( const XubString& rStr ); virtual String GetText() const; }; //add for OutlineBulletDlg end class SdPresLayoutTemplateDlg; class SdPresLayoutTemplateDlg_Impl : public SfxAbstractTabDialog { DECL_ABSTDLG_BASE( SdPresLayoutTemplateDlg_Impl,SdPresLayoutTemplateDlg ) virtual void SetCurPageId( USHORT nId ); virtual const SfxItemSet* GetOutputItemSet() const; virtual const USHORT* GetInputRanges( const SfxItemPool& pItem ); virtual void SetInputSet( const SfxItemSet* pInSet ); //From class Window. virtual void SetText( const XubString& rStr ); virtual String GetText() const; }; // add for AssistentDlg class AssistentDlg; class AbstractAssistentDlg_Impl : public AbstractAssistentDlg { DECL_ABSTDLG_BASE(AbstractAssistentDlg_Impl,AssistentDlg) virtual SfxObjectShellLock GetDocument(); virtual OutputType GetOutputMedium() const; virtual BOOL IsSummary() const; virtual StartType GetStartType() const; virtual String GetDocPath() const; virtual BOOL GetStartWithFlag() const; virtual BOOL IsDocEmpty() const; virtual String GetPassword(); }; // add for SdModifyFieldDlg class SdModifyFieldDlg; class AbstractSdModifyFieldDlg_Impl : public AbstractSdModifyFieldDlg { DECL_ABSTDLG_BASE(AbstractSdModifyFieldDlg_Impl,SdModifyFieldDlg) virtual SvxFieldData* GetField(); virtual SfxItemSet GetItemSet(); }; // add for SdSnapLineDlg class SdSnapLineDlg; class AbstractSdSnapLineDlg_Impl : public AbstractSdSnapLineDlg { DECL_ABSTDLG_BASE(AbstractSdSnapLineDlg_Impl,SdSnapLineDlg) virtual void GetAttr(SfxItemSet& rOutAttrs); virtual void HideRadioGroup(); virtual void HideDeleteBtn(); virtual void SetInputFields(BOOL bEnableX, BOOL bEnableY); //from class Window virtual void SetText( const XubString& rStr ); }; // add for SdInsertLayerDlg class SdInsertLayerDlg; class AbstractSdInsertLayerDlg_Impl : public AbstractSdInsertLayerDlg { DECL_ABSTDLG_BASE(AbstractSdInsertLayerDlg_Impl,SdInsertLayerDlg) virtual void GetAttr( SfxItemSet& rOutAttrs ) ; //from class Window virtual void SetHelpId( ULONG nHelpId ) ; }; // add for SdInsertPasteDlg class SdInsertPasteDlg; class AbstractSdInsertPasteDlg_Impl : public AbstractSdInsertPasteDlg { DECL_ABSTDLG_BASE(AbstractSdInsertPasteDlg_Impl,SdInsertPasteDlg) virtual BOOL IsInsertBefore() const; }; // add for SdInsertPagesObjsDlg class SdInsertPagesObjsDlg; class AbstractSdInsertPagesObjsDlg_Impl : public AbstractSdInsertPagesObjsDlg { DECL_ABSTDLG_BASE(AbstractSdInsertPagesObjsDlg_Impl,SdInsertPagesObjsDlg) virtual ::Window * GetWindow(); //this method is added for return a Window type pointer virtual List* GetList( USHORT nType ); virtual BOOL IsLink(); virtual BOOL IsRemoveUnnessesaryMasterPages() const; }; // add for MorphDlg class AbstractMorphDlg_Impl : public AbstractMorphDlg { DECL_ABSTDLG_BASE(AbstractMorphDlg_Impl,::sd::MorphDlg) virtual void SaveSettings() const; virtual USHORT GetFadeSteps() const; virtual BOOL IsAttributeFade() const ; virtual BOOL IsOrientationFade() const ; }; // add for SdStartPresentationDlg class SdStartPresentationDlg; class AbstractSdStartPresDlg_Impl : public AbstractSdStartPresDlg { DECL_ABSTDLG_BASE(AbstractSdStartPresDlg_Impl,SdStartPresentationDlg) virtual void GetAttr( SfxItemSet& rOutAttrs ); }; // add for SdPrintDlg class SdPrintDlg; class AbstractSdPrintDlg_Impl : public AbstractSdPrintDlg { DECL_ABSTDLG_BASE(AbstractSdPrintDlg_Impl,SdPrintDlg) virtual USHORT GetAttr(); }; // add for SdPresLayoutDlg class SdPresLayoutDlg; class AbstractSdPresLayoutDlg_Impl : public AbstractSdPresLayoutDlg { DECL_ABSTDLG_BASE(AbstractSdPresLayoutDlg_Impl,SdPresLayoutDlg) virtual void GetAttr(SfxItemSet& rOutAttrs); }; // add for SdActionDlg class SfxSingleTabDialog; class AbstractSfxSingleTabDialog_Impl :public AbstractSfxSingleTabDialog { DECL_ABSTDLG_BASE(AbstractSfxSingleTabDialog_Impl,SfxSingleTabDialog) virtual const SfxItemSet* GetOutputItemSet() const; }; // add for SdVectorizeDlg class SdVectorizeDlg; class AbstractSdVectorizeDlg_Impl :public AbstractSdVectorizeDlg { DECL_ABSTDLG_BASE(AbstractSdVectorizeDlg_Impl,SdVectorizeDlg) virtual const GDIMetaFile& GetGDIMetaFile() const ; }; // add for SdPublishingDlg class SdPublishingDlg; class AbstractSdPublishingDlg_Impl :public AbstractSdPublishingDlg { DECL_ABSTDLG_BASE(AbstractSdPublishingDlg_Impl,SdPublishingDlg) virtual void GetParameterSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rParams ); }; // add for HeaderFooterDialog class AbstractHeaderFooterDialog_Impl :public AbstractHeaderFooterDialog { DECL_ABSTDLG_BASE(AbstractHeaderFooterDialog_Impl,::sd::HeaderFooterDialog) virtual void ApplyToAll( TabPage* pPage ); virtual void Apply( TabPage* pPage ); virtual void Cancel( TabPage* pPage ); }; //------------------------------------------------------------------------ //AbstractDialogFactory_Impl implementations class SdAbstractDialogFactory_Impl : public SdAbstractDialogFactory { public: virtual VclAbstractDialog* CreateBreakDlg(::Window* pWindow, ::sd::DrawView* pDrView, ::sd::DrawDocShell* pShell, ULONG nSumActionCount, ULONG nObjCount ); virtual AbstractCopyDlg* CreateCopyDlg( ::Window* pWindow, const SfxItemSet& rInAttrs, XColorTable* pColTab, ::sd::View* pView ); virtual AbstractSdCustomShowDlg* CreateSdCustomShowDlg( ::Window* pWindow, SdDrawDocument& rDrawDoc ); virtual SfxAbstractTabDialog* CreateSdTabCharDialog( ::Window* pParent, const SfxItemSet* pAttr, SfxObjectShell* pDocShell ); virtual SfxAbstractTabDialog* CreateSdTabPageDialog( ::Window* pParent, const SfxItemSet* pAttr, SfxObjectShell* pDocShell, BOOL bAreaPage = TRUE ); virtual AbstractAssistentDlg* CreateAssistentDlg( ::Window* pParent, BOOL bAutoPilot); virtual AbstractSdModifyFieldDlg* CreateSdModifyFieldDlg( ::Window* pWindow, const SvxFieldData* pInField, const SfxItemSet& rSet ); virtual AbstractSdSnapLineDlg* CreateSdSnapLineDlg( ::Window* pWindow, const SfxItemSet& rInAttrs, ::sd::View* pView); virtual AbstractSdInsertLayerDlg* CreateSdInsertLayerDlg( ::Window* pWindow, const SfxItemSet& rInAttrs, BOOL bDeletable, String aStr ); virtual AbstractSdInsertPasteDlg* CreateSdInsertPasteDlg( ::Window* pWindow ); virtual AbstractSdInsertPagesObjsDlg* CreateSdInsertPagesObjsDlg( ::Window* pParent, const SdDrawDocument* pDoc, SfxMedium* pSfxMedium, const String& rFileName ); virtual AbstractMorphDlg* CreateMorphDlg( ::Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2); virtual SfxAbstractTabDialog* CreateSdOutlineBulletTabDlg ( ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView = NULL ); virtual SfxAbstractTabDialog* CreateSdParagraphTabDlg ( ::Window* pParent, const SfxItemSet* pAttr ); virtual AbstractSdStartPresDlg* CreateSdStartPresentationDlg( ::Window* pWindow, const SfxItemSet& rInAttrs, List& rPageNames, List* pCSList ); virtual AbstractSdPrintDlg* CreateSdPrintDlg( ::Window* pWindow ); //add for SdPrintDlg virtual SfxAbstractTabDialog* CreateSdPresLayoutTemplateDlg( SfxObjectShell* pDocSh, ::Window* pParent, SdResId DlgId, SfxStyleSheetBase& rStyleBase, PresentationObjects ePO, SfxStyleSheetBasePool* pSSPool ); virtual AbstractSdPresLayoutDlg* CreateSdPresLayoutDlg( ::sd::DrawDocShell* pDocShell, ::sd::ViewShell* pViewShell, ::Window* pWindow, const SfxItemSet& rInAttrs); virtual SfxAbstractTabDialog* CreateSdTabTemplateDlg( ::Window* pParent, const SfxObjectShell* pDocShell, SfxStyleSheetBase& rStyleBase, SdrModel* pModel, SdrView* pView ); virtual AbstractSfxSingleTabDialog* CreatSdActionDialog( ::Window* pParent, const SfxItemSet* pAttr, ::sd::View* pView ); virtual AbstractSdVectorizeDlg* CreateSdVectorizeDlg( ::Window* pParent, const Bitmap& rBmp, ::sd::DrawDocShell* pDocShell ); virtual AbstractSdPublishingDlg* CreateSdPublishingDlg( ::Window* pWindow, DocumentType eDocType); virtual VclAbstractDialog* CreateMasterLayoutDialog( ::Window* pParent, SdDrawDocument* pDoc, SdPage* ); // add for MasterLayoutDialog virtual AbstractHeaderFooterDialog* CreateHeaderFooterDialog( ViewShell* pViewShell, ::Window* pParent, SdDrawDocument* pDoc, SdPage* pCurrentPage ); // add for HeaderFooterDialog // For TabPage virtual CreateTabPage GetSdOptionsContentsTabPageCreatorFunc(); virtual CreateTabPage GetSdPrintOptionsTabPageCreatorFunc(); virtual CreateTabPage GetSdOptionsMiscTabPageCreatorFunc(); virtual CreateTabPage GetSdOptionsSnapTabPageCreatorFunc(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuoltext.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:52:52 $ * * 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_sd.hxx" #include "fuoltext.hxx" #include <sfx2/viewfrm.hxx> #ifndef _OUTLINER_HXX #include <svx/outliner.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #define ITEMID_FIELD EE_FEATURE_FIELD #ifndef _SVX_FLDITEM_HXX //autogen #include <svx/flditem.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SFXDISPATCH_HXX #include <sfx2/dispatch.hxx> #endif #include <svx/svxids.hrc> #include "app.hrc" #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "DrawDocShell.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #include <stdio.h> // Fuer SlotFilter-Listing namespace sd { static USHORT SidArray[] = { SID_STYLE_FAMILY2, SID_STYLE_FAMILY5, SID_STYLE_UPDATE_BY_EXAMPLE, SID_CUT, SID_COPY, SID_PASTE, SID_SELECTALL, SID_ATTR_CHAR_FONT, SID_ATTR_CHAR_POSTURE, SID_ATTR_CHAR_WEIGHT, SID_ATTR_CHAR_UNDERLINE, SID_ATTR_CHAR_FONTHEIGHT, SID_ATTR_CHAR_COLOR, SID_OUTLINE_UP, SID_OUTLINE_DOWN, SID_OUTLINE_LEFT, SID_OUTLINE_RIGHT, //SID_OUTLINE_FORMAT, SID_OUTLINE_COLLAPSE_ALL, //SID_OUTLINE_BULLET, SID_OUTLINE_COLLAPSE, SID_OUTLINE_EXPAND_ALL, SID_OUTLINE_EXPAND, SID_SET_SUPER_SCRIPT, SID_SET_SUB_SCRIPT, SID_HYPERLINK_GETLINK, SID_PRESENTATION_TEMPLATES, SID_STATUS_PAGE, SID_STATUS_LAYOUT, SID_EXPAND_PAGE, SID_SUMMARY_PAGE, SID_PARASPACE_INCREASE, SID_PARASPACE_DECREASE, 0 }; TYPEINIT1( FuOutlineText, FuOutline ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuOutlineText::FuOutlineText(ViewShell* pViewShell, ::sd::Window* pWindow, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuOutline(pViewShell, pWindow, pView, pDoc, rReq) { } FunctionReference FuOutlineText::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuOutlineText( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute( rReq ); return xFunc; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; pWindow->GrabFocus(); bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonDown(rMEvt); if (bReturn) { // Attributierung der akt. Textstelle kann jetzt anders sein pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); } else { bReturn = FuOutline::MouseButtonDown(rMEvt); } return (bReturn); } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseMove(rMEvt); if (!bReturn) { bReturn = FuOutline::MouseMove(rMEvt); } // MT 07/2002: Done in OutlinerView::MouseMove /* const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )-> GetFieldUnderMousePointer(); const SvxFieldData* pField = NULL; if( pFieldItem ) pField = pFieldItem->GetField(); if( pField && pField->ISA( SvxURLField ) ) { pWindow->SetPointer( Pointer( POINTER_REFHAND ) ); } else pWindow->SetPointer( Pointer( POINTER_TEXT ) ); */ return (bReturn); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonUp(rMEvt); if (bReturn) { // Attributierung der akt. Textstelle kann jetzt anders sein pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); } else { const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->GetFieldUnderMousePointer(); if( pFieldItem ) { const SvxFieldData* pField = pFieldItem->GetField(); if( pField && pField->ISA( SvxURLField ) ) { bReturn = TRUE; pWindow->ReleaseMouse(); SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() ); SfxStringItem aReferer( SID_REFERER, pDocSh->GetMedium()->GetName() ); SfxBoolItem aBrowseItem( SID_BROWSE, TRUE ); SfxViewFrame* pFrame = pViewShell->GetViewFrame(); if ( rMEvt.IsMod1() ) { // Im neuen Frame oeffnen pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aStrItem, &aBrowseItem, &aReferer, 0L); } else { // Im aktuellen Frame oeffnen SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame ); pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L); } } } } if( !bReturn ) bReturn = FuOutline::MouseButtonUp(rMEvt); return (bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FALSE; USHORT nKeyGroup = rKEvt.GetKeyCode().GetGroup(); if( !pDocSh->IsReadOnly() || nKeyGroup == KEYGROUP_CURSOR ) { pWindow->GrabFocus(); std::auto_ptr< OutlineViewModelChangeGuard > aGuard; if( (nKeyGroup != KEYGROUP_CURSOR) && (nKeyGroup != KEYGROUP_FKEYS) ) aGuard.reset( new OutlineViewModelChangeGuard( *pOutlineView ) ); bReturn = pOutlineView->GetViewByWindow(pWindow)->PostKeyEvent(rKEvt); if (bReturn) { UpdateForKeyPress (rKEvt); } else { bReturn = FuOutline::KeyInput(rKEvt); } } return (bReturn); } void FuOutlineText::UpdateForKeyPress (const KeyEvent& rEvent) { // Attributes at the current text position may have changed. pViewShell->GetViewFrame()->GetBindings().Invalidate(SidArray); bool bUpdatePreview = true; switch (rEvent.GetKeyCode().GetCode()) { // When just the cursor has been moved the preview only changes when // it moved to entries of another page. To prevent unnecessary // updates we check this here. This is an early rejection test, so // missing a key is not a problem. case KEY_UP: case KEY_DOWN: case KEY_LEFT: case KEY_RIGHT: case KEY_HOME: case KEY_END: case KEY_PAGEUP: case KEY_PAGEDOWN: { SdPage* pCurrentPage = pOutlineViewShell->GetActualPage(); bUpdatePreview = (pCurrentPage != pOutlineViewShell->GetActualPage()); } break; } if (bUpdatePreview) pOutlineViewShell->UpdatePreview (pOutlineViewShell->GetActualPage()); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuOutlineText::Activate() { FuOutline::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuOutlineText::Deactivate() { FuOutline::Deactivate(); } /************************************************************************* |* |* Cut object to clipboard |* \************************************************************************/ void FuOutlineText::DoCut() { pOutlineView->GetViewByWindow(pWindow)->Cut(); } /************************************************************************* |* |* Copy object to clipboard |* \************************************************************************/ void FuOutlineText::DoCopy() { pOutlineView->GetViewByWindow(pWindow)->Copy(); } /************************************************************************* |* |* Paste object from clipboard |* \************************************************************************/ void FuOutlineText::DoPaste() { pOutlineView->GetViewByWindow(pWindow)->PasteSpecial(); } } // end of namespace sd <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.12.38); FILE MERGED 2006/11/22 12:41:54 cl 1.12.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuoltext.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:20:50 $ * * 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_sd.hxx" #include "fuoltext.hxx" #include <sfx2/viewfrm.hxx> #ifndef _OUTLINER_HXX #include <svx/outliner.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #define ITEMID_FIELD EE_FEATURE_FIELD #ifndef _SVX_FLDITEM_HXX //autogen #include <svx/flditem.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SFXDISPATCH_HXX #include <sfx2/dispatch.hxx> #endif #include <svx/svxids.hrc> #include "app.hrc" #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "DrawDocShell.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #include <stdio.h> // Fuer SlotFilter-Listing namespace sd { static USHORT SidArray[] = { SID_STYLE_FAMILY2, SID_STYLE_FAMILY5, SID_STYLE_UPDATE_BY_EXAMPLE, SID_CUT, SID_COPY, SID_PASTE, SID_SELECTALL, SID_ATTR_CHAR_FONT, SID_ATTR_CHAR_POSTURE, SID_ATTR_CHAR_WEIGHT, SID_ATTR_CHAR_UNDERLINE, SID_ATTR_CHAR_FONTHEIGHT, SID_ATTR_CHAR_COLOR, SID_OUTLINE_UP, SID_OUTLINE_DOWN, SID_OUTLINE_LEFT, SID_OUTLINE_RIGHT, //SID_OUTLINE_FORMAT, SID_OUTLINE_COLLAPSE_ALL, //SID_OUTLINE_BULLET, SID_OUTLINE_COLLAPSE, SID_OUTLINE_EXPAND_ALL, SID_OUTLINE_EXPAND, SID_SET_SUPER_SCRIPT, SID_SET_SUB_SCRIPT, SID_HYPERLINK_GETLINK, SID_PRESENTATION_TEMPLATES, SID_STATUS_PAGE, SID_STATUS_LAYOUT, SID_EXPAND_PAGE, SID_SUMMARY_PAGE, SID_PARASPACE_INCREASE, SID_PARASPACE_DECREASE, 0 }; TYPEINIT1( FuOutlineText, FuOutline ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuOutlineText::FuOutlineText(ViewShell* pViewShell, ::sd::Window* pWindow, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuOutline(pViewShell, pWindow, pView, pDoc, rReq) { } FunctionReference FuOutlineText::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuOutlineText( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute( rReq ); return xFunc; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; mpWindow->GrabFocus(); bReturn = pOutlineView->GetViewByWindow(mpWindow)->MouseButtonDown(rMEvt); if (bReturn) { // Attributierung der akt. Textstelle kann jetzt anders sein mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); } else { bReturn = FuOutline::MouseButtonDown(rMEvt); } return (bReturn); } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = pOutlineView->GetViewByWindow(mpWindow)->MouseMove(rMEvt); if (!bReturn) { bReturn = FuOutline::MouseMove(rMEvt); } // MT 07/2002: Done in OutlinerView::MouseMove /* const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( mpWindow )-> GetFieldUnderMousePointer(); const SvxFieldData* pField = NULL; if( pFieldItem ) pField = pFieldItem->GetField(); if( pField && pField->ISA( SvxURLField ) ) { mpWindow->SetPointer( Pointer( POINTER_REFHAND ) ); } else mpWindow->SetPointer( Pointer( POINTER_TEXT ) ); */ return (bReturn); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = pOutlineView->GetViewByWindow(mpWindow)->MouseButtonUp(rMEvt); if (bReturn) { // Attributierung der akt. Textstelle kann jetzt anders sein mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); } else { const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( mpWindow )->GetFieldUnderMousePointer(); if( pFieldItem ) { const SvxFieldData* pField = pFieldItem->GetField(); if( pField && pField->ISA( SvxURLField ) ) { bReturn = TRUE; mpWindow->ReleaseMouse(); SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() ); SfxStringItem aReferer( SID_REFERER, mpDocSh->GetMedium()->GetName() ); SfxBoolItem aBrowseItem( SID_BROWSE, TRUE ); SfxViewFrame* pFrame = mpViewShell->GetViewFrame(); if ( rMEvt.IsMod1() ) { // Im neuen Frame oeffnen pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aStrItem, &aBrowseItem, &aReferer, 0L); } else { // Im aktuellen Frame oeffnen SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame ); pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L); } } } } if( !bReturn ) bReturn = FuOutline::MouseButtonUp(rMEvt); return (bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FALSE; USHORT nKeyGroup = rKEvt.GetKeyCode().GetGroup(); if( !mpDocSh->IsReadOnly() || nKeyGroup == KEYGROUP_CURSOR ) { mpWindow->GrabFocus(); std::auto_ptr< OutlineViewModelChangeGuard > aGuard; if( (nKeyGroup != KEYGROUP_CURSOR) && (nKeyGroup != KEYGROUP_FKEYS) ) aGuard.reset( new OutlineViewModelChangeGuard( *pOutlineView ) ); bReturn = pOutlineView->GetViewByWindow(mpWindow)->PostKeyEvent(rKEvt); if (bReturn) { UpdateForKeyPress (rKEvt); } else { bReturn = FuOutline::KeyInput(rKEvt); } } return (bReturn); } void FuOutlineText::UpdateForKeyPress (const KeyEvent& rEvent) { // Attributes at the current text position may have changed. mpViewShell->GetViewFrame()->GetBindings().Invalidate(SidArray); bool bUpdatePreview = true; switch (rEvent.GetKeyCode().GetCode()) { // When just the cursor has been moved the preview only changes when // it moved to entries of another page. To prevent unnecessary // updates we check this here. This is an early rejection test, so // missing a key is not a problem. case KEY_UP: case KEY_DOWN: case KEY_LEFT: case KEY_RIGHT: case KEY_HOME: case KEY_END: case KEY_PAGEUP: case KEY_PAGEDOWN: { SdPage* pCurrentPage = pOutlineViewShell->GetActualPage(); bUpdatePreview = (pCurrentPage != pOutlineViewShell->GetActualPage()); } break; } if (bUpdatePreview) pOutlineViewShell->UpdatePreview (pOutlineViewShell->GetActualPage()); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuOutlineText::Activate() { FuOutline::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuOutlineText::Deactivate() { FuOutline::Deactivate(); } /************************************************************************* |* |* Cut object to clipboard |* \************************************************************************/ void FuOutlineText::DoCut() { pOutlineView->GetViewByWindow(mpWindow)->Cut(); } /************************************************************************* |* |* Copy object to clipboard |* \************************************************************************/ void FuOutlineText::DoCopy() { pOutlineView->GetViewByWindow(mpWindow)->Copy(); } /************************************************************************* |* |* Paste object from clipboard |* \************************************************************************/ void FuOutlineText::DoPaste() { pOutlineView->GetViewByWindow(mpWindow)->PasteSpecial(); } } // end of namespace sd <|endoftext|>
<commit_before><commit_msg>coverity#705876 Dereference before null check<commit_after><|endoftext|>
<commit_before><commit_msg>-Werror,-Wunused-const-variable<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: presvish.cxx,v $ * * $Revision: 1.26 $ * * last change: $Author: vg $ $Date: 2005-03-23 14:05:38 $ * * 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): _______________________________________ * * ************************************************************************/ #include "PresentationViewShell.hxx" #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFX_TOPFRM_HXX #include <sfx2/topfrm.hxx> #endif #ifndef _SFX_DISPATCH_HXX #include <sfx2/dispatch.hxx> #endif #include <sfx2/objface.hxx> #include <svx/svxids.hrc> #include <sfx2/app.hxx> #ifndef SD_FRAME_VIEW #include "FrameView.hxx" #endif #include "sdresid.hxx" #include "DrawDocShell.hxx" #ifndef _SD_SLIDESHOW_HXX #include "slideshow.hxx" #endif #include "sdattr.hxx" #include "sdpage.hxx" #include "drawdoc.hxx" #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #include "app.hrc" #include "strings.hrc" #include "glob.hrc" #include "PaneManager.hxx" #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #ifndef SD_FACTORY_IDS_HXX #include "FactoryIds.hxx" #endif // #110496# #include "slideshow.hxx" #include "fupoor.hxx" #include "Window.hxx" #define PresentationViewShell using namespace sd; #include "sdslots.hxx" namespace sd { // ------------------- // - PresentationViewShell - // ------------------- SFX_IMPL_INTERFACE( PresentationViewShell, DrawViewShell, SdResId( STR_PRESVIEWSHELL ) ) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_TOOLBOX)); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_APPLICATION | SFX_VISIBILITY_DESKTOP | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_CLIENT | SFX_VISIBILITY_VIEWER | SFX_VISIBILITY_READONLYDOC, SdResId(RID_DRAW_VIEWER_TOOLBOX) ); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_OPTIONS_TOOLBOX)); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_COMMONTASK_TOOLBOX)); } TYPEINIT1( PresentationViewShell, DrawViewShell ); PresentationViewShell::PresentationViewShell ( SfxViewFrame* pFrame, ViewShellBase& rViewShellBase, ::Window* pParentWindow, FrameView* pFrameView) : DrawViewShell ( pFrame, rViewShellBase, pParentWindow, PK_STANDARD, pFrameView), mbShowStarted( sal_False ) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED ) maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT ); meShellType = ST_PRESENTATION; } PresentationViewShell::PresentationViewShell ( SfxViewFrame* pFrame, ::Window* pParentWindow, const DrawViewShell& rShell) : DrawViewShell (pFrame, pParentWindow, rShell), mbShowStarted( sal_False ) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED ) maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT ); meShellType = ST_PRESENTATION; } PresentationViewShell::~PresentationViewShell (void) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() ) GetDocSh()->SetVisArea( maOldVisArea ); if( GetViewFrame() && GetViewFrame()->GetTopFrame() ) { WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent(); if( pWorkWindow ) pWorkWindow->StartPresentationMode( FALSE, mpSlideShow ? mpSlideShow->isAlwaysOnTop() : 0 ); } if( mpSlideShow ) { mpSlideShow->deactivate(); mpSlideShow->stopShow(); mpSlideShow->dispose(); delete mpSlideShow; mpSlideShow = NULL; } } void PresentationViewShell::FinishInitialization ( FrameView* pFrameView, SfxRequest& rRequest, USHORT nPageNumber) { DrawViewShell::Init(); // Use the frame view that comes form the view shell that initiated our // creation. if (pFrameView != NULL) { GetFrameView()->Disconnect(); SetFrameView (pFrameView); pFrameView->Connect(); } SetRuler(false); SwitchPage (nPageNumber); WriteFrameViewData(); mpSlideShow = new sd::Slideshow( this, GetView(), GetDoc() ); mpSlideShow->setRehearseTimings( rRequest.GetSlot() == SID_REHEARSE_TIMINGS ); GetActiveWindow()->GrabFocus(); // Start the show. if (mpSlideShow->startShow(0)) mbShowStarted = sal_True; else { delete mpSlideShow; mpSlideShow = 0; } GetViewFrame()->Show(); Activate(TRUE); } SvxRuler* PresentationViewShell::CreateHRuler(::sd::Window* pWin, BOOL bIsFirst) { return NULL; } SvxRuler* PresentationViewShell::CreateVRuler(::sd::Window* pWin) { return NULL; } void PresentationViewShell::Activate( BOOL bIsMDIActivate ) { DrawViewShell::Activate( bIsMDIActivate ); if( bIsMDIActivate ) { ::sd::View* pView = GetView(); SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE ); GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L ); if( mpSlideShow) mpSlideShow->activate(); if( pFuActual ) pFuActual->Activate(); if( pView ) pView->ShowMarkHdl( NULL ); } if( bIsMDIActivate ) ReadFrameViewData( pFrameView ); GetDocSh()->Connect( this ); if( mpSlideShow && !mbShowStarted ) { if (mpSlideShow->startShow(0)) mbShowStarted = sal_True; else { delete mpSlideShow; mpSlideShow = 0; } } } void PresentationViewShell::Paint( const Rectangle& rRect, ::sd::Window* pWin ) { // allow paints only if show is already started if( mbShowStarted && mpSlideShow ) mpSlideShow->paint(rRect); } void PresentationViewShell::CreateFullScreenShow ( ViewShell* pOriginShell, SfxRequest& rRequest) { SdDrawDocument* pDoc = pOriginShell->GetDoc(); SdPage* pCurrentPage = pOriginShell->GetActualPage(); SFX_REQUEST_ARG (rRequest, pAlwaysOnTop, SfxBoolItem, ATTR_PRESENT_ALWAYS_ON_TOP, FALSE); bool bAlwaysOnTop = ((rRequest.GetSlot() != SID_REHEARSE_TIMINGS) && pAlwaysOnTop ) ? pAlwaysOnTop->GetValue() : pDoc->getPresentationSettings().mbAlwaysOnTop; WorkWindow* pWorkWindow = new WorkWindow ( NULL, WB_HIDE | WB_CLIPCHILDREN); pWorkWindow->StartPresentationMode ( TRUE, bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0); pWorkWindow->SetBackground(Wallpaper(COL_BLACK)); if (pWorkWindow->IsVisible()) { // The new frame is created hidden. To make it visible and activate // the new view shell--a prerequisite to process slot calls and // initialize its panes--a GrabFocus() has to be called later on. SfxTopFrame* pNewFrame = SfxTopFrame::Create ( pDoc->GetDocSh(), pWorkWindow, PRESENTATION_FACTORY_ID, TRUE); pNewFrame->SetPresentationMode (TRUE); ViewShellBase* pBase = static_cast<ViewShellBase*>( pNewFrame->GetCurrentViewFrame()->GetViewShell()); if (pBase != NULL) { // Get the page where the show is to be started. This normally // is the current page of the shell from which the show has been // started. This, however, may be NULL, e.g. when started from // the slide sorter and that has an empty selection. USHORT nStartPage = 0; if (pCurrentPage != NULL) nStartPage = (pCurrentPage->GetPageNum() - 1) / 2; // pBase->GetViewFrame()->Show(); // The following GrabFocus() is responsible for activating the // new view shell. Without it the screen remains blank (under // Windows and some Linux variants.) pBase->GetWindow()->GrabFocus(); PresentationViewShell* pShell = PTR_CAST(PresentationViewShell, pBase->GetMainViewShell()); if (pShell != NULL) pShell->FinishInitialization ( pOriginShell->GetFrameView(), rRequest, nStartPage); } } } } // end of namespace sd <commit_msg>INTEGRATION: CWS ooo19126 (1.26.154); FILE MERGED 2005/09/05 13:25:59 rt 1.26.154.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: presvish.cxx,v $ * * $Revision: 1.27 $ * * last change: $Author: rt $ $Date: 2005-09-09 07:15:50 $ * * 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 * ************************************************************************/ #include "PresentationViewShell.hxx" #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFX_TOPFRM_HXX #include <sfx2/topfrm.hxx> #endif #ifndef _SFX_DISPATCH_HXX #include <sfx2/dispatch.hxx> #endif #include <sfx2/objface.hxx> #include <svx/svxids.hrc> #include <sfx2/app.hxx> #ifndef SD_FRAME_VIEW #include "FrameView.hxx" #endif #include "sdresid.hxx" #include "DrawDocShell.hxx" #ifndef _SD_SLIDESHOW_HXX #include "slideshow.hxx" #endif #include "sdattr.hxx" #include "sdpage.hxx" #include "drawdoc.hxx" #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #include "app.hrc" #include "strings.hrc" #include "glob.hrc" #include "PaneManager.hxx" #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #ifndef SD_FACTORY_IDS_HXX #include "FactoryIds.hxx" #endif // #110496# #include "slideshow.hxx" #include "fupoor.hxx" #include "Window.hxx" #define PresentationViewShell using namespace sd; #include "sdslots.hxx" namespace sd { // ------------------- // - PresentationViewShell - // ------------------- SFX_IMPL_INTERFACE( PresentationViewShell, DrawViewShell, SdResId( STR_PRESVIEWSHELL ) ) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_TOOLBOX)); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_APPLICATION | SFX_VISIBILITY_DESKTOP | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_CLIENT | SFX_VISIBILITY_VIEWER | SFX_VISIBILITY_READONLYDOC, SdResId(RID_DRAW_VIEWER_TOOLBOX) ); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_OPTIONS_TOOLBOX)); SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_SERVER, SdResId(RID_DRAW_COMMONTASK_TOOLBOX)); } TYPEINIT1( PresentationViewShell, DrawViewShell ); PresentationViewShell::PresentationViewShell ( SfxViewFrame* pFrame, ViewShellBase& rViewShellBase, ::Window* pParentWindow, FrameView* pFrameView) : DrawViewShell ( pFrame, rViewShellBase, pParentWindow, PK_STANDARD, pFrameView), mbShowStarted( sal_False ) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED ) maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT ); meShellType = ST_PRESENTATION; } PresentationViewShell::PresentationViewShell ( SfxViewFrame* pFrame, ::Window* pParentWindow, const DrawViewShell& rShell) : DrawViewShell (pFrame, pParentWindow, rShell), mbShowStarted( sal_False ) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED ) maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT ); meShellType = ST_PRESENTATION; } PresentationViewShell::~PresentationViewShell (void) { if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() ) GetDocSh()->SetVisArea( maOldVisArea ); if( GetViewFrame() && GetViewFrame()->GetTopFrame() ) { WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent(); if( pWorkWindow ) pWorkWindow->StartPresentationMode( FALSE, mpSlideShow ? mpSlideShow->isAlwaysOnTop() : 0 ); } if( mpSlideShow ) { mpSlideShow->deactivate(); mpSlideShow->stopShow(); mpSlideShow->dispose(); delete mpSlideShow; mpSlideShow = NULL; } } void PresentationViewShell::FinishInitialization ( FrameView* pFrameView, SfxRequest& rRequest, USHORT nPageNumber) { DrawViewShell::Init(); // Use the frame view that comes form the view shell that initiated our // creation. if (pFrameView != NULL) { GetFrameView()->Disconnect(); SetFrameView (pFrameView); pFrameView->Connect(); } SetRuler(false); SwitchPage (nPageNumber); WriteFrameViewData(); mpSlideShow = new sd::Slideshow( this, GetView(), GetDoc() ); mpSlideShow->setRehearseTimings( rRequest.GetSlot() == SID_REHEARSE_TIMINGS ); GetActiveWindow()->GrabFocus(); // Start the show. if (mpSlideShow->startShow(0)) mbShowStarted = sal_True; else { delete mpSlideShow; mpSlideShow = 0; } GetViewFrame()->Show(); Activate(TRUE); } SvxRuler* PresentationViewShell::CreateHRuler(::sd::Window* pWin, BOOL bIsFirst) { return NULL; } SvxRuler* PresentationViewShell::CreateVRuler(::sd::Window* pWin) { return NULL; } void PresentationViewShell::Activate( BOOL bIsMDIActivate ) { DrawViewShell::Activate( bIsMDIActivate ); if( bIsMDIActivate ) { ::sd::View* pView = GetView(); SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE ); GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L ); if( mpSlideShow) mpSlideShow->activate(); if( pFuActual ) pFuActual->Activate(); if( pView ) pView->ShowMarkHdl( NULL ); } if( bIsMDIActivate ) ReadFrameViewData( pFrameView ); GetDocSh()->Connect( this ); if( mpSlideShow && !mbShowStarted ) { if (mpSlideShow->startShow(0)) mbShowStarted = sal_True; else { delete mpSlideShow; mpSlideShow = 0; } } } void PresentationViewShell::Paint( const Rectangle& rRect, ::sd::Window* pWin ) { // allow paints only if show is already started if( mbShowStarted && mpSlideShow ) mpSlideShow->paint(rRect); } void PresentationViewShell::CreateFullScreenShow ( ViewShell* pOriginShell, SfxRequest& rRequest) { SdDrawDocument* pDoc = pOriginShell->GetDoc(); SdPage* pCurrentPage = pOriginShell->GetActualPage(); SFX_REQUEST_ARG (rRequest, pAlwaysOnTop, SfxBoolItem, ATTR_PRESENT_ALWAYS_ON_TOP, FALSE); bool bAlwaysOnTop = ((rRequest.GetSlot() != SID_REHEARSE_TIMINGS) && pAlwaysOnTop ) ? pAlwaysOnTop->GetValue() : pDoc->getPresentationSettings().mbAlwaysOnTop; WorkWindow* pWorkWindow = new WorkWindow ( NULL, WB_HIDE | WB_CLIPCHILDREN); pWorkWindow->StartPresentationMode ( TRUE, bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0); pWorkWindow->SetBackground(Wallpaper(COL_BLACK)); if (pWorkWindow->IsVisible()) { // The new frame is created hidden. To make it visible and activate // the new view shell--a prerequisite to process slot calls and // initialize its panes--a GrabFocus() has to be called later on. SfxTopFrame* pNewFrame = SfxTopFrame::Create ( pDoc->GetDocSh(), pWorkWindow, PRESENTATION_FACTORY_ID, TRUE); pNewFrame->SetPresentationMode (TRUE); ViewShellBase* pBase = static_cast<ViewShellBase*>( pNewFrame->GetCurrentViewFrame()->GetViewShell()); if (pBase != NULL) { // Get the page where the show is to be started. This normally // is the current page of the shell from which the show has been // started. This, however, may be NULL, e.g. when started from // the slide sorter and that has an empty selection. USHORT nStartPage = 0; if (pCurrentPage != NULL) nStartPage = (pCurrentPage->GetPageNum() - 1) / 2; // pBase->GetViewFrame()->Show(); // The following GrabFocus() is responsible for activating the // new view shell. Without it the screen remains blank (under // Windows and some Linux variants.) pBase->GetWindow()->GrabFocus(); PresentationViewShell* pShell = PTR_CAST(PresentationViewShell, pBase->GetMainViewShell()); if (pShell != NULL) pShell->FinishInitialization ( pOriginShell->GetFrameView(), rRequest, nStartPage); } } } } // end of namespace sd <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_compact", storage_mode_compact) .value("storage_mode_sparse", storage_mode_sparse) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) #endif .def( "add_torrent", &add_torrent , ( arg("resume_data") = entry(), arg("compact_mode") = true , arg("paused") = false ) , session_add_torrent_doc ) .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) #ifndef TORRENT_DISABLE_DHT .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <commit_msg>python binding fix<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_compact", storage_mode_compact) .value("storage_mode_sparse", storage_mode_sparse) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) #endif .def( "add_torrent", &add_torrent , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) , session_add_torrent_doc ) .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) #ifndef TORRENT_DISABLE_DHT .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <|endoftext|>