Example #1
0
/**
 * @brief Executed when new instance connect command is sent to LocalServer
 */
void Rshare::slotConnectionEstablished()
{
	QLocalSocket *socket = localServer->nextPendingConnection();
	socket->close();
	delete socket;

	QSharedMemory newArgs;
	newArgs.setKey(QString(TARGET) + "_newArgs");

	if (!newArgs.attach())
	{
		std::cerr << "(EE) Rshare::slotConnectionEstablished() Unable to attach to shared memory segment."
		          << newArgs.errorString().toStdString() << std::endl;
		return;
	}

	QBuffer buffer;
	QDataStream in(&buffer);
	QStringList args;

	newArgs.lock();
	buffer.setData((char*)newArgs.constData(), newArgs.size());
	buffer.open(QBuffer::ReadOnly);
	in >> args;
	newArgs.unlock();
	newArgs.detach();

	emit newArgsReceived(args);
	while (!args.empty())
	{
		std::cerr << "Rshare::slotConnectionEstablished args:" << QString(args.takeFirst()).toStdString() << std::endl;
	}
}
Example #2
0
/** Перезагружает словарь по пути changedDictionaryPath */
void DictionaryManager::reloadDictionary()
{
    QString &path = changedDictionaryPath;
    qDebug() << QString("reloading dictionary from %1.").arg(path);
    try {
        QString key = filenameToKey.value(path);
        QSharedMemory *shared = data.value(key);
        if (!shared)
            throw Exception(QString("Ошибка перезагрузки словаря %1. Словарь не был загружен ранее.").arg(path));

        QFile fileDictionary(path);
        QByteArray buffer;
        if (!fileDictionary.open(QFile::ReadOnly))
            throw Exception(QString("Ошибка чтения файла словаря. Key: %1; file: %2").arg(key).arg(path));

        buffer = fileDictionary.readAll();
        shared->lock();
        char *to = (char *)shared->data();
        const char *from = buffer.data();
        memcpy(to, from, qMin(shared->size(), buffer.size()));
        shared->unlock();

        qDebug() << "Словарь обновлён";
    } catch (Exception &ex) {
        qDebug() << tr("Ошибка во время загрузки словаря %1.\nОписание: %2").arg(path).arg(ex.text());
    }
}
QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command)
{
    static const bool dontUseSharedMemory = !qgetenv("DESIGNER_DONT_USE_SHARED_MEMORY").isEmpty();

    if (!dontUseSharedMemory && command.valueChanges().count() > 5) {
        static quint32 keyCounter = 0;
        ++keyCounter;
        command.m_keyNumber = keyCounter;
        QByteArray outDataStreamByteArray;
        QDataStream temporaryOutDataStream(&outDataStreamByteArray, QIODevice::WriteOnly);
        temporaryOutDataStream.setVersion(QDataStream::Qt_4_8);

        temporaryOutDataStream << command.valueChanges();;

        QSharedMemory *sharedMemory = createSharedMemory(keyCounter, outDataStreamByteArray.size());

        if (sharedMemory) {
            std::memcpy(sharedMemory->data(), outDataStreamByteArray.constData(), sharedMemory->size());
            out << command.keyNumber();
            return out;
        }
    }

    out << qint32(0);
    out << command.valueChanges();

    return out;
}
Example #4
0
void conflict_core::updateAida(){
    QBuffer buffer;
    QDataStream in(&buffer);
    QString text;
    if(conflict.aidaOpen){
        aida.lock();
        buffer.setData((char*)aida.constData(), aida.size());
        buffer.open(QBuffer::ReadOnly);
        in >> text;
        ui->debugOutputOut->append(text);
        aida.unlock();
    }
Example #5
0
File: main.cpp Project: shazron/ckb
// Check if the application is running. Optionally write something to its shared memory.
static bool isRunning(const char* command){
    // Try to create shared memory (if successful, application was not already running)
    if(!appShare.create(SHMEM_SIZE) || !appShare.lock()){
        // Lock existing shared memory
        if(!appShare.attach() || !appShare.lock())
            return true;
        bool running = false;
        if(appShare.size() == SHMEM_SIZE_V015){
            // Old shmem - no PID listed so assume the process is running, and print the command directly to the buffer
            if(command){
                void* data = appShare.data();
                snprintf((char*)data, SHMEM_SIZE_V015, "%s", command);
            }
            running = true;
        } else {
            // New shmem. Scan the contents of the shared memory for a PID
            QStringList lines = QString((const char*)appShare.constData()).split("\n");
            if(pidActive(lines)){
                running = true;
                // Append the command
                if(command){
                    lines.append(QString("Option ") + command);
                    QByteArray newMem = lines.join("\n").left(SHMEM_SIZE).toLatin1();
                    // Copy the NUL byte as well as the string
                    memcpy(appShare.data(), newMem.constData(), newMem.length() + 1);
                }
            }
        }
        if(running){
            appShare.unlock();
            return true;
        }
    }
    // Not already running. Initialize the shared memory with our PID
    snprintf((char*)appShare.data(), appShare.size(), "PID %ld", (long)getpid());
    appShare.unlock();
    return false;
}
bool TasDataShare::storeSharedData(const QString& identifier, const TasSharedData& data, QString& errMsg)
{
    QSharedMemory* storage = new QSharedMemory(identifier);
    QByteArray array = data.asArray();
    int size = array.size();
    if(!storage->create(size)){
        delete storage;
        return false;
    }

    storage->lock();
    char *to = (char*)storage->data();
    const char *from = array.data();
    memcpy(to, from, qMin(storage->size(), size));
    storage->unlock();
    mStoredDataBlocks.insert(identifier, storage);
    errMsg = " key:" + storage->key();
    return true;
}
Example #7
0
void setBool(bool value, QString name) {
    QSharedMemory* sharedMemory = boolMemoryMap.value(name);

    if(sharedMemory->isAttached()) {
        sharedMemory->detach();
    }

    int size = sizeof(bool);

    if (!sharedMemory->create(size)) {
        sharedMemory->attach(QSharedMemory::ReadWrite);
    }

    sharedMemory->lock();

    bool *array = (bool*)sharedMemory->data();
    memcpy(array, &value, qMin(sharedMemory->size(), size));

    sharedMemory->unlock();
}
Example #8
0
void setString(const char value[], QString name) {
    QSharedMemory* sharedMemory = stringMemoryMap.value(name);

    if(sharedMemory->isAttached())
        sharedMemory->detach();

    int size = strlen(value) + sizeof(char);

    if (!sharedMemory->create(size)) {
        if (!sharedMemory->isAttached()) {
            sharedMemory->attach(QSharedMemory::ReadWrite);
        }
    }

    sharedMemory->lock();

    char *to = (char*)sharedMemory->data();
    memcpy(to, value, qMin(sharedMemory->size(), size));

    sharedMemory->unlock();
}
Example #9
0
// Example how to get json using shared memory. Not tested :-D
std::pair<bool, QString> json() {

    QSharedMemory sharedMemory;

    if (!sharedMemory.attach()) {
        return std::make_pair<bool, QString>(false, QString());
    }

    QBuffer buffer;
    QDataStream in(&buffer);
    QString json;

    sharedMemory.lock();
    buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
    buffer.open(QBuffer::ReadOnly);
    in >> json;
    sharedMemory.unlock();

    sharedMemory.detach();
    return std::make_pair<bool, QString>(false, QString());
}
Example #10
0
void setInt(int value, QString name) {
    QSharedMemory* sharedMemory = intMemoryMap.value(name);

    if(sharedMemory->isAttached())
        sharedMemory->detach();

    int size = sizeof(int);

    if (!sharedMemory->create(size)) {
        if (!sharedMemory->isAttached()) {
            sharedMemory->attach(QSharedMemory::ReadWrite);
        }
    }

    sharedMemory->lock();

    int* to = (int*)sharedMemory->data();

    memcpy(to, &value, qMin(sharedMemory->size(), size));

    sharedMemory->unlock();
}
Example #11
0
/*!
  Загружает словарь из файла filename в разделяемую память с ключём key.
  */
QSharedMemory *DictionaryManager::loadDictionary(const QString &filename, const QString &key)
{
    QFile fileDictionary(filename);
    QByteArray buffer;
    QSharedMemory *shared;
    if (!fileDictionary.open(QFile::ReadOnly))
        throw Exception(QString("Ошибка чтения файла словаря. Key: %1; file: %2").arg(key).arg(filename));

    buffer = fileDictionary.readAll();
    shared = new QSharedMemory(key);
    if (!shared->create(buffer.size() * 1.2))   // Выделяем память с 20% запасом
        throw Exception(QString("Ошибка выделения памяти под словарь %1. Описание: %2. "
                               "Словарь будет пропущен.")
                           .arg(key)
                           .arg(shared->errorString()));
    shared->lock();
    char *to = (char *)shared->data();
    const char *from = buffer.data();
    memcpy(to, from, qMin(shared->size(), buffer.size()));
    shared->unlock();

    return shared;
}
int
main(int argc, char *argv[])
{
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication a(argc, argv);

    auto startMinimized = false;
    QString uri = "";

    for (auto string : QCoreApplication::arguments()) {
        if (string == "-m" || string == "--minimized")
            startMinimized = true;
        if (string == "-d" || string == "--debug")
            Console();
        if (string.startsWith("ring:")) {
            uri = string;
        }
    }

#ifdef URI_PROTOCOL
    QSharedMemory* shm = new QSharedMemory("RingShm");
    QSystemSemaphore* sem = new QSystemSemaphore("RingSem", 0);

    if (not shm->create(1024)) {
        if (not uri.isEmpty()) {
            shm->attach();
            shm->lock();
            char *to = (char*) shm->data();
            QChar *data = uri.data();
            while (!data->isNull())
            {
                memset(to, data->toLatin1(), 1);
                ++data;
                ++to;
            }
            memset(to, 0, 1); //null terminator
            shm->unlock();
        }
        sem->release();

        delete shm;
        exit(EXIT_SUCCESS);
    }
    //Client listening to shm event
    memset((char*)shm->data(), 0, shm->size());
    ShmClient* shmClient = new ShmClient(shm, sem);
#endif

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(),
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    a.installTranslator(&qtTranslator);

    QTranslator lrcTranslator;
    lrcTranslator.load("share/libringclient/translations/lrc_" + QLocale::system().name());
    a.installTranslator(&lrcTranslator);

    QTranslator mainTranslator;
    mainTranslator.load("share/ring/translations/ring_client_windows_" + QLocale::system().name());
    a.installTranslator(&mainTranslator);

    QFont font;
    font.setFamily("Segoe UI");
    a.setFont(font);

    QFile file(":/stylesheet.css");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        a.setStyleSheet(file.readAll());
        file.close();
    }

    QCoreApplication::setOrganizationName("Savoir-faire Linux");
    QCoreApplication::setOrganizationDomain("ring.cx");
    QCoreApplication::setApplicationName("Ring");

    if (not uri.isEmpty()) {
        startMinimized = false;
        MainWindow::instance().onRingEvent(uri);
    }

    if (not startMinimized)
        MainWindow::instance().show();
    else {
        MainWindow::instance().showMinimized();
        MainWindow::instance().hide();
    }

    MainWindow::instance().createThumbBar();

#ifdef URI_PROTOCOL
    QObject::connect(shmClient, SIGNAL(RingEvent(QString)), &MainWindow::instance(), SLOT(onRingEvent(QString)));

    QObject::connect(&a, &QApplication::aboutToQuit, [&a, &shmClient, &shm, &sem]() {
        shmClient->terminate();
        delete shmClient;
        delete shm;
        delete sem;
    });
#endif

    return a.exec();
}
Example #13
0
int size_jt9_() {return (int)mem_jt9.size();}
Example #14
0
/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();
  localServer = NULL;

  //Initialize connection to LocalServer to know if other process runs.
  {
    QString serverName = QString(TARGET);

    if (!args.isEmpty()) {
      // load into shared memory
      QBuffer buffer;
      buffer.open(QBuffer::ReadWrite);
      QDataStream out(&buffer);
      out << args;
      int size = buffer.size();

      QSharedMemory newArgs;
      newArgs.setKey(serverName + "_newArgs");
      if (newArgs.isAttached()) newArgs.detach();

      if (!newArgs.create(size)) {
        std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:"
                  << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX
        std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
        //No need for windows, as it removes shared segment directly even when crash.
#endif
        newArgs.detach();
        ::exit(EXIT_FAILURE);
      }
      newArgs.lock();
      char *to = (char*)newArgs.data();
      const char *from = buffer.data().data();
      memcpy(to, from, qMin(newArgs.size(), size));
      newArgs.unlock();

      // Connect to the Local Server of the main process to notify it
      // that a new process had been started
      QLocalSocket localSocket;
      localSocket.connectToServer(QString(TARGET));

      std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
      if( localSocket.waitForConnected(100) )
      {
        std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
        localSocket.waitForDisconnected(1000);
        newArgs.detach();
        std::cerr << "Rshare::Rshare Arguments was sended." << std::endl
                  << " To disable it, in Options - General - Misc," << std::endl
                  << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
        ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
      }
      newArgs.detach();
    }
    // No main process exists
    // Or started without arguments
    // So we start a Local Server to listen for connections from new process
    localServer= new QLocalServer();
    QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    updateLocalServer();
  }

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
  if (_args.contains(ARG_LOGFILE))
    _log.open(_args.value(ARG_LOGFILE));
  if (_args.contains(ARG_LOGLEVEL)) {
    _log.setLogLevel(Log::stringToLogLevel(
                      _args.value(ARG_LOGLEVEL)));
    if (!_args.contains(ARG_LOGFILE))
      _log.open(stdout);
  }
  if (!_args.contains(ARG_LOGLEVEL) && 
      !_args.contains(ARG_LOGFILE))
    _log.setLogLevel(Log::Off);

  /* config directory */
  useConfigDir = false;
  if (dir != "")
  {
  	setConfigDirectory(dir);
  }

  /** Initialize support for language translations. */
  //LanguageSupport::initialize();

  resetLanguageAndStyle();

  /* Switch off auto shutdown */
  setQuitOnLastWindowClosed ( false );

	/* Initialize GxsIdDetails */
	GxsIdDetails::initialize();
}