Esempio n. 1
0
void RenderingWindowX11::addEventMask( unsigned long eventMask ) {
    XWindowAttributes windowAttributes = {};

    if( !::XGetWindowAttributes(_display, _handle, &windowAttributes) )
        throwRuntimeError( "::XGetWindowAttributes has failed" );

    windowAttributes.your_event_mask |= eventMask;

    if( !::XSelectInput(_display, _handle, windowAttributes.your_event_mask) )
        throwRuntimeError( "::XSelectInput has failed" );
}
Esempio n. 2
0
StreamWriter* StreamWriterBuilder::newStreamWriter() const
{
    std::string indentation = settings_["indentation"].asString();
    std::string cs_str = settings_["commentStyle"].asString();
    bool eyc = settings_["enableYAMLCompatibility"].asBool();
    bool dnp = settings_["dropNullPlaceholders"].asBool();
    bool usf = settings_["useSpecialFloats"].asBool();
    unsigned int pre = settings_["precision"].asUInt();
    CommentStyle::Enum cs = CommentStyle::All;
    if (cs_str == "All") {
        cs = CommentStyle::All;
    } else if (cs_str == "None") {
        cs = CommentStyle::None;
    } else {
        throwRuntimeError("commentStyle must be 'All' or 'None'");
    }
    std::string colonSymbol = " : ";
    if (eyc) {
        colonSymbol = ": ";
    } else if (indentation.empty()) {
        colonSymbol = ":";
    }
    std::string nullSymbol = "null";
    if (dnp) {
        nullSymbol = "";
    }
    if (pre > 17) pre = 17;
    std::string endingLineFeedSymbol = "";
    return new BuiltStyledStreamWriter(
               indentation, cs,
               colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
}
Esempio n. 3
0
RenderingWindowX11::RenderingWindowX11( XDisplay *display ) :
    _handle( None ), _display( display ), _fullscreen( false )
{
    const int defaultScreen = ::XDefaultScreen( _display );

    const Window parentWindow = ::XDefaultRootWindow( _display );
    const int x = 0;
    const int y = 0;
    const unsigned int width = 1;
    const unsigned int height = 1;
    const unsigned int borderWidth = 1;
    const unsigned long borderColor =
        ::XBlackPixel( _display, defaultScreen );
    const unsigned long backgroundColor =
        ::XWhitePixel( _display, defaultScreen );

    _handle = ::XCreateSimpleWindow( _display, parentWindow,
        x, y, width, height, borderWidth, borderColor, backgroundColor );
    if( _handle == None )
        throwRuntimeError( "::XCreateSimpleWindow has failed" );

    addEventMask( FocusChangeMask | PropertyChangeMask );

    installShutdownHandler();
    installFocusHandlers();
    installStateChangeHandlers();
}
Esempio n. 4
0
void RenderingWindowX11::installShutdownHandler() {
    Atom windowDestructionAtom = ::XInternAtom(
        _display, "WM_DELETE_WINDOW", /*onlyExisting = */ false );
    if( windowDestructionAtom == None )
        throwRuntimeError( "::XInternAtom has failed" );

    const Status result = ::XSetWMProtocols(
        _display, _handle, &windowDestructionAtom, /*count = */ 1 );
    if( !result )
        throwRuntimeError( "::XSetWMProtocols has failed" );

    _eventListener.onEvent[ClientMessage] = [=]( const XEvent &event ) {
        if( static_cast<Atom>(event.xclient.data.l[0]) ==
            windowDestructionAtom )
        {
            _observers.notify( &Observer::onShutdown );
            EventLoop::getInstance()->stop();
        }
    };
}
Esempio n. 5
0
  Part::Part(const_iterator b, const_iterator e)
  {
    iterator_streambuf<const_iterator> buf(b, e);
    std::istream in(&buf);
    in >> _header;
    if (!in)
      throwRuntimeError("error in parsing message-header");
    in.sync();

    _bodyBegin = b;
    _bodyEnd = e;
  }
Esempio n. 6
0
void RenderingWindowX11::installStateChangeHandlers() {
    Atom windowStateAtom = ::XInternAtom(
        _display, "WM_STATE", /*onlyExisting = */ false );
    if( windowStateAtom == None )
        throwRuntimeError( "::XInternAtom has failed" );

    _eventListener.onEvent[PropertyNotify] = [=]( const XEvent &event ) {
        if( event.xproperty.atom == windowStateAtom &&
            event.xproperty.state == PropertyNewValue )
        {
            const long offset = 0;
            const long length = 2; // The number of 32-bit fields
            const Bool shouldDelete = false;
            const Atom type = windowStateAtom;

            // Returned values
            Atom actualType;
            int actualFormat;
            unsigned long itemNumber;
            unsigned long remainingBytes;

            struct State {
                uint32_t state;
                uint32_t icon;
            } *state = nullptr;

            ::XGetWindowProperty(
                _display,
                _handle,
                windowStateAtom,
                offset,
                length,
                shouldDelete,
                type,
                &actualType,
                &actualFormat,
                &itemNumber,
                &remainingBytes,
                reinterpret_cast<unsigned char**>(&state) );

            if( state ) {
                if( state->state == NormalState )
                    _observers.notify( &Observer::onUnfolding );
                else if( state->state == IconicState )
                    _observers.notify( &Observer::onFolding );
                ::XFree( state );
            }
        }
    };
}
Esempio n. 7
0
/** Duplicates the specified string value.
 * @param value Pointer to the string to duplicate. Must be zero-terminated if
 *              length is "unknown".
 * @param length Length of the value. if equals to unknown, then it will be
 *               computed using strlen(value).
 * @return Pointer on the duplicate instance of string.
 */
static inline char* duplicateStringValue(const char* value, size_t length) {
  // Avoid an integer overflow in the call to malloc below by limiting length
  // to a sane value.
  if (length >= static_cast<size_t>(Value::maxInt))
    length = Value::maxInt - 1;

  char* newString = static_cast<char*>(malloc(length + 1));
  if (newString == nullptr) {
    throwRuntimeError("in Json::Value::duplicateStringValue(): "
                      "Failed to allocate string value buffer");
  }
  memcpy(newString, value, length);
  newString[length] = 0;
  return newString;
}
Esempio n. 8
0
/* Record the length as a prefix.
 */
static inline char* duplicateAndPrefixStringValue(const char* value,
                                                  unsigned int length) {
  // Avoid an integer overflow in the call to malloc below by limiting length
  // to a sane value.
  JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) -
                                    sizeof(unsigned) - 1U,
                      "in Json::Value::duplicateAndPrefixStringValue(): "
                      "length too big for prefixing");
  unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
  char* newString = static_cast<char*>(malloc(actualLength));
  if (newString == nullptr) {
    throwRuntimeError("in Json::Value::duplicateAndPrefixStringValue(): "
                      "Failed to allocate string value buffer");
  }
  *reinterpret_cast<unsigned*>(newString) = length;
  memcpy(newString + sizeof(unsigned), value, length);
  newString[actualLength - 1U] =
      0; // to avoid buffer over-run accidents by users later
  return newString;
}
Esempio n. 9
0
void Zdata::addRef()
{
    if (cxxtools::atomicIncrement(_refs) == 1)
    {
        // allocate uncompressed data
        _data = new char[_data_len];

        // uncompress Zdata => data
        log_debug("uncompress " << _zdata_len << " to " << _data_len << " bytes");
        uLong dest_len = _data_len;
        int z_ret = uncompress((Bytef*)_data, &dest_len, (const Bytef*)_zptr, _zdata_len);
        if (z_ret != Z_OK)
        {
            throwRuntimeError(std::string("error uncompressing data: ") +
                              (z_ret == Z_MEM_ERROR ? "Z_MEM_ERROR" :
                               z_ret == Z_BUF_ERROR ? "Z_BUF_ERROR" :
                               z_ret == Z_DATA_ERROR ? "Z_DATA_ERROR" : "unknown error"));
        }
        log_debug("uncompress ready");
    }
}
Esempio n. 10
0
TEST_F(AssertionTest, throwExceptionShouldThrowWhenExpressionThrowsADifferentException)
{
    expectAssertionFailedWithExpectation(
        []{ CXXSPEC_EXPECT(throwRuntimeError()).should.throwException<std::logic_error>(); },
        "has thrown an unexpected exception");
}
Esempio n. 11
0
  void TntnetImpl::run()
  {
    log_debug("worker-process");

    _stop = false;

    if (_listeners.empty())
      throwRuntimeError("no listeners defined");

    log_debug(_listeners.size() << " listeners");

    if (_listeners.size() >= _minthreads)
    {
      log_warn("at least one more worker than listeners needed - set MinThreads to "
        << _listeners.size() + 1);
      _minthreads = _listeners.size() + 1;
    }

    if (_maxthreads < _minthreads)
    {
      log_warn("MaxThreads < MinThreads - set MaxThreads = MinThreads = " << _minthreads);
      _maxthreads = _minthreads;
    }

    // initialize worker-process

    // SIGPIPE must be ignored
    ::signal(SIGPIPE, SIG_IGN);

    // create worker-threads
    log_info("create " << _minthreads << " worker threads");
    for (unsigned i = 0; i < _minthreads; ++i)
    {
      log_debug("create worker " << i);
      Worker* s = new Worker(*this);
      s->create();
    }

    // create poller-thread
    log_debug("start poller thread");
    _pollerthread.start();

    log_debug("start timer thread");
    cxxtools::AttachedThread timerThread(cxxtools::callable(*this, &TntnetImpl::timerTask));
    timerThread.start();

    {
      cxxtools::MutexLock lock(allTntnetInstancesMutex);
      allRunningTntnetInstances.insert(this);
    }

    // mainloop
    cxxtools::Mutex mutex;
    while (!_stop)
    {
      {
        cxxtools::MutexLock lock(mutex);
        _queue.noWaitThreads.wait(lock);
      }

      if (_stop)
        break;

      if (Worker::getCountThreads() < _maxthreads)
      {
        log_info("create workerthread");
        Worker* s = new Worker(*this);
        s->create();
      }
      else
        log_info("max worker-threadcount " << _maxthreads << " reached");

      if (TntConfig::it().threadStartDelay > 0)
        usleep(TntConfig::it().threadStartDelay.totalUSecs());
    }

    log_info("stopping TntnetImpl");

    {
      cxxtools::MutexLock lock(allTntnetInstancesMutex);
      allRunningTntnetInstances.erase(this);
    }

    log_info("stop listener");
    for (listeners_type::iterator it = _listeners.begin(); it != _listeners.end(); ++it)
      (*it)->terminate();

    log_info("stop poller thread");
    _poller.doStop();
    _pollerthread.join();

    log_info("stop timer thread");
    timerThread.join();

    if (Worker::getCountThreads() > 0)
    {
      log_info("wait for " << Worker::getCountThreads() << " worker threads to stop");
      while (Worker::getCountThreads() > 0)
      {
        log_debug("wait for worker threads to stop; " << Worker::getCountThreads() << " left");
        usleep(100);
      }
    }

    log_debug("destroy listener");
    for (listeners_type::iterator it = _listeners.begin(); it != _listeners.end(); ++it)
      delete *it;
    _listeners.clear();

    HttpReply::postRunCleanup();
    HttpRequest::postRunCleanup();

    log_info("all threads stopped");
  }
Esempio n. 12
0
 void throwRuntimeError(const char* msg)
   { throwRuntimeError(std::string(msg)); }
Esempio n. 13
0
ValueIterator::ValueIterator(const ValueConstIterator& other)
    : ValueIteratorBase(other) {
  throwRuntimeError("ConstIterator to Iterator should never be allowed.");
}