Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
    MainApp a(argc,argv);

    // had to disable this for now on Mac,
    // weird crash deep in Qt leaves shared memory segment dangling
#ifdef Q_OS_WIN
    // http://qt-project.org/doc/qt-5/qtcore-sharedmemory-example.html
    // http://qt-project.org/forums/viewthread/18262/#89444
    sharedMemory.setKey("Blink1ControlShMemKey");
    if( !sharedMemory.create(1) ) {
        qDebug() << "Blink1Control already running";
        QMessageBox::about(0, QString("Blink1Control running"), 
                           "Blink1Control is already running.");
#ifdef Q_OS_WIN
        a.processEvents();  // FIXME: why are different OSes different here?
        return -1;
#else
        return a.exec();
#endif
    }

#endif
   
    MainWindow w;  // this seems messed up, why even use mainwindow?

    // to capture power change (sleep/wake) on Windows
    // (can we move this to osFixes?)
    a.installNativeEventFilter(&w);
    
    return a.exec();
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setOrganizationName(APP_ORG);
    a.setApplicationVersion(APP_VERSION);
    a.setApplicationName(APP_NAME);
    QTranslator translator;
    const QStringList localeDirs({QString("%1/languages").arg(QDir::currentPath()),
                                  QString(qApp->applicationDirPath() + "/languages"),
                                  QString("/usr/share/%1/languages").arg(APP_NAME),
                                  QString("/usr/local/share/%1/languages").arg(APP_NAME),
                                  QString(QDir::home().absolutePath() + "/.local/share/%1/languages").arg(APP_NAME),
                                  QString(QDir::currentPath().left(QDir::currentPath().lastIndexOf("/")) + "/share/%1/languages").arg(APP_NAME)});
    const QString langFile(qApp->applicationName());
    foreach(const QString &dir, localeDirs){
        if (translator.load(QLocale::system(),langFile, "_", dir )) {
            qApp->installTranslator(&translator);
            break;
        }
    }
    QApplication::setQuitOnLastWindowClosed(false);
    PopupWindow w;
    w.hide();
    QSharedMemory sharedMemory;
    sharedMemory.setKey("QtAlsaVolume");
    if (sharedMemory.attach()) {
        return 0;
    }
    if (!sharedMemory.create(1)) {
        return 0;
    }
    else{
        return a.exec();
    }
}
Ejemplo n.º 3
0
int readonly_segfault()
{
    QSharedMemory sharedMemory;
    sharedMemory.setKey("readonly_segfault");
    sharedMemory.create(1024, QSharedMemory::ReadOnly);
    sharedMemory.lock();
    set(sharedMemory, 0, 'a');
    sharedMemory.unlock();
    return EXIT_SUCCESS;
}
Ejemplo n.º 4
0
static QSharedMemory *createSharedMemory(qint32 key, int byteCount)
{
    QSharedMemory *sharedMemory = new QSharedMemory(QString(valueKeyTemplateString).arg(key));

    bool sharedMemoryIsCreated = sharedMemory->create(byteCount);
    if (!sharedMemoryIsCreated) {
        if (sharedMemory->isAttached())
            sharedMemory->attach();
        sharedMemory->detach();
        sharedMemoryIsCreated = sharedMemory->create(byteCount);
    }

    if (sharedMemoryIsCreated) {
        globalSharedMemoryCache.insert(key, sharedMemory);
        return sharedMemory;
    }

    return 0;
}
Ejemplo n.º 5
0
Archivo: main.cpp Proyecto: chocoop/ckb
bool isRunning(){
    if(!appShare.create(16)){
        if(!appShare.attach() || !appShare.lock())
            return false;
        void* data = appShare.data();
        snprintf((char*)data, 16, "Open");
        appShare.unlock();
        return true;
    }
    return false;
}
Ejemplo n.º 6
0
void conflict_core::openAida(){
    aida.setKey("AIDA64_SensorValues");
    if (aida.isAttached()){
          aida.detach();
    }
    if (!aida.create(10000)){
        conflict.aidaOpen = false;
    }else{
        conflict.aidaOpen = true;
    }
}
Ejemplo n.º 7
0
static mydsp *create_shared_dsp(){
  QString key = "radium_crashreporter_" + QString::number(QDateTime::currentMSecsSinceEpoch());
  QSharedMemory *shared = new QSharedMemory(key);

  if(shared->create(sizeof(mydsp))==false){
    fprintf(stderr,"COMPRESSOR_create_shared: Couldn't create... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data());
    return NULL;
  }

  void *memory = shared->data();

  mydsp *dsp = new(memory) mydsp();

#if 0
  printf("memory: %p, shared: %p\n",memory,shared);
  dsp->key = key;
  dsp->shared = shared;
#endif

  //printf("system: %d\n",system(QString(QString("xterm -e gdb /home/kjetil/radium_compressor/radium_compressor --args --ladspa-slave ")+key).toAscii()));
  printf("system: %d\n",system(QString(QString("xterm -e gdb --args /home/kjetil/radium_compressor/radium_compressor  --ladspa-slave ")+key+" &").toAscii()));


  return dsp;

#if 0
  if(fork()!=0){

    return dsp;

  }else{

    QSharedMemory *shared = new QSharedMemory(key);

    if(shared->attach()==false){
      fprintf(stderr,"Ladspa compressor: Couldn't attach... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data());
      exit(0);
    }

    char *argv[1]={(char*)"radium_compressor"};

    mydsp *dsp          = (mydsp*)shared->data();
    fprintf(stderr,"dsp: %p.\n",dsp);
    portData* port_data = new portData(dsp->getNumInputs(), dsp->getNumOutputs());
    dsp->buildUserInterface(port_data); // This is the second time buildUserInterface is called twice on the dsp data. One time in each process.

    start_program(1,argv,new PLUGIN(0, port_data, dsp));

    exit(0);
    return NULL;
  }
#endif
}
Ejemplo n.º 8
0
int SingleApp(){//TODO:problem.
    int ret = 1;
    QSharedMemory sharedMemory;
    sharedMemory.setKey("FishProjectApp");
//    if (sharedMemory.create(1) && sharedMemory.error() != QSharedMemory::AlreadyExists)
    if(sharedMemory.attach())
    {
        qDebug()<<"single";
        return 0;
    }
    sharedMemory.create(1);
    qDebug()<<"create";
    return ret;
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
    qRegisterMetaTypeStreamOperators<SQProfile>("SQProfile");

    QApplication a(argc, argv);

    signal(SIGINT, onSIGINT_TERM);
    signal(SIGTERM, onSIGINT_TERM);

    a.setApplicationName(QString("shadowsocks-qt5"));
    a.setApplicationDisplayName(QString("Shadowsocks-Qt5"));
    a.setApplicationVersion(APP_VERSION);

#ifdef Q_OS_WIN
    if (QLocale::system().country() == QLocale::China) {
        a.setFont(QFont("Microsoft Yahei", 9, QFont::Normal, false));
    }
    else {
        a.setFont(QFont("Segoe UI", 9, QFont::Normal, false));
    }
    QIcon::setThemeName("Breeze");
#endif

    QTranslator ssqt5t;
    ssqt5t.load(QLocale::system(), "ss-qt5", "_", ":/i18n");
    a.installTranslator(&ssqt5t);

    MainWindow w;
    QSharedMemory sharedMem;
    sharedMem.setKey("Shadowsocks-Qt5");
    if (w.isOnlyOneInstance()) {
        if (!sharedMem.create(1)) {
            QMessageBox::critical(&w, QObject::tr("Error"), QObject::tr("Another instance of Shadowsocks-Qt5 is already running."));
            return -1;
        }
    }
    w.show();
    if (w.isHideWindowOnStartup()) {
        if (w.isUsingAppIndicator()) {
            QTimer::singleShot(5, &w, SLOT(minimizeToSysTray()));
        } else {
            w.minimizeToSysTray();
        }
    }

    return a.exec();
}
Ejemplo n.º 10
0
void *COMPRESSOR_create_shared(float sample_rate){
  QString key = "radium_crashreporter_" + QString::number(QDateTime::currentMSecsSinceEpoch());
  QSharedMemory *shared = new QSharedMemory(key);
  if(shared->create(sizeof(Compressor_wrapper))==false){
    fprintf(stderr,"COMPRESSOR_create_shared: Couldn't create... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data());
    return NULL;
  }

  void *memory = shared->data();

  Compressor_wrapper *wrapper = new(memory) Compressor_wrapper(sample_rate);
  printf("memory: %p, shared: %p\n",memory,shared);
  wrapper->key = key;
  wrapper->shared = shared;
  
  return wrapper;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QCoreApplication::setOrganizationName("Scary HalloSoft");
    QCoreApplication::setOrganizationDomain("hallosoft.de");
    QCoreApplication::setApplicationName("Hallos Inspection Tool");

    // Version
    QString versionString = QString("%1.%2.%3.%4").arg(VERSION_MAJOR).arg(VERSION_MINOR).arg(VERSION_REVISION).arg(VERSION_BUILD);
    a.setApplicationVersion(versionString);

    qDebug() << "Version" << versionString;

    // splash screen
    QPixmap splashPixmap(":/pic/icons/Slpash.png");
    Q_ASSERT(!splashPixmap.isNull());


    QSharedMemory sharedMemory;
    sharedMemory.setKey("HallosInspectionTool");

    if (!sharedMemory.create(1))
    {
        qDebug() << "Shared memory:" << sharedMemory.errorString();

        QMessageBox::warning(0,
                             QApplication::tr("Warning!"),
                             QApplication::tr("An instance of HIT is running!") );

        exit(0); // Exit, a process is already running
    }

    QSplashScreen splash(splashPixmap);
    splash.show();
    qApp->processEvents();
    splash.showMessage(QString("Version %1").arg(versionString), Qt::AlignBottom);
    qApp->processEvents();

    MainWindow w;
    w.show();

    splash.finish(&w);

    return a.exec();
}
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;
}
Ejemplo n.º 13
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();
}
Ejemplo n.º 14
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();
}
Ejemplo n.º 15
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();
}
Ejemplo n.º 16
0
Archivo: main.cpp Proyecto: 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;
}
Ejemplo n.º 17
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;
}
Ejemplo n.º 18
0
bool Application::isRunning()
{
    bool running = BaseApplication::isRunning();
    QSharedMemory *sharedMem = new QSharedMemory(id() + QLatin1String("-shared-memory-key"), this);
    if (!running) {
        // First instance creates shared memory and store PID
        if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock()) {
            *(static_cast<DWORD*>(sharedMem->data())) = ::GetCurrentProcessId();
            sharedMem->unlock();
        }
    }
    else {
        // Later instances attach to shared memory and retrieve PID
        if (sharedMem->attach() && sharedMem->lock()) {
            ::AllowSetForegroundWindow(*(static_cast<DWORD*>(sharedMem->data())));
            sharedMem->unlock();
        }
    }

    if (!sharedMem->isAttached())
        qWarning() << "Failed to initialize shared memory: " << sharedMem->errorString();

    return running;
}
Ejemplo n.º 19
0
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();
}
Ejemplo n.º 20
0
bool create_jt9_(int nsize) {return mem_jt9.create(nsize);}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //Check if another instance has been started already
    QSharedMemory sharedMemory;
    sharedMemory.setKey("neu");

    if (!sharedMemory.create(1))
    {
        QMessageBox::warning(nullptr, QObject::tr("Warning!"), QObject::tr("An instance of this application is running!"));
        exit(0); // Exit process immediately
    }

    QSettings settings("neuPlayer.ini", QSettings::IniFormat);

    // Init Trad engine
    QString locale = QLocale::system().name().section('_', 0, 0);
    QTranslator translator;
    //Load correct translation based on system locale
    translator.load("neuplayer_" + locale);
    a.installTranslator(&translator);
    //Setup actual window
    qApp->setStyle(QStyleFactory::create("Fusion")); //base theme fusion

    if(settings.value("skin", 1).toInt() == 1 || settings.value("skin", 1).toInt() == 3)
    {
        Skin HoloFusion(1, nullptr);
        HoloFusion.load();
    }

    else
    {
        Skin CleanFusion(0, nullptr);
        CleanFusion.load();
    }
    //Ready to show
    //Create the helper so it isn't destroyed right away
    NcFramelessHelper helper(nullptr);
    QFile fileHandler(".configdone"); //So you config before anything else
    if(!fileHandler.exists()) //If there is the config to do, the config will launch the app when done
    {
        QPointer <InitialConfig> config = new InitialConfig();
        config->show();
    }
    else
    {
        Player *neuPlayer = new Player(nullptr);
        if(settings.value("Additional_Features/framelessWindow", false).toBool())
        {
            if(settings.value("visibilite").toBool())
                helper.activateOn(neuPlayer, true);
            else
                helper.activateOn(neuPlayer);
        }
        neuPlayer->show();
    }
    fileHandler.close();

    return a.exec();
}
Ejemplo n.º 22
0
int producer()
{
    QSharedMemory producer;
    producer.setKey("market");

    int size = 1024;
    if (!producer.create(size)) {
        if (producer.error() == QSharedMemory::AlreadyExists) {
            if (!producer.attach()) {
                qWarning() << "Could not attach to" << producer.key();
                return EXIT_FAILURE;
            }
        } else {
            qWarning() << "Could not create" << producer.key();
            return EXIT_FAILURE;
        }
    }
    // tell parent we're ready
    //qDebug("producer created and attached");
    puts("");
    fflush(stdout);

    if (!producer.lock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }
    set(producer, 0, 'Q');
    if (!producer.unlock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }

    int i = 0;
    while (i < 5) {
        if (!producer.lock()) {
            qWarning() << "Could not lock" << producer.key();
            return EXIT_FAILURE;
        }
        if (get(producer, 0) == 'Q') {
            if (!producer.unlock()) {
                qWarning() << "Could not unlock" << producer.key();
                return EXIT_FAILURE;
            }
            QTest::qSleep(1);
            continue;
        }
        //qDebug() << "producer:" << i);
        ++i;
        set(producer, 0, 'Q');
        if (!producer.unlock()) {
            qWarning() << "Could not unlock" << producer.key();
            return EXIT_FAILURE;
        }
        QTest::qSleep(1);
    }
    if (!producer.lock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }
    set(producer, 0, 'E');
    if (!producer.unlock()) {
        qWarning() << "Could not unlock" << producer.key();
        return EXIT_FAILURE;
    }

    //qDebug("producer done");

    // Sleep for a bit to let all consumers exit
    getchar();
    return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
int main(int argc, const char* argv[]) {
    disableQtBearerPoll(); // Fixes wifi ping spikes
    
    QString applicationName = "High Fidelity Interface - " + qgetenv("USERNAME");

    bool instanceMightBeRunning = true;

#ifdef Q_OS_WIN
    // Try to create a shared memory block - if it can't be created, there is an instance of
    // interface already running. We only do this on Windows for now because of the potential
    // for crashed instances to leave behind shared memory instances on unix.
    QSharedMemory sharedMemory { applicationName };
    instanceMightBeRunning = !sharedMemory.create(1, QSharedMemory::ReadOnly);
#endif

    if (instanceMightBeRunning) {
        // Try to connect and send message to existing interface instance
        QLocalSocket socket;

        socket.connectToServer(applicationName);

        static const int LOCAL_SERVER_TIMEOUT_MS = 500;

        // Try to connect - if we can't connect, interface has probably just gone down
        if (socket.waitForConnected(LOCAL_SERVER_TIMEOUT_MS)) {

            QStringList arguments;
            for (int i = 0; i < argc; ++i) {
                arguments << argv[i];
            }

            QCommandLineParser parser;
            QCommandLineOption urlOption("url", "", "value");
            parser.addOption(urlOption);
            parser.process(arguments);

            if (parser.isSet(urlOption)) {
                QUrl url = QUrl(parser.value(urlOption));
                if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) {
                    qDebug() << "Writing URL to local socket";
                    socket.write(url.toString().toUtf8());
                    if (!socket.waitForBytesWritten(5000)) {
                        qDebug() << "Error writing URL to local socket";
                    }
                }
            }

            socket.close();

            qDebug() << "Interface instance appears to be running, exiting";

            return EXIT_SUCCESS;
        }

#ifdef Q_OS_WIN
        return EXIT_SUCCESS;
#endif
    }

    // Check OpenGL version.
    // This is done separately from the main Application so that start-up and shut-down logic within the main Application is
    // not made more complicated than it already is.
    {
        OpenGLVersionChecker openGLVersionChecker(argc, const_cast<char**>(argv));
        if (!openGLVersionChecker.isValidVersion()) {
            qCDebug(interfaceapp, "Early exit due to OpenGL version.");
            return 0;
        }
    }

    QElapsedTimer startupTime;
    startupTime.start();

    // Debug option to demonstrate that the client's local time does not
    // need to be in sync with any other network node. This forces clock
    // skew for the individual client
    const char* CLOCK_SKEW = "--clockSkew";
    const char* clockSkewOption = getCmdOption(argc, argv, CLOCK_SKEW);
    if (clockSkewOption) {
        int clockSkew = atoi(clockSkewOption);
        usecTimestampNowForceClockSkew(clockSkew);
        qCDebug(interfaceapp, "clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew);
    }

    // Oculus initialization MUST PRECEDE OpenGL context creation.
    // The nature of the Application constructor means this has to be either here,
    // or in the main window ctor, before GL startup.
    Application::initPlugins();

    int exitCode;
    {
        QSettings::setDefaultFormat(QSettings::IniFormat);
        Application app(argc, const_cast<char**>(argv), startupTime);

        // Setup local server
        QLocalServer server { &app };

        // We failed to connect to a local server, so we remove any existing servers.
        server.removeServer(applicationName);
        server.listen(applicationName);

        QObject::connect(&server, &QLocalServer::newConnection, &app, &Application::handleLocalServerConnection);

        QTranslator translator;
        translator.load("i18n/interface_en");
        app.installTranslator(&translator);

        qCDebug(interfaceapp, "Created QT Application.");
        exitCode = app.exec();
        server.close();
    }

    Application::shutdownPlugins();

    qCDebug(interfaceapp, "Normal exit.");
    return exitCode;
}
Ejemplo n.º 24
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();
}