Example #1
0
void Tserial_event::run(void)
{
    bool          done;
    long          status;
    unsigned long read_nbr, result_nbr;
    char          success;

    ready                   = true;
    done                    = false;
    tx_in_progress          = 0;
    rx_in_progress          = 0;
    WaitCommEventInProgress = 0;

    if (manager!=0)
        manager((t_uint32) this, SERIAL_CONNECTED);

    GetLastError();               // just to clear any pending error
    SetEvent(serial_events[SIG_READ_DONE]);
    if (check_modem)
        SetEvent(serial_events[SIG_MODEM_CHECKED]);

    /* ----------------------------------------------------------- */
    while(!done)
    {
        /* ------------------------------------------------------------------ */
        /*                                                                    */
        /*                                                                    */
        /*                                                                    */
        /*                          Waiting  for signals                      */
        /*                                                                    */
        /*                                                                    */
        /*                                                                    */
        /* ------------------------------------------------------------------ */
        // Main wait function. Waiting for something to happen.
        // This may be either the completion of a Read or a Write or
        // the reception of modem events, Power Down, new Tx
        //
        status = WaitForMultipleObjects(SERIAL_SIGNAL_NBR, serial_events,
                                        FALSE, INFINITE);

        // processing answer to filter other failures
        status = status - WAIT_OBJECT_0;
        if ((status<0) || (status>=SERIAL_SIGNAL_NBR))
            done=true;   // error
        else
        {
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++ EVENT DISPATCHER ++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            switch(status)
            {
                /* ######################################################## */
                case SIG_POWER_DOWN:
                    // receiving a POWER down signal. Stopping the thread
                    done = true;
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                       RX                             # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_READ_DONE:
                    // previous reading is finished
                    // I start a new one here
                    if (!rx_in_progress)
                    {
                        // locking reading
                        rx_in_progress = 1;
                        // starting a new read
                        success = (char) ReadFile(serial_handle,&rxBuffer,
                                         max_rx_size,&read_nbr,&ovReader);
                        if (!success)
                        {
                            // failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("Readfile error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("ReadFile pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("ReadFile immediate success\n");
                        }
                        #endif
                    }
                    break;
                /* ######################################################## */
                case SIG_READER:
                    // reading the result of the terminated read
                    //BOOL GetOverlappedResult(
                    //    HANDLE hFile,	// handle of file, pipe, or communications device
                    //    LPOVERLAPPED lpOverlapped,	// address of overlapped structure
                    //    LPDWORD lpNumberOfBytesTransferred,	// address of actual bytes count
                    //    BOOL bWait 	// wait flag
                    //   );
                    //
                    if (GetOverlappedResult(serial_handle, &ovReader,
                        &result_nbr, FALSE))
                    {
                        #ifdef DEBUG_EVENTS
                            printf("ReadFile => GetOverlappedResult done\n");
                        #endif DEBUG_EVENTS
                        // no error => OK
                        // Read operation completed successfully
                        ResetEvent(serial_events[SIG_READER]);
                        // Write operation completed successfully
                        received_size  = result_nbr;
                        rx_in_progress = 0; // read has ended
                        // if incoming data, I process them
                        if ((result_nbr!=0) &&(manager!=0))
                            manager((t_uint32) this, SERIAL_DATA_ARRIVAL);
                        // I automatically restart a new read once the
                        // previous is completed.
                        //SetEvent(serial_events[SIG_READ_DONE]);
                        // BUG CORRECTION 02.06.22
                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError()!= ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                       TX                             # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_DATA_TO_TX:
                    // Signal asserted that there is a new valid message
                    // in the "txBuffer" variable
                    // sending data to the port
                    success = (char) WriteFile(serial_handle, (unsigned char*)txBuffer, tx_size,
                                        &result_nbr, &ovWriter);
                        if (!success)
                        {
                            // ouups, failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("WriteFile error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("WriteFile pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("WriteFile immediate success\n");
                        }
                        #endif
                    break;
                /* ######################################################## */
                case SIG_WRITER:
                    // WriteFile has terminated
                    // checking the result of the operation
                    if (GetOverlappedResult(serial_handle, &ovWriter,
                        &result_nbr, FALSE))
                    {
                        // Write operation completed successfully
                        //printf("Write operation completed successfully\n");
                        ResetEvent(serial_events[SIG_WRITER]);
                        // further write are now allowed
                        tx_in_progress = 0;
                        // telling it to the manager
                        if (manager!=0)
                            manager((t_uint32) this, SERIAL_DATA_SENT);
                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError() != ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                    MODEM_EVENTS EVENTS                      # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_MODEM_CHECKED:
                    if ((!WaitCommEventInProgress) && check_modem)
                    // if no wait is in progress I start a new one
                    {            
                        WaitCommEventInProgress=1;
                        success = (char) WaitCommEvent(serial_handle,&dwCommEvent,
                                                       &ovWaitEvent);
                        // reading one byte only to have immediate answer on each byte
                        if (!success)
                        {
                            // ouups, failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("WaitCommEvent error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("WaitCommEvent pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("WaitCommEvent immediate success\n");
                        }
                        #endif
                    }
                    break;
                /* ######################################################## */
                case SIG_MODEM_EVENTS:
                    // reading the result of the terminated wait
                    if (GetOverlappedResult(serial_handle, &ovWaitEvent,
                        &result_nbr, FALSE))
                    {
                        // Wait operation completed successfully
                        ResetEvent(serial_events[SIG_MODEM_EVENTS]);
                        WaitCommEventInProgress = 0;
                        // if incoming data, I process them
                        OnEvent(dwCommEvent);
                        // automatically starting a new check
                        SetEvent(serial_events[SIG_MODEM_CHECKED]);
                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError() != ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
            }
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
        }
    };

    // --------------------- Disconnecting ----------------
    ready = false;
    if (serial_handle!=INVALID_HANDLE_VALUE)
        CloseHandle(serial_handle);
    serial_handle = INVALID_HANDLE_VALUE;

    if (manager!=0)
        manager((t_uint32) this, SERIAL_DISCONNECTED);
}
Example #2
0
void Msg::incomingUser(const QString& login) {
    if(manager()->databasePlugin()->isRegisteredUser(login))
        showmsgCmd(login,QStringList("showmsg"));
}
Example #3
0
void Msg::killedUser(const QString& login) {
    QFile f(manager()->dataDir() + "/msg/" + login);
    f.remove();
}
Example #4
0
QDBusConnection::QDBusConnection(const QString &name)
{
    d = manager()->connection(name);
    if (d)
        d->ref.ref();
}
Example #5
0
void Msg::subscribeCmd(const QString& from, const QStringList& list) {
    writeMsg(list[0],from);
    QString txt("You subscribed to list " + list[0]);
    manager()->connectionPlugin()->serverSend(from,txt);
}
Example #6
0
File: init.c Project: 8l/akaros
void kernel_init(multiboot_info_t *mboot_info)
{
	extern char edata[], end[];

	memset(edata, 0, end - edata);
	/* mboot_info is a physical address.  while some arches currently have the
	 * lower memory mapped, everyone should have it mapped at kernbase by now.
	 * also, it might be in 'free' memory, so once we start dynamically using
	 * memory, we may clobber it. */
	multiboot_kaddr = (struct multiboot_info*)((physaddr_t)mboot_info
                                               + KERNBASE);
	extract_multiboot_cmdline(multiboot_kaddr);

	cons_init();
	print_cpuinfo();

	printk("Boot Command Line: '%s'\n", boot_cmdline);

	exception_table_init();
	cache_init();					// Determine systems's cache properties
	pmem_init(multiboot_kaddr);
	kmem_cache_init();              // Sets up slab allocator
	kmalloc_init();
	hashtable_init();
	radix_init();
	cache_color_alloc_init();       // Inits data structs
	colored_page_alloc_init();      // Allocates colors for agnostic processes
	acpiinit();
	topology_init();
	kthread_init();					/* might need to tweak when this happens */
	vmr_init();
	file_init();
	page_check();
	idt_init();
	kernel_msg_init();
	timer_init();
	vfs_init();
	devfs_init();
	train_timing();
	kb_buf_init(&cons_buf);
	arch_init();
	block_init();
	enable_irq();
	run_linker_funcs();
	/* reset/init devtab after linker funcs 3 and 4.  these run NIC and medium
	 * pre-inits, which need to happen before devether. */
	devtabreset();
	devtabinit();

#ifdef CONFIG_EXT2FS
	mount_fs(&ext2_fs_type, "/dev/ramdisk", "/mnt", 0);
#endif /* CONFIG_EXT2FS */
#ifdef CONFIG_ETH_AUDIO
	eth_audio_init();
#endif /* CONFIG_ETH_AUDIO */
	get_coreboot_info(&sysinfo);
	booting = 0;

#ifdef CONFIG_RUN_INIT_SCRIPT
	if (run_init_script()) {
		printk("Configured to run init script, but no script specified!\n");
		manager();
	}
#else
	manager();
#endif
}
Example #7
0
void ClearCookies::start()
{
  manager()->cookieJar()->clearCookies();
  finish(true);
}
Example #8
0
void TextEncoding::add(TextEncoding::Ptr pEncoding)
{
	manager().add(pEncoding, pEncoding->canonicalName());
}
Example #9
0
void TextEncoding::add(TextEncoding::Ptr pEncoding, const std::string& name)
{
	manager().add(pEncoding, name);
}
Example #10
0
int main(int argc, char  *argv[])
{
    QCoreApplication application(argc, argv);

    const QStringList &args(application.arguments());

    const bool quickMode(args.contains(QStringLiteral("-q")) || args.contains(QStringLiteral("--quick")));

    QMap<QString, QString> parameters;
    parameters.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false"));

    QContactManager manager(QString::fromLatin1("org.nemomobile.contacts.sqlite"), parameters);

    QContactFetchRequest request;
    request.setManager(&manager);

    // Perform an initial request to ensure the database has been created before we start timing
    request.start();
    request.waitForFinished();

    qint64 elapsedTimeTotal = 0;

    QElapsedTimer asyncTotalTimer;
    asyncTotalTimer.start();

    // Fetch all, no optimization hints
    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Skip relationships
    QContactFetchHint hint;
    hint.setOptimizationHints(QContactFetchHint::NoRelationships);
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Reduce data access
    hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type);
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Reduce number of results
    hint.setMaxCountHint(request.contacts().count() / 8);
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Max count fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }
    qint64 asyncTotalElapsed = asyncTotalTimer.elapsed();



    // Time some synchronous operations.  First, generate the test data.
    qsrand((int)asyncTotalElapsed);
    QList<int> nbrContacts;
    if (quickMode) {
        nbrContacts << 200;
    } else {
        nbrContacts << 10 << 100 << 500 << 1000 << 2000;
    }
    QList<QList<QContact> > testData;
    qDebug() << "\n\nGenerating test data for timings...";
    for (int i = 0; i < nbrContacts.size(); ++i) {
        int howMany = nbrContacts.at(i);
        QList<QContact> newTestData;
        newTestData.reserve(howMany);

        for (int j = 0; j < howMany; ++j) {
            // Use testing sync target, so 'local' won't be modified into 'was_local' via aggregation
            newTestData.append(generateContact(QString::fromLatin1("testing")));
        }

        testData.append(newTestData);
    }


    // Perform the timings - these all create new contacts and assume an "empty" initial database
    QElapsedTimer syncTimer;
    for (int i = 0; i < testData.size(); ++i) {
        QList<QContact> td = testData.at(i);
        qint64 ste = 0;
        qDebug() << "Performing tests for" << td.size() << "contacts:";

        syncTimer.start();
        manager.saveContacts(&td);
        ste = syncTimer.elapsed();
        qDebug() << "    saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactDetailFilter testingFilter;
        testingFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget);
        testingFilter.setValue(QString::fromLatin1("testing"));

        QContactFetchHint fh;
        syncTimer.start();
        QList<QContact> readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type
                << QContactPhoneNumber::Type << QContactEmailAddress::Type);
        syncTimer.start();
        readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all, common details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        fh.setOptimizationHints(QContactFetchHint::NoRelationships);
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
        syncTimer.start();
        readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all, no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type);
        syncTimer.start();
        readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        // Read the contacts, selected by ID
        QList<QContactId> idsToRetrieve;
        for (int j = 0; j < td.size(); ++j) {
            idsToRetrieve.append(retrievalId(td.at(j)));
        }

        syncTimer.start();
        readContacts = manager.contacts(idsToRetrieve, fh, 0);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all by IDs, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        // Read the same set using ID filtering
        QContactIdFilter idFilter;
        idFilter.setIds(idsToRetrieve);

        syncTimer.start();
        readContacts = manager.contacts(idFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != td.size()) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size();
        }
        qDebug() << "    reading all by ID filter, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        // Read the same set, but filter everything out using syncTarget
        QContactDetailFilter aggregateFilter;
        aggregateFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget);
        aggregateFilter.setValue(QString::fromLatin1("aggregate"));

        syncTimer.start();
        readContacts = manager.contacts(idFilter & aggregateFilter, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        if (readContacts.size() != 0) {
            qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << 0;
        }
        qDebug() << "    reading all by ID filter & aggregate, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactDetailFilter firstNameStartsA;
        firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName);
        firstNameStartsA.setValue("A");
        firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith);
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
        syncTimer.start();
        readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QList<QContactId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(retrievalId(td.at(j)));
        }

        syncTimer.start();
        manager.removeContacts(idsToRemove);
        ste = syncTimer.elapsed();
        qDebug() << "    removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;
    }

    // these tests are slightly different to those above.  They operate on much smaller
    // batches, but occur after the database has already been prefilled with some data.
    QList<int> smallerNbrContacts;
    if (quickMode) {
        smallerNbrContacts << 20;
    } else {
        smallerNbrContacts << 1 << 2 << 5 << 10 << 20 << 50;
    }
    QList<QList<QContact> > smallerTestData;
    qDebug() << "\n\nGenerating smaller test data for prefilled timings...";
    for (int i = 0; i < smallerNbrContacts.size(); ++i) {
        int howMany = smallerNbrContacts.at(i);
        QList<QContact> newTestData;
        newTestData.reserve(howMany);

        for (int j = 0; j < howMany; ++j) {
            newTestData.append(generateContact());
        }

        smallerTestData.append(newTestData);
    }

    // prefill the database
    QList<QContact> prefillData;
    for (int i = 0; i < testData.size() && testData.at(i).size() < 1001; ++i) {
        prefillData = testData.at(i);
    }
    qDebug() << "Prefilling database with" << prefillData.size() << "contacts... this will take a while...";
    manager.saveContacts(&prefillData);
    qDebug() << "Now performing timings (shouldn't get aggregated)...";
    for (int i = 0; i < smallerTestData.size(); ++i) {
        QList<QContact> td = smallerTestData.at(i);
        qint64 ste = 0;
        qDebug() << "Performing tests for" << td.size() << "contacts:";

        syncTimer.start();
        manager.saveContacts(&td);
        ste = syncTimer.elapsed();
        qDebug() << "    saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactFetchHint fh;
        syncTimer.start();
        QList<QContact> readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type
                << QContactPhoneNumber::Type << QContactEmailAddress::Type);
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, common details, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        fh.setOptimizationHints(QContactFetchHint::NoRelationships);
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, no relationships, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type);
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, display details + no rels, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        QContactDetailFilter firstNameStartsA;
        firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName);
        firstNameStartsA.setValue("A");
        firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith);
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
        syncTimer.start();
        readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        QList<QContactId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(retrievalId(td.at(j)));
        }

        syncTimer.start();
        manager.removeContacts(idsToRemove);
        ste = syncTimer.elapsed();
        qDebug() << "    removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;
    }

    // The next test is about saving contacts which should get aggregated into others.
    // Aggregation is an expensive operation, so we expect these save operations to take longer.
    qDebug() << "\n\nPerforming aggregation tests";
    QList<QContact> contactsToAggregate;
    for (int i = 0; i < 100; ++i) {
        QContact existingContact = prefillData.at(prefillData.size() - 1 - i);
        QContact contactToAggregate;
        QContactSyncTarget newSyncTarget;
        newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation")));
        QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated
        QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc.
        newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i));
        contactToAggregate.saveDetail(&newSyncTarget);
        contactToAggregate.saveDetail(&aggName);
        contactToAggregate.saveDetail(&newOnlineAcct);
        contactsToAggregate.append(contactToAggregate);
    }

    syncTimer.start();
    manager.saveContacts(&contactsToAggregate);
    qint64 aggregationElapsed = syncTimer.elapsed();
    int totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed
             << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )";
    elapsedTimeTotal += aggregationElapsed;

    // Now perform the test again, this time with more aggregates, to test nonlinearity.
    contactsToAggregate.clear();
    const int high = prefillData.size() / 2, low = high / 2;
    for (int i = low; i < high; ++i) {
        QContact existingContact = prefillData.at(prefillData.size() - 1 - i);
        QContact contactToAggregate;
        QContactSyncTarget newSyncTarget;
        newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation")));
        QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated
        QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc.
        newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i));
        contactToAggregate.saveDetail(&newSyncTarget);
        contactToAggregate.saveDetail(&aggName);
        contactToAggregate.saveDetail(&newOnlineAcct);
        contactsToAggregate.append(contactToAggregate);
    }

    syncTimer.start();
    manager.saveContacts(&contactsToAggregate);
    aggregationElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed
             << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )";
    elapsedTimeTotal += aggregationElapsed;


    // The next test is about updating existing contacts, amongst a large set.
    // We're especially interested in presence updates, as these are common.
    qDebug() << "\n\nPerforming presence update tests:";

    // in the first presence update test, we update a small number of contacts.
    QStringList presenceAvatars = generateAvatarsList();
    QList<QContact> contactsToUpdate;
    for (int i = 0; i < 10; ++i) {
        contactsToUpdate.append(prefillData.at(prefillData.size() - 1 - i));
    }

    // modify the presence, nickname and avatar of the test data
    for (int j = 0; j < contactsToUpdate.size(); ++j) {
        QString genstr = QString::number(j);
        QContact curr = contactsToUpdate[j];
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(QDateTime::currentDateTime());
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>(qrand() % 4));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.replace(j, curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    qint64 presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // in the second presence update test, we update ALL of the contacts
    // This simulates having a large number of contacts from a single source (eg, a social network)
    // where (due to changed connectivity status) presence updates for the entire set become available.
    contactsToUpdate.clear();
    QDateTime timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < prefillData.size(); ++j) {
        QContact curr = prefillData.at(j);
        QString genstr = QString::number(j) + "2";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the third presence update test is identical to the previous, but with 2000 prefilled contacts in database.
    qDebug() << "    Adding more prefill data, please wait...";
    QList<QContact> morePrefillData;
    for (int i = 0; i < contactsToUpdate.size(); ++i) {
        morePrefillData.append(generateContact(QString::fromLatin1("testing")));
    }
    manager.saveContacts(&morePrefillData);

    // now do the updates and save.
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < prefillData.size(); ++j) {
        QContact curr = prefillData.at(j);
        QString genstr = QString::number(j) + "3";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "3";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
    QList<QContactId> morePrefillIds;
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(retrievalId(morePrefillData.at(j)));
    }

    manager.removeContacts(morePrefillIds);

    // the fourth presence update test checks update time for non-overlapping sets of data.
    qDebug() << "    generating non-overlapping / aggregated prefill data, please wait...";
    morePrefillData.clear();
    for (int i = 0; i < prefillData.size(); ++i) {
        morePrefillData.append(generateContact("test-presence-4", false)); // false = don't aggregate.
    }
    manager.saveContacts(&morePrefillData);

    // now do the update
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "4";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, no overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).id());
    }
    manager.removeContacts(morePrefillIds);

    // the fifth presence update test is similar to the above except that half of
    // the extra contacts have a (high) chance of being aggregated into an existing contact.
    // So, database should have 2000 constituents, 1000 from "local", 1000 from "test-presence-5"
    // with 1500 aggregates (about 500 of test-presence-5 contacts will share an aggregate with
    // a local contact).  TODO: check what happens if multiple aggregates for local contacts
    // could possibly match a given test-presence-5 contact (which is possible, since the backend
    // never aggregates two contacts from the same sync source...)
    qDebug() << "    generating partially-overlapping / aggregated prefill data, please wait...";
    morePrefillData.clear();
    for (int i = 0; i < prefillData.size(); ++i) {
        if (i < (prefillData.size() / 2)) {
            morePrefillData.append(generateContact("test-presence-5", false)); // false = don't aggregate.
        } else {
            morePrefillData.append(generateContact("test-presence-5", true));  // true = possibly aggregate.
        }
    }
    manager.saveContacts(&morePrefillData);

    // now do the update
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "5";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the sixth presence update test is identical to the fifth test, except that we ONLY
    // update the presence status (not nickname or avatar).
    morePrefillData = contactsToUpdate;
    contactsToUpdate.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QContactPresence cp = curr.detail<QContactPresence>();
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        curr.saveDetail(&cp);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the seventh presence update test is identical to the 6th test, except that
    // we also pass a "detail type mask" to the update.  This allows the backend
    // to perform optimisation based upon which details are modified.
    morePrefillData = contactsToUpdate;
    contactsToUpdate.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QContactPresence cp = curr.detail<QContactPresence>();
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        curr.saveDetail(&cp);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    QList<QContactDetail::DetailType> typeMask;
    typeMask << QContactDetail::TypePresence;
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate, typeMask);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") masked presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).id());
    }
    manager.removeContacts(morePrefillIds);

    qDebug() << "\n\nCumulative elapsed time:" << elapsedTimeTotal << "milliseconds";
    return 0;
}
Example #11
0
TextEncoding::Ptr TextEncoding::find(const std::string& encodingName)
{
	return manager().find(encodingName);
}
Example #12
0
void RTMFPServer::run() {

	try {
		_startDatetimeStr = DateTimeFormatter::format(LocalDateTime(), "%b %d %Y %H:%M:%S");
		_pSocket->bind(SocketAddress("0.0.0.0",_port));
		NOTE("RTMFP server sendbufsize %d recvbufsize %d recvtmo %d sendtmo %d", 
				_pSocket->getSendBufferSize(),
				_pSocket->getReceiveBufferSize(),
				_pSocket->getReceiveTimeout().milliseconds(),
				_pSocket->getSendTimeout().milliseconds()
				);

		sockets.add(*_pSocket,*this);  //_mainSockets
		NOTE("RTMFP server starts on %u port",_port);

		if(_shellPort > 0) { 
			_shellSocket.bind(SocketAddress("0.0.0.0", _shellPort));
			sockets.add(_shellSocket, *this);
			NOTE("RTMFP server shell command portal on %u prot", _shellPort);
		}

		onStart();

		RTMFPManager manager(*this);
		bool terminate=false;
		while(!terminate)
			handle(terminate);

	} catch(Exception& ex) {
		FATAL("RTMFPServer, %s",ex.displayText().c_str());
	} catch (exception& ex) {
		FATAL("RTMFPServer, %s",ex.what());
	} catch (...) {
		FATAL("RTMFPServer, unknown error");
	}

	sockets.remove(*_pSocket); // _mainSockets

	// terminate handle
	terminate();
	
	// clean sessions, and send died message if need
	_handshake.clear();
	_sessions.clear();

	// stop receiving and sending engine (it waits the end of sending last session messages)
	poolThreads.clear();

	// close UDP socket
	_pSocket->close();

	// close shell command port 
	if(_shellPort > 0) { 
		_shellSocket.close();
	}

	sockets.clear();
	//_mainSockets.clear();
	_port=0;
	onStop();

	if(_pCirrus) {
		delete _pCirrus;
		_pCirrus = NULL;
	}

	if(_pSocket) {
		delete _pSocket;
		_pSocket = NULL;
	}
	
	NOTE("RTMFP server stops");
}
Example #13
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);
    app.setApplicationName(APP_NAME);
    app.setApplicationVersion("2.0");
    app.setOrganizationName(ORGANIZATION_NAME);

    bool bCallRequest = false;

    g_LanguagesPath         = QApplication::applicationDirPath() + "/lang";
    g_AppSettingsFolderPath = QDir::homePath() + "/OutCALL";
    g_AppDirPath            = QApplication::applicationDirPath();

    if (argc==2 && QString(argv[1]) == "installer")
    {
        // Setup log file paths
        QDir().mkpath(g_AppSettingsFolderPath);
        QFile(g_AppSettingsFolderPath + "/outcall.log").remove();

        if (global::IsOutlookInstalled())
        {
            if (global::EnableOutlookIntegration(true))
                global::log("Outlook plugin installed successfully.", LOG_INFORMATION);
            else
                global::log("Could not install Outlook plugin.", LOG_ERROR);
        }
        else
        {
            global::log("Outlook was not detected.", LOG_INFORMATION);
        }
        return 0;
    }

    if (argc == 2)
    {
        bCallRequest = QString(argv[1]).contains("Dial#####");
    }

    if (bCallRequest)
    {
        QStringList arguments = QString(argv[1]).split("#####");
        QString contactName = arguments[1];
        QString numbers = QString(arguments[2]).replace("outcall://", "");

        contactName.replace("&&&", " ");
        numbers.replace("&&&", " ");

        QLocalSocket s;
        s.connectToServer(LOCAL_SERVER_NAME);

        global::log("MAIN LOCAL", LOG_INFORMATION);

        QString msg = QObject::tr("It appears that %1 is not running.\n" \
                                  "Note for Windows 7/Vista users: please make sure that %2 and Outlook are running under same level of privileges. " \
                                  "Either both elevated (Run as Administrator option) or non-elevated.").arg(APP_NAME).arg(APP_NAME);

        if (!s.waitForConnected(2000))
        {
            MsgBoxInformation(msg);
        }
        else
        {
            if (!s.waitForReadyRead(2000)) // wait for "OK" from the local server
            {
                MsgBoxInformation(QObject::tr("Timeout on local socket. Maybe %1 is not running?").arg(APP_NAME));
            }
            else
            {
                QByteArray socket_data = QString("outlook_call %1 %2\n").arg(QString(contactName.toLatin1().toBase64())).
                                         arg(QString(numbers.toLatin1().toBase64())).toLatin1();
                s.write(socket_data);

                if (!s.waitForBytesWritten(2000))
                    MsgBoxError(QObject::tr("Failed local socket write()."));
            }
        }
        s.disconnectFromServer();
        s.close();

        return 0;
    }

    Notifier notifier;
    QString lang = global::getSettingsValue("language", "general").toString();
    QTranslator translator;
    if (!lang.isEmpty())
    {
        if (translator.load(QString("%1/%2.lang").arg(g_LanguagesPath).arg(lang)))
        {
            qApp->installTranslator(&translator);
        }
        else
        {
            global::setSettingsValue("language", "", "general");
            MsgBoxError(QObject::tr("Failed to load language file."));
        }
    }

    QString username  = global::getSettingsValue("username", "settings").toString();
    QByteArray secret = global::getSettingsValue("password", "settings").toByteArray();
    AsteriskManager manager(username, QString(QByteArray::fromBase64(secret)));

    OutCall outcall;
    outcall.show();

    LocalServer localServer;
    return app.exec();
}
int main(int argc, char **argv)
{
  // instantiate a model manager:
  ModelManager manager("test VRD Boundary Detection");

  // Instantiate our various ModelComponents:

  nub::soft_ref<InputFrameSeries> ifs(new InputFrameSeries(manager));
  manager.addSubComponent(ifs);

  nub::soft_ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager));
  manager.addSubComponent(ofs);

  rutz::shared_ptr<ContourBoundaryDetector> 
    cbd(new ContourBoundaryDetector());

  manager.exportOptions(MC_RECURSE);

  // Parse command-line:
  if (manager.parseCommandLine(argc, argv, "[window_size] ", 0, 1)
      == false) return(1);

  // get the operation mode
  int r = 8;
  if(manager.numExtraArgs() >  0)
    r = manager.getExtraArgAs<uint>(0);

  // let's do it!
  manager.start();

  ifs->updateNext();
  Image<PixRGB<byte> > ima = ifs->readRGB();
  // ima = Image<PixRGB<byte> >(ima.getDims(),ZEROS);
  // drawFilledRect(ima, 
  // 	   Rectangle(Point2D<int>(180, 100), Dims(100, 100)), 
  // 	   PixRGB<byte>(255,0,0));

  Image<float> fIma(luminance(ima));
  Image<float> tempFIma = fIma;
  inplaceNormalize(tempFIma, 0.0f,255.0f);  
  Image<byte>  bIma(tempFIma); 

  Timer timer(1000000); timer.reset();
  cbd->computeContourBoundary(ima,r);	
  Image<float> boundaryMap = cbd->getVarianceRidgeBoundaryMap();
  LINFO("time: %f ms", timer.get()/1000.0);

  // get non-max suppressed boundary map image
  
  float mVal = 32;
  float bVal = 255 - mVal;
  inplaceNormalize(boundaryMap, 0.0f,bVal);
  Image<byte> dBmapc(boundaryMap);

  Image<byte> dImaR, dImaG, dImaB;
  getComponents(ima, dImaR, dImaG, dImaB);
  inplaceNormalize(dImaR, byte(0), byte(mVal));
  inplaceNormalize(dImaG, byte(0), byte(mVal));
  inplaceNormalize(dImaB, byte(0), byte(mVal));
  Image<PixRGB<byte> > dBmap = toRGB(dBmapc);
  Image<PixRGB<byte> > dIma  = makeRGB(dImaR,dImaG,dImaB);

  // the non-max suppressed boundary map image
  Image<float> dBmapNMStemp = cbd->getNmsBoundaryMap();
  inplaceNormalize(dBmapNMStemp, 0.0F, 255.0F);
  Image<PixRGB<byte> > dBmapNMS = toRGB(Image<byte>(dBmapNMStemp));

  // the contour boundary map image
  Image<float> dCBmapTemp = cbd->getEdgelBoundaryMap();
  inplaceNormalize(dCBmapTemp, 0.0F, bVal);
  Image<PixRGB<byte> > dCBmap = toRGB(Image<byte>(dCBmapTemp));

  // setup the display map
  uint w = ima.getWidth();
  uint h = ima.getHeight();
  Image<PixRGB<byte> > dispIma(4*w,2*h,ZEROS);
  inplacePaste(dispIma, ima, Point2D<int>(0,0));
  inplacePaste(dispIma, Image<PixRGB<byte> >(dBmap), Point2D<int>(w,0));
  //inplacePaste(dispIma, Image<PixRGB<byte> >(dIma+dBmap), Point2D<int>(w,0));
  inplacePaste(dispIma, dBmapNMS, Point2D<int>(0,h));
  inplacePaste(dispIma,  Image<PixRGB<byte> >(dIma+dCBmap), Point2D<int>(w,h));
  inplacePaste(dispIma,  cbd->getContourBoundaryMap(), Point2D<int>(2*w,0));

  // angle at 4th param: 0 degrees
  //Image<float> gaborImg = getGabor(fIma, 0.0, 2.50, 1.0, 5);
  // Image<float> gaborImg = getGabor(fIma,0,7,1,9);
  // --------------
  // Image<float> gaborImg = getCanny(fIma);
  // inplaceNormalize(gaborImg, 0.0F, 255.0F);
  // Image<PixRGB<byte> > dGaborImg = toRGB(Image<byte>(gaborImg));
  // inplacePaste(dispIma, Image<PixRGB<byte> >(dGaborImg), 
  //  	       Point2D<int>(w*2,h));  

  // Image<float> rDir0 = itsRDirMax[0];
  // inplaceNormalize(rDir0, 0.0F, 255.0F);
  // Image<PixRGB<byte> > dRDir0 = toRGB(Image<byte>(rDir0));
  // inplacePaste(dispIma, dRDir0, Point2D<int>(2*w,0));

  // Image<float> rDir1 = itsRDirMax[1];
  // inplaceNormalize(rDir1, 0.0F, 255.0F);
  // Image<PixRGB<byte> > dRDir1 = toRGB(Image<byte>(rDir1));
  // inplacePaste(dispIma, dRDir1, Point2D<int>(3*w,0));

  // Image<float> rDir2 = itsRDirMax[2];
  // inplaceNormalize(rDir2, 0.0F, 255.0F);
  // Image<PixRGB<byte> > dRDir2 = toRGB(Image<byte>(rDir2));
  // inplacePaste(dispIma, dRDir2, Point2D<int>(2*w,h));

  // Image<float> rDir3 = itsRDirMax[3];
  // inplaceNormalize(rDir3, 0.0F, 255.0F);
  // Image<PixRGB<byte> > dRDir3 = toRGB(Image<byte>(rDir3));
  // inplacePaste(dispIma, dRDir3, Point2D<int>(3*w,h));

  // 300, 140
  /*
  drawRect(dispIma, 
	   Rectangle(Point2D<int>(w+156, 68), Dims(8, 8)), 
	   PixRGB<byte>(255,0,0));
  drawRect(dispIma, 
	   Rectangle(Point2D<int>(w+152, 64), Dims(16, 16)), 
	   PixRGB<byte>(255,255,0));

  drawRect(dispIma, 
	   Rectangle(Point2D<int>(156, h+68), Dims(8, 8)), 
	   PixRGB<byte>(255,0,0));
  drawRect(dispIma, 
	   Rectangle(Point2D<int>(152, h+64), Dims(16, 16)), 
	   PixRGB<byte>(255,255,0));
  */
  //ofs->writeRGB(boundaryMap, "VRD Boundary Detection");
  ofs->writeRGB(dispIma, "VRD Boundary Detection");
  ofs->updateNext();
  Raster::waitForKey();

  return 0;
}
 // For member pointers, we use the small-object optimization buffer.
 static inline void
 manager(const function_buffer& in_buffer, function_buffer& out_buffer,
         functor_manager_operation_type op, member_ptr_tag)
 {
   manager(in_buffer, out_buffer, op, mpl::true_());
 }
Example #16
0
void TextEncoding::remove(const std::string& encodingName)
{
	manager().remove(encodingName);
}
Example #17
0
/*!
  Returns a rich text formatted QString representing the contents the contact.
*/
QString OContact::toRichText() const
{
    QString text;
    QString value, comp, state;
    QString str;
    bool marker = false;

    Config cfg("qpe");
    cfg.setGroup("Appearance");
    int addressformat = cfg.readNumEntry( "AddressFormat", Zip_City_State );

    // name, jobtitle and company
    if ( !(value = fullName()).isEmpty() )
	text += "<b><h3><img src=\"addressbook/AddressBook\"> " + Qtopia::escapeString(value) + "</h3></b>";

    if ( !(value = jobTitle()).isEmpty() )
	text += Qtopia::escapeString(value) + " ";

    comp = company();
    if ( !(value = department()).isEmpty() ) {
	text += Qtopia::escapeString(value);
	if ( comp )
		text += ", " + Qtopia::escapeString(comp);
    }else if ( comp )
	    text += "<br>" + Qtopia::escapeString(comp);
    text += "<br><hr>";

    // defailt email
    QString defEmail = defaultEmail();
    if ( !defEmail.isEmpty() ){
	text += "<b><img src=\"addressbook/email\"> " + QObject::tr("Default Email: ") + "</b>"
		+ Qtopia::escapeString(defEmail);
	marker = true;
    }

    // business address
    if ( !businessStreet().isEmpty() || !businessCity().isEmpty() ||
	 !businessZip().isEmpty() || !businessCountry().isEmpty() ) {
	text += QObject::tr( "<br><b>Work Address:</b>" );
	marker = true;
    }

    if ( !(value = businessStreet()).isEmpty() ){
	    text += "<br>" + Qtopia::escapeString(value);
	    marker = true;
    }

    switch( addressformat ){
    case Zip_City_State:{ //  Zip_Code City, State
	    state =  businessState();
	    if ( !(value = businessZip()).isEmpty() ){
		    text += "<br>" + Qtopia::escapeString(value) + " ";
		    marker = true;

	    }
	    if ( !(value = businessCity()).isEmpty() ) {
		    marker = true;
		    if ( businessZip().isEmpty() && !businessStreet().isEmpty() )
			    text += "<br>";
		    text += Qtopia::escapeString(value);
		    if ( state )
			    text += ", " + Qtopia::escapeString(state);
	    } else if ( !state.isEmpty() ){
		    text += "<br>" + Qtopia::escapeString(state);
		    marker = true;
	    }
	    break;
    }
    case City_State_Zip:{ // City, State Zip_Code
	    state =  businessState();
	    if ( !(value = businessCity()).isEmpty() ) {
		    marker = true;
		    text += "<br>" + Qtopia::escapeString(value);
		    if ( state )
			    text += ", " + Qtopia::escapeString(state);
	    } else if ( !state.isEmpty() ){
		    text += "<br>" + Qtopia::escapeString(state);
		    marker = true;
	    }
	    if ( !(value = businessZip()).isEmpty() ){
		    text += " " + Qtopia::escapeString(value);
		    marker = true;
	    }
	    break;
    }
    }

    if ( !(value = businessCountry()).isEmpty() ){
	text += "<br>" + Qtopia::escapeString(value);
	marker = true;
    }

    // rest of Business data
    str = office();
    if ( !str.isEmpty() ){
	text += "<br><b>" + QObject::tr("Office: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = businessWebpage();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/webpagework\"> " + QObject::tr("Business Web Page: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = businessPhone();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/phonework\"> " + QObject::tr("Business Phone: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = businessFax();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/faxwork\"> " + QObject::tr("Business Fax: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = businessMobile();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/mobilework\"> " + QObject::tr("Business Mobile: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = businessPager();
    if ( !str.isEmpty() ){
	text += "<br><b>" + QObject::tr("Business Pager: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }

    // text += "<br>";

    // home address
    if ( !homeStreet().isEmpty() || !homeCity().isEmpty() ||
	 !homeZip().isEmpty() || !homeCountry().isEmpty() ) {
	text += QObject::tr( "<br><b>Home Address:</b>" );
	marker = true;
    }

    if ( !(value = homeStreet()).isEmpty() ){
	text += "<br>" + Qtopia::escapeString(value);
	marker = true;
    }

    switch( addressformat ){
    case Zip_City_State:{ //  Zip_Code City, State
	    state =  homeState();
	    if ( !(value = homeZip()).isEmpty() ){
		    text += "<br>" + Qtopia::escapeString(value) + " ";
		    marker = true;
	    }
	    if ( !(value = homeCity()).isEmpty() ) {
		    marker = true;
		    if ( homeZip().isEmpty() && !homeStreet().isEmpty() )
			    text += "<br>";
		    text += Qtopia::escapeString(value);
		    if ( !state.isEmpty() )
			    text += ", " + Qtopia::escapeString(state);
	    } else if (!state.isEmpty()) {
		    text += "<br>" + Qtopia::escapeString(state);
		    marker = true;
	    }
	    break;
    }
    case City_State_Zip:{ // City, State Zip_Code
	    state =  homeState();
	    if ( !(value = homeCity()).isEmpty() ) {
		    marker = true;
		    text += "<br>" + Qtopia::escapeString(value);
		    if ( state )
			    text += ", " + Qtopia::escapeString(state);
	    } else if ( !state.isEmpty() ){
		    text += "<br>" + Qtopia::escapeString(state);
		    marker = true;
	    }
	    if ( !(value = homeZip()).isEmpty() ){
		    text += " " + Qtopia::escapeString(value);
		    marker = true;
	    }
	    break;
    }
    }

    if ( !(value = homeCountry()).isEmpty() ){
	text += "<br>" + Qtopia::escapeString(value);
	marker = true;
    }

    // rest of Home data
    str = homeWebpage();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/webpagehome\"> " + QObject::tr("Home Web Page: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = homePhone();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/phonehome\"> " + QObject::tr("Home Phone: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = homeFax();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/faxhome\"> " + QObject::tr("Home Fax: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }
    str = homeMobile();
    if ( !str.isEmpty() ){
	text += "<br><b><img src=\"addressbook/mobilehome\"> " + QObject::tr("Home Mobile: ") + "</b>"
		+ Qtopia::escapeString(str);
	marker = true;
    }

    if ( marker )
	    text += "<br><hr>";

    // the rest...
    str = emails();
    if ( !str.isEmpty() && ( str != defEmail ) )
	text += "<br><b>" + QObject::tr("All Emails: ") + "</b>"
		+ Qtopia::escapeString(str);
    str = profession();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Profession: ") + "</b>"
		+ Qtopia::escapeString(str);
    str = assistant();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Assistant: ") + "</b>"
		+ Qtopia::escapeString(str);
    str = manager();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Manager: ") + "</b>"
		+ Qtopia::escapeString(str);
    str = gender();
    if ( !str.isEmpty() && str.toInt() != 0 ) {
	    text += "<br>";
	    if ( str.toInt() == 1 )
		    str = QObject::tr( "Male" );
	    else if ( str.toInt() == 2 )
		    str = QObject::tr( "Female" );
	    text += "<b>" + QObject::tr("Gender: ") + "</b>" + str;
    }
    str = spouse();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Spouse: ") + "</b>"
		+ Qtopia::escapeString(str);
    if ( birthday().isValid() ){
	    str = TimeString::numberDateString( birthday() );
	    text += "<br><b>" + QObject::tr("Birthday: ") + "</b>"
		    + Qtopia::escapeString(str);
    }
    if ( anniversary().isValid() ){
	    str = TimeString::numberDateString( anniversary() );
	    text += "<br><b>" + QObject::tr("Anniversary: ") + "</b>"
		    + Qtopia::escapeString(str);
    }
    str = children();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Children: ") + "</b>"
		+ Qtopia::escapeString(str);

    str = nickname();
    if ( !str.isEmpty() )
	text += "<br><b>" + QObject::tr("Nickname: ") + "</b>"
		+ Qtopia::escapeString(str);

    // categories
    if ( categoryNames("Contacts").count() ){
	    text += "<br><b>" + QObject::tr( "Category:") + "</b> ";
	    text += categoryNames("Contacts").join(", ");
    }

    // notes last
    if ( !(value = notes()).isEmpty() ) {
	    text += "<br><hr><b>" + QObject::tr( "Notes:") + "</b> ";
	    QRegExp reg("\n");

	    //QString tmp = Qtopia::escapeString(value);
	    QString tmp = QStyleSheet::convertFromPlainText(value);
	    //tmp.replace( reg, "<br>" );
	    text += "<br>" + tmp + "<br>";
    }
    return text;
}
Example #18
0
    void Scene::initialize( const std::vector<ActorUId>& persistent_actors )
    {
        mSceneManager = EventManager::create("Scene "+mName+" Manager");
        Controller::get()->eventManager()->addListener(fastdelegate::MakeDelegate(this, &Scene::handleInitGUI), InitGUIEvent::TYPE);
        Controller::get()->eventManager()->addListener( fastdelegate::MakeDelegate(this, &Scene::handleSceneUpdate), SceneUpdateEvent::TYPE );
        Controller::get()->eventManager()->addListener( fastdelegate::MakeDelegate(this, &Scene::handleReturnActorCreate), ReturnActorCreatedEvent::TYPE );
        Controller::get()->eventManager()->addListener( fastdelegate::MakeDelegate(this, &Scene::handleScenePreDraw), ScenePreDrawEvent::TYPE );
        Controller::get()->eventManager()->addListener( fastdelegate::MakeDelegate(this, &Scene::handleSceneDraw), SceneDrawEvent::TYPE );
        Controller::get()->eventManager()->addListener( fastdelegate::MakeDelegate(this, &Scene::handleShutDown), ShutDownEvent::TYPE );
        
        if( !persistent_actors.empty() ){
            for(auto &id : persistent_actors)
            {
                auto actor_weak = ActorManager::get()->retreiveUnique(id);
                mActors.insert( std::make_pair(id, actor_weak) );
            }
        }
        
        auto init = ConfigManager::get()->retreiveActorsForScene( mName );
        
        ///call to inherited initialize for sub classes to pulll custom shit out of the config
        initialize( ConfigManager::get()->retreiveScene(mName) );
        
        try {
            
            //TODO: the problem with persistent actors is how to manage state across scenes, how to identify actors of the same type across scenes that are persistent, one solution is destroy all and reload referencing a serialized state file that is written out and read back in or something
            //for now, just sending across actors marked 'persistent' and not including them in the config for the next scene, the state has to be handled at runtime then
            
            auto & actors = init.getChildren();
            
            auto it = actors.begin();
            auto end = actors.end();
            for(;it!=end;++it){
                auto actor_name = it->getValueForKey("name");
                CI_LOG_V("found actor: "+actor_name);

                auto onInit = it->getValueForKey<bool>( "create_on_scene_init" );
                auto persistent = it->getValueForKey<bool>( "persistent" );
                
                if( persistent ){
                    //make sure its not already in there
                   if( !ec::ActorManager::get()->actorExists( ec::getHash(actor_name) ) ){
                       if( onInit ){
                           //make sure it shuld be created on scene init
                           CI_LOG_V("creating actor: "+actor_name);
                           Controller::get()->eventManager()->triggerEvent( CreateActorEvent::create( mName, actor_name) );
                       }
                    }
                }else if (onInit){
                    //make sure it shuld be created on scene init
                    CI_LOG_V("creating actor: "+actor_name);
                    Controller::get()->eventManager()->triggerEvent( CreateActorEvent::create( mName, actor_name) );

                }

                
            }
            
        } catch (const ci::JsonTree::ExcChildNotFound &e) {
            CI_LOG_E("actors not found in init");
        }
        
      
        ///POST INITIALIZE ALL ACTORS
        auto actor = mActors.begin();
        auto end = mActors.end();
        
        while( actor != end )
        {
            if(auto a = (*actor).second.lock()){
                a->postInit();
                ++actor;
            }else{
                CI_LOG_E("Actor is missing");
                ec::Controller::get()->eventManager()->triggerEvent(DestoryActorEvent::create((*actor).first));
                actor = mActors.erase(actor);
            }
        }
        
        postInit();
        
        ///run setup events;
        manager()->update();
        
    }
Example #19
0
group::module_ptr group::get_module(const std::string& module_name) {
    return manager()->get_module(module_name);
}
void forwarding_actor_proxy::kill_proxy(uint32_t reason) {
  manager(invalid_actor);
  cleanup(reason);
}
Example #21
0
void qDBusBindToApplication()
{
    manager()->bindToApplication();
}
Example #22
0
//-------------------------------------------------------------------------------------------------
int_t xTMAIN(int_t a_argsNum, tchar_t *a_args[])
{
    xUNUSED(a_argsNum);
    xUNUSED(a_args);

    {
    #if 1
        std::vector<int_t> signalNums;
        signalNums.push_back(SIGHUP);      // Hangup (POSIX)
        signalNums.push_back(SIGINT);      // Interrupt (ANSI)
        signalNums.push_back(SIGQUIT);     // Quit (POSIX)
        signalNums.push_back(SIGILL);      // Illegal instruction (ANSI)
        signalNums.push_back(SIGTRAP);     // Trace trap (POSIX)
        signalNums.push_back(SIGABRT);     // Abort (ANSI)
        signalNums.push_back(SIGIOT);      // IOT trap (4.2 BSD)
        signalNums.push_back(SIGBUS);      // BUS error (4.2 BSD)
        signalNums.push_back(SIGFPE);      // Floating-point exception (ANSI)
        signalNums.push_back(SIGKILL);     // Kill); unblockable (POSIX)
        signalNums.push_back(SIGUSR1);     // User-defined signal 1 (POSIX)
        signalNums.push_back(SIGSEGV);     // Segmentation violation (ANSI)
        signalNums.push_back(SIGUSR2);     // User-defined signal 2 (POSIX)
        signalNums.push_back(SIGPIPE);     // Broken pipe (POSIX)
        signalNums.push_back(SIGALRM);     // Alarm clock (POSIX)
        signalNums.push_back(SIGTERM);     // Termination (ANSI)
        signalNums.push_back(SIGSTKFLT);   // Stack fault
        signalNums.push_back(SIGCLD);      // Same as SIGCHLD (System V)
        signalNums.push_back(SIGCHLD);     // Child status has changed (POSIX)
        signalNums.push_back(SIGCONT);     // Continue (POSIX)
        signalNums.push_back(SIGSTOP);     // Stop); unblockable (POSIX)
        signalNums.push_back(SIGTSTP);     // Keyboard stop (POSIX)
        signalNums.push_back(SIGTTIN);     // Background read from tty (POSIX)
        signalNums.push_back(SIGTTOU);     // Background write to tty (POSIX)
        signalNums.push_back(SIGURG);      // Urgent condition on socket (4.2 BSD)
        signalNums.push_back(SIGXCPU);     // CPU limit exceeded (4.2 BSD)
        signalNums.push_back(SIGXFSZ);     // File size limit exceeded (4.2 BSD)
        signalNums.push_back(SIGVTALRM);   // Virtual alarm clock (4.2 BSD)
        signalNums.push_back(SIGPROF);     // Profiling alarm clock (4.2 BSD)
        signalNums.push_back(SIGWINCH);    // Window size change (4.3 BSD); Sun)
        signalNums.push_back(SIGPOLL);     // Pollable event occurred (System V)
        signalNums.push_back(SIGIO);       // I/O now possible (4.2 BSD)
        signalNums.push_back(SIGPWR);      // Power failure restart (System V)
        signalNums.push_back(SIGSYS);      // Bad system call

        Application application(xT("[app_name]_guid"));
        Application::setName(xT("[app_name]"));
    #if 0
        application.setName(xT("[app_name]"));
        application.setDecription(xT("[decription]"));
        application.setUsage(xT("[usage]"));
        application.setHelp(xT("[help]"));
        application.setCopyrightYears(xT("[2008-2014]"));
        application.setVersionMajor(xT("[1]"));
        application.setVersionMinor(xT("[0]"));
        application.setVersionPatch(xT("[0]"));
        application.setVersionType(xT("[alpha]"));
        application.setVersionRevision(xT("[develop/970f53b]"));
        application.setVendorName(xT("[Skynowa Studio]"));
        application.setVendorDomain(xT("[com]"));
        application.setVendorAuthor(xT("[skynowa]"));
        application.setVendorUrl(xT("[http://bitbucket.org/skynowa/xlib]"));
        application.setVendorEmail(xT("[[email protected]]"));
        application.setVendorSkype(xT("[skynowa777]"));
    #endif

    #if 0
        Trace()
            << xTRACE_VAR(application.name())            << xT("\n")
            << xTRACE_VAR(application.decription())      << xT("\n")
            << xTRACE_VAR(application.usage())           << xT("\n")
            << xTRACE_VAR(application.help())            << xT("\n")
            << xTRACE_VAR(application.copyrightYears())  << xT("\n")
            << xTRACE_VAR(application.versionMajor())    << xT("\n")
            << xTRACE_VAR(application.versionMinor())    << xT("\n")
            << xTRACE_VAR(application.versionPatch())    << xT("\n")
            << xTRACE_VAR(application.versionType())     << xT("\n")
            << xTRACE_VAR(application.versionRevision()) << xT("\n")
            << xTRACE_VAR(application.vendorName())      << xT("\n")
            << xTRACE_VAR(application.vendorDomain())    << xT("\n")
            << xTRACE_VAR(application.vendorAuthor())    << xT("\n")
            << xTRACE_VAR(application.vendorUrl())       << xT("\n")
            << xTRACE_VAR(application.vendorEmail())     << xT("\n")
            << xTRACE_VAR(application.vendorSkype());
    #endif

        application.setOnSignals(signalNums, SignalFunctor::onSignals);
        application.setOnTerminate(SignalFunctor::onTerminate);
        application.setOnExit(SignalFunctor::onExit);

        // test error
        TestFail testFail;
        testFail.foo3();
    #endif
    }

#if xOPTION_TESTS
    // checks
    {
    #if xENV_UNIX
        SystemInfo info;
        xCHECK_MSG_RET(info.isUserAdmin(), xT("xLib_test: Can't run as root"), EXIT_FAILURE);
    #endif
    }

    // options (default)
    bool_t      isUseTracing = true;
    ulonglong_t allLoops     = 1ULL;
    ulonglong_t unitLoops    = 1ULL;
    ulonglong_t caseLoops    = 1ULL;
    {
        std::vec_tstring_t args;

        ProcessInfo info;
        info.setProcessId(Process::currentId());
        info.commandLine(&args);

        if (a_argsNum == 1) {
            // OK, run tests with default params
        }
        else if (a_argsNum == 2) {
            // usage
            bool_t bRv = StringCI::compare(xT("-h"),     args.at(1)) ||
                         StringCI::compare(xT("--help"), args.at(1));
            if (!bRv) {
                std::tcout << xT("\nxLib_test: unknown switches\n") << std::endl;
            } else {
                std::tcout << xT("\nUsage: ./xLib_test [is_tracing] [all_loops] [unit_loops]\n")
                              xT("  - xLib_test  (binary file path)\n")
                              xT("  - is_tracing (is tracing)\n")
                              xT("  - all_loops  (loops for all tests)\n")
                              xT("  - unit_loops (loops for unit test)\n")
                              xT("  - case_loops (loops for case test)\n") << std::endl;
            }

            return EXIT_SUCCESS;
        }
        else if (a_argsNum == 5) {
            // addition params
            isUseTracing = String::cast<bool_t>     ( args.at(1) );
            allLoops     = String::cast<ulonglong_t>( args.at(2) );
            unitLoops    = String::cast<ulonglong_t>( args.at(3) );
            caseLoops    = String::cast<ulonglong_t>( args.at(4) );
        }
        else {
            // fail
            std::tcout << xT("\nxLib_test: unknown switches\n") << std::endl;
            return EXIT_FAILURE;
        }
    }

    // add and run tests
    {
        TestManager manager(isUseTracing);

        // Test
    #if 1
        manager.add(new Test_Test);
    #endif

        // Core
    #if 1
        manager.add(new Test_Units);
        manager.add(new Test_Defines);
        manager.add(new Test_Limits);
        manager.add(new Test_Utils);
        manager.add(new Test_StdStream);
        manager.add(new Test_HandleT);
        manager.add(new Test_Type);
        manager.add(new Test_Flags);
        manager.add(new Test_Array);
        manager.add(new Test_AutoReset);
        manager.add(new Test_Char);
        manager.add(new Test_Locale);
        manager.add(new Test_String);
        manager.add(new Test_DateTime);
        manager.add(new Test_Com);
        manager.add(new Test_Application);
    #endif

        // Crypt
    #if 1
        manager.add(new Test_Base64);
        #if xHAVE_OPENSSL_CRYPTO
        manager.add(new Test_Blowfish);
        #endif
        manager.add(new Test_Crc32);
        manager.add(new Test_Guid);
        manager.add(new Test_Random);

        // Db
        #if xHAVE_MYSQL
        manager.add(new Test_MySql);
        #endif
    #endif

        // Debug
    #if 1
        manager.add(new Test_Debug);
        manager.add(new Test_BuildInfo);
        manager.add(new Test_StdError);
        manager.add(new Test_NativeError);
        manager.add(new Test_Exception);
        manager.add(new Test_StackTrace);
        manager.add(new Test_Debugger);
        manager.add(new Test_ErrorReport);
        manager.add(new Test_Profiler);
        manager.add(new Test_AutoProfiler);
    #endif

        // File system
    #if 1
        manager.add(new Test_Path);
        manager.add(new Test_FileType);
        manager.add(new Test_File);
        manager.add(new Test_FileTemp);
        manager.add(new Test_Dll);
        manager.add(new Test_Finder);
        manager.add(new Test_Dir);
        manager.add(new Test_Volume);
        manager.add(new Test_Config);
        manager.add(new Test_Backup);
    #endif

        // Log
    #if 1
        manager.add(new Test_Trace);
        manager.add(new Test_FileLog);
        manager.add(new Test_SystemLog);
    #endif

        // Net
    #if 1
        manager.add(new Test_CookiePv0);
        manager.add(new Test_CookiePv1);
        manager.add(new Test_Cgi);
        manager.add(new Test_SocketInit);
        manager.add(new Test_DnsClient);
        // manager.add(new Test_TcpClient);
        // manager.add(new Test_TcpServer);
        manager.add(new Test_HttpClient);
    #endif

        // Patterns
    #if 1
        manager.add(new Test_Observer);
        manager.add(new Test_Raii);
        manager.add(new Test_Singleton);
    #endif

        // Sync
    #if 1
        manager.add(new Test_AtomicLongInt);
        manager.add(new Test_ThreadStorage);
        manager.add(new Test_Mutex);
        manager.add(new Test_AutoMutex);
        manager.add(new Test_IpcMutex);
        manager.add(new Test_AutoIpcMutex);
        // manager.add(new Test_Event);
        manager.add(new Test_Condition);
        manager.add(new Test_Semaphore);
        manager.add(new Test_IpcSemaphore);
        // manager.add(new Test_Sleeper);
        // manager.add(new Test_Thread);
        // manager.add(new Test_ThreadPool);
        manager.add(new Test_Process);
    #endif

        // Gui
    #if 1
        manager.add(new Test_MsgBox);
    #endif

        // System
    #if 1
        manager.add(new Test_Environment);
        manager.add(new Test_SystemInfo);
        manager.add(new Test_ProcessInfo);
        manager.add(new Test_Console);
        manager.add(new Test_Shell);
    #endif

        manager.run(allLoops, unitLoops, caseLoops);
    }
#endif // xOPTION_TESTS

    return EXIT_SUCCESS;
}
Example #23
0
void QDBusConnection::closeConnection(const QString &name)
{
    manager()->removeConnection(name);
}
Example #24
0
int SDL_MAIN_FUNC(int argc, char *argv[])
{
    CLogger logger; // single istance of logger

    // Workaround for character encoding in argv on Windows
    #if PLATFORM_WINDOWS
    int wargc;
    wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &wargc);
    if(wargv == nullptr)
    {
        logger.Error("CommandLineToArgvW failed\n");
        return 1;
    }
    argv = new char*[wargc];
    for(int i = 0; i < wargc; i++) {
        std::wstring warg = wargv[i];
        std::string arg = CSystemUtilsWindows::UTF8_Encode(warg);
        argv[i] = new char[arg.length()+1];
        strcpy(argv[i], arg.c_str());
    }
    LocalFree(wargv);
    #endif

    CResourceManager manager(argv[0]);

    // Initialize static string arrays
    InitializeRestext();
    InitializeEventTypeTexts();

    logger.Info("%s starting\n", COLOBOT_FULLNAME);
    
    int code = 0;
    while(true) {
        CSystemUtils* systemUtils = CSystemUtils::Create(); // platform-specific utils
        systemUtils->Init();
        
        CApplication* app = new CApplication(); // single instance of the application

        ParseArgsStatus status = app->ParseArguments(argc, argv);
        if (status == PARSE_ARGS_FAIL)
        {
            systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", "Invalid commandline arguments!\n");
            return app->GetExitCode();
        }
        else if (status == PARSE_ARGS_HELP)
        {
            return app->GetExitCode();
        }


        if (! app->Create())
        {
            app->Destroy(); // ensure a clean exit
            code = app->GetExitCode();
            if ( code != 0 && !app->GetErrorMessage().empty() )
            {
                systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", app->GetErrorMessage());
            }
            logger.Info("Didn't run main loop. Exiting with code %d\n", code);
            return code;
        }

        code = app->Run();
        bool restarting = app->IsRestarting();

        delete app;
        delete systemUtils;
        if(!restarting) break;
    }

    logger.Info("Exiting with code %d\n", code);

    #if PLATFORM_WINDOWS
    // See the workaround above
    delete[] argv;
    #endif

    return code;
}
Example #25
0
Msg::Msg(PluginManagerInterface* parent) : Plugin(parent) {
    manager()->databasePlugin()->registerInternalVariable(this, "msg_display_count", PRIVATE | INTERNAL | RESIDENT | GLOBAL | UNENCRYPTED, INT, "8");
}
Example #26
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	extern struct key const keys [];
	static char const * optv [] =
	{
		"abB:d:D:efFHi:IJ:K:l:LmMn:N:p:P:QqrRS:t:Tvw:x",
		"device [device] [...]",
		"Qualcomm Atheros Panther/Lynx Powerline Device Manager",
		"a\tread Device Attributes using VS_OP_ATTRIBUTES",
		"B n\tperform pushbutton action (n) using MS_PB_ENC [1|2|3|'join'|'leave'|'status']",
		"d f\tdump and clear watchdog report to file (f) using VS_WD_RPT",
		"D x\tDevice Access Key (DAK) is (x) [" DAK1 "]",
		"e\tredirect stderr to stdout",
		"f\tread NVRAM Configuration using VS_GET_NVM",
		"F[F]\tflash [force] parameters and/or firmware using VS_MODULE_OPERATION",
		"H\tstop host action requests using VS_HOST_ACTION.IND",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"I\tread device identity using VS_MODULE_OPERATION",
		"J x\tset NMK on remote device (x) via local device using VS_SET_KEY (see -K)",
		"K x\tNetwork Membership Key (NMK) is (x) [" NMK1 "]",
		"l n\tloop (n) times [" LITERAL (PLCTOOL_LOOP) "]",
		"L\tdisplay link status",
		"m\tread network membership information using VS_NW_INFO",
		"M\tset NMK on local device using VS_SET_KEY (see -K)",
		"n f\tread NVM from SDRAM to file (f) using VS_MODULE_OPERATION",
		"N f\twrite firmware file (f) to flash memory using VS_MODULE_OPERATION",
		"p f\tread PIB from SDRAM to file (f) using VS_MODULE_OPERATION",
		"P f\twrite parameter file (f) to flash memory using VS_MODULE_OPERATION",
		"q\tquiet mode",
		"Q\tquick flash (return immediately)",
		"r\tread hardware and firmware revision using VS_SW_VER",
		"R\treset device using VS_RS_DEV",
		"S f\twrite softloader file (f) to flash memory using VS_MODULE_OPERATION",
		"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_TIMEOUT) "]",
		"T\trestore factory defaults using VS_FAC_DEFAULTS",
		"v\tverbose mode",
		"w n\tpause (n) seconds [" LITERAL (PLCTOOL_WAIT) "]",
		"x\texit on error",
		(char const *) (0)
	};

#include "../plc/plc.c"

	signed loop = PLCTOOL_LOOP;
	signed wait = PLCTOOL_WAIT;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'a':
			_setbits (plc.flags, PLC_ATTRIBUTES);
			break;
		case 'B':
			_setbits (plc.flags, PLC_PUSH_BUTTON);
			plc.pushbutton = (unsigned)(uintspec (synonym (optarg, buttons, BUTTONS), 0, UCHAR_MAX));
			break;
		case 'b':
			_setbits (plc.flags, PLC_REMOTEHOSTS);
			break;
		case 'd':
			_setbits (plc.flags, PLC_WATCHDOG_REPORT);
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.rpt.file = open (plc.rpt.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.rpt.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			plc.readaction = 3;
			break;
		case 'D':
			if (!strcmp (optarg, "none"))
			{
				memcpy (plc.DAK, keys [0].DAK, sizeof (plc.DAK));
				break;
			}
			if (!strcmp (optarg, "key1"))
			{
				memcpy (plc.DAK, keys [1].DAK, sizeof (plc.DAK));
				break;
			}
			if (!strcmp (optarg, "key2"))
			{
				memcpy (plc.DAK, keys [2].DAK, sizeof (plc.DAK));
				break;
			}
			if (!hexencode (plc.DAK, sizeof (plc.DAK), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_DAK, optarg);
			}
			break;
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'f':
			_setbits (plc.flags, PLC_NVRAM_INFO);
			break;
		case 'F':
			_setbits (plc.module, (VS_MODULE_MAC | VS_MODULE_PIB));
			if (_anyset (plc.flags, PLC_FLASH_DEVICE))
			{
				_setbits (plc.module, VS_MODULE_FORCE);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 'H':
			_setbits (plc.flags, PLC_HOST_ACTION);
			break;
		case 'I':
			_setbits (plc.flags, PLC_READ_IDENTITY);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'J':
			if (!hexencode (plc.RDA, sizeof (plc.RDA), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_MAC, optarg);
			}
			_setbits (plc.flags, PLC_SETREMOTEKEY);
			break;
		case 'K':
			if (!strcmp (optarg, "none"))
			{
				memcpy (plc.NMK, keys [0].NMK, sizeof (plc.NMK));
				break;
			}
			if (!strcmp (optarg, "key1"))
			{
				memcpy (plc.NMK, keys [1].NMK, sizeof (plc.NMK));
				break;
			}
			if (!strcmp (optarg, "key2"))
			{
				memcpy (plc.NMK, keys [2].NMK, sizeof (plc.NMK));
				break;
			}
			if (!hexencode (plc.NMK, sizeof (plc.NMK), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_NMK, optarg);
			}
			break;
		case 'M':
			_setbits (plc.flags, PLC_SETLOCALKEY);
			break;
		case 'l':
			loop = (unsigned)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'L':
			_setbits (plc.flags, PLC_LINK_STATUS);
			break;
		case 'm':
			_setbits (plc.flags, PLC_NETWORK);
			break;
		case 'N':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.NVM.file = open (plc.NVM.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.NVM.name);
			}
			if (nvmfile2 (&plc.NVM))
			{
				error (1, errno, "Bad firmware file: %s", plc.NVM.name);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 'n':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.nvm.file = open (plc.nvm.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.nvm.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			_setbits (plc.flags, PLC_READ_MAC);
			break;
		case 'P':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.PIB.file = open (plc.PIB.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.PIB.name);
			}
			if (pibfile2 (&plc.PIB))
			{
				error (1, errno, "Bad parameter file: %s", plc.PIB.name);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 'p':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.pib.file = open (plc.pib.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.pib.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			_setbits (plc.flags, PLC_READ_PIB);
			break;
		case 'Q':
			_setbits (plc.flags, PLC_QUICK_FLASH);
			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'R':
			_setbits (plc.flags, PLC_RESET_DEVICE);
			break;
		case 'r':
			_setbits (plc.flags, PLC_VERSION);
			break;
		case 'S':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.CFG.file = open (plc.CFG.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.CFG.name);
			}
			if (nvmfile2 (&plc.CFG))
			{
				error (1, errno, "Bad softloader file: %s", plc.CFG.name);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 't':
			channel.timeout = (signed)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'T':
			_setbits (plc.flags, PLC_FACTORY_DEFAULTS);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		case 'V':
			_setbits (plc.flags, PLC_SNIFFER);
			plc.action = (uint8_t)(uintspec (optarg, 0, UCHAR_MAX));
			break;
		case 'w':
			wait = (unsigned)(uintspec (optarg, 0, 3600));
			break;
		case 'x':
			_setbits (plc.flags, PLC_BAILOUT);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 1)
	{
		if (plc.nvm.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
		if (plc.pib.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
		if (plc.rpt.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
	}
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (!argc)
	{
		manager (&plc, loop, wait);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		manager (&plc, loop, wait);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Example #27
0
void Msg::outgoingUser(const QString& login) {
    if(!manager()->databasePlugin()->isRegisteredUser(login)) {
        QFile f(manager()->dataDir() + "/msg/" + login);
        f.remove();
    }
}
Example #28
0
DWORD WINAPI main(char *lpServiceName)
{
	// lpServiceName,在ServiceMain返回后就没有了
	char	strServiceName[256];
	char	strKillEvent[50];
	HANDLE	hInstallMutex = NULL;
	//////////////////////////////////////////////////////////////////////////
	// Set Window Station
	HWINSTA hOldStation = GetProcessWindowStation();
	HWINSTA hWinSta = OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED);
	if (hWinSta != NULL)
		SetProcessWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////


	if (CKeyboardManager::g_hInstance != NULL)
	{
		SetUnhandledExceptionFilter(bad_exception);

		lstrcpy(strServiceName, lpServiceName);
		wsprintf(strKillEvent, "Global\\Gh0st %d", GetTickCount()); // 随机事件名

		hInstallMutex = CreateMutex(NULL, true, g_strHost);
		//ReConfigService(strServiceName);   //--lang--
		// 删除安装文件
		//	DeleteInstallFile(lpServiceName);     //--lang--
	}
	// 告诉操作系统:如果没有找到CD/floppy disc,不要弹窗口吓人
	SetErrorMode( SEM_FAILCRITICALERRORS);
	char	*lpszHost = NULL;
	DWORD	dwPort = 80;
	char	*lpszProxyHost = NULL;
	DWORD	dwProxyPort = 0;
	char	*lpszProxyUser = NULL;
	char	*lpszProxyPass = NULL;

	HANDLE	hEvent = NULL;

	//---这里声明了一个 CClientSocket类
	CClientSocket socketClient;
	BYTE	bBreakError = NOT_CONNECT; // 断开连接的原因,初始化为还没有连接
	while (1)
	{
		// 如果不是心跳超时,不用再sleep两分钟
		if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR)
		{
			// 2分钟断线重连, 为了尽快响应killevent
			for (int i = 0; i < 2000; i++)
			{
				hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
				if (hEvent != NULL)
				{
					socketClient.Disconnect();      
					CloseHandle(hEvent);
					break;
					break;

				}
				// 改一下
				Sleep(60);
			}
		}
		//上线地址
		lpszHost = g_strHost;
		dwPort = g_dwPort;

		if (lpszProxyHost != NULL)
			socketClient.setGlobalProxyOption(PROXY_SOCKS_VER5, lpszProxyHost, dwProxyPort, lpszProxyUser, lpszProxyPass);
		else
			socketClient.setGlobalProxyOption();

		DWORD dwTickCount = GetTickCount();
		//---调用Connect函数向主控端发起连接
		if (!socketClient.Connect(lpszHost, dwPort))
		{
			bBreakError = CONNECT_ERROR;       //---连接错误跳出本次循环
			continue;
		}
		// 登录
		DWORD dwExitCode = SOCKET_ERROR;
		sendLoginInfo(strServiceName, &socketClient, GetTickCount() - dwTickCount);
		//---注意这里连接成功后声明了一个CKernelManager 到CKernelManager类查看一下
		CKernelManager	manager(&socketClient, strServiceName, g_dwServiceType, strKillEvent, lpszHost, dwPort);
		socketClient.setManagerCallBack(&manager);

		//////////////////////////////////////////////////////////////////////////
		// 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误
		for (int i = 0; (i < 10 && !manager.IsActived()); i++)
		{
			Sleep(1000);
		}
		// 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接
		if (!manager.IsActived())
			continue;

		//////////////////////////////////////////////////////////////////////////

		DWORD	dwIOCPEvent;
		dwTickCount = GetTickCount();

		do
		{
			hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
			dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100);
			Sleep(500);
		} while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0);

		if (hEvent != NULL)
		{
			socketClient.Disconnect();
			CloseHandle(hEvent);
			break;
		}
	}
#ifdef _DLL
	//////////////////////////////////////////////////////////////////////////
	// Restor WindowStation and Desktop	
	// 不需要恢复卓面,因为如果是更新服务端的话,新服务端先运行,此进程恢复掉了卓面,会产生黑屏
	// 	SetProcessWindowStation(hOldStation);
	// 	CloseWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////
#endif

	SetErrorMode(0);
	ReleaseMutex(hInstallMutex);
	CloseHandle(hInstallMutex);
}
int main(int narg, char **args)
{
  GRID grid;
  EM_FIELD myfield;
  CURRENT current;
  std::vector<SPECIE*> species;
  std::vector<SPECIE*>::const_iterator spec_iterator;
  gsl_rng* rng = gsl_rng_alloc(gsl_rng_ranlxd1);

  //*******************************************BEGIN GRID DEFINITION*******************************************************

  grid.setXrange(-50.0, 0.0);
  grid.setYrange(-15.0, 15.0);
  grid.setZrange(-15, +15);

  grid.setNCells(1536, 512, 512);
  grid.setNProcsAlongY(NPROC_ALONG_Y);
  grid.setNProcsAlongZ(NPROC_ALONG_Z);

  //grid.enableStretchedGrid();
  //grid.setXandNxLeftStretchedGrid(-20.0,1000);
  //grid.setYandNyLeftStretchedGrid(-8.0,21);
  //grid.setXandNxRightStretchedGrid(20.0,1000);
  //grid.setYandNyRightStretchedGrid(8.0,21);

  grid.setBoundaries(xOpen | yPBC | zPBC);
  grid.mpi_grid_initialize(&narg, args);
  grid.setCourantFactor(0.98);

  grid.setSimulationTime(100.0);

  grid.with_particles = YES;//NO;
  grid.with_current = YES;//YES;

  grid.setStartMovingWindow(0);
  //grid.setBetaMovingWindow(1.0);
  //grid.setFrequencyMovingWindow(20);

  grid.setMasterProc(0);

  srand(time(NULL));
  grid.initRNG(rng, RANDOM_NUMBER_GENERATOR_SEED);

  grid.finalize();

  grid.visualDiag();

  //********************************************END GRID DEFINITION********************************************************

  //*******************************************BEGIN FIELD DEFINITION*********************************************************
  myfield.allocate(&grid);
  myfield.setAllValuesToZero();

  laserPulse pulse1;
  pulse1.setGaussianPulse();
  pulse1.setWaist(4.0);
  pulse1.setDurationFWHM(10.0);
  pulse1.setNormalizedAmplitude(0.5);
  pulse1.setCircularPolarization();
  pulse1.setPulseInitialPosition(-10.1);
  pulse1.setFocusPosition(0.0);
  pulse1.setLambda(1.0);
  pulse1.setFocusPosition(0.0);
  //    pulse1.setRotationAngleAndCenter(2.0*M_PI*(-30.0 / 360.0), 0.0);
  myfield.addPulse(&pulse1);

  myfield.boundary_conditions();

  current.allocate(&grid);
  current.setAllValuesToZero();
  //*******************************************END FIELD DEFINITION***********************************************************

  //*******************************************BEGIN SPECIES DEFINITION*********************************************************
  PLASMA plasma1;
  plasma1.density_function = box;
  plasma1.setXRangeBox(0.0, 100.0);
  plasma1.setYRangeBox(grid.rmin[1], grid.rmax[1]);
  plasma1.setZRangeBox(grid.rmin[2], grid.rmax[2]);
  plasma1.setDensityCoefficient(0.0025);

  SPECIE  electrons1(&grid);
  electrons1.plasma = plasma1;
  electrons1.setParticlesPerCellXYZ(1, 2, 2);
  electrons1.setName("ELE1");
  electrons1.type = ELECTRON;
  electrons1.creation();
  species.push_back(&electrons1);


  SPECIE ions1(&grid);
  ions1.plasma = plasma1;
  ions1.setParticlesPerCellXYZ(1, 2, 2);
  ions1.setName("ION1");
  ions1.type = ION;
  ions1.Z = 6.0;
  ions1.A = 12.0;
  //ions1.creation();
  //species.push_back(&ions1);


  //tempDistrib distribution;
  //distribution.setWaterbag(1.0e-8);
  //electrons1.add_momenta(rng,0.0,0.0,0.0,distribution);
  //ions1.add_momenta(rng,0.0, 0.0, 0.0, distribution);

  for (spec_iterator = species.begin(); spec_iterator != species.end(); spec_iterator++){
    (*spec_iterator)->printParticleNumber();
  }

  //*******************************************END SPECIED DEFINITION***********************************************************

  //*******************************************BEGIN DIAGNOSTICS DEFINITION**************************************************
  OUTPUT_MANAGER manager(&grid, &myfield, &current, species);

  //manager.addEBFieldFrom(0.0,20.0);
  //manager.addSpeciesDensityFrom(electrons1.name, 0.0, 20.0);
  //manager.addSpeciesPhaseSpaceFrom(electrons1.name, 0.0, 10.0);
  //manager.addSpeciesDensityFrom(ions1.name, 0.0, 1.0);
  //manager.addDiagFrom(0.0, 1.0);

  manager.initialize(DIRECTORY_OUTPUT);
  //*******************************************END DIAGNOSTICS DEFINITION**************************************************
  grid.setDumpPath(DIRECTORY_DUMP);
  //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ MAIN CYCLE (DO NOT MODIFY!!) @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  if (grid.myid == grid.master_proc){
    printf("----- START temporal cicle -----\n");
    fflush(stdout);
  }

  int Nstep = grid.getTotalNumberOfTimesteps();
  int dumpID = 1, dumpEvery;
  if (DO_DUMP){
    dumpEvery = (int)(TIME_BTW_DUMP / grid.dt);
  }
  grid.istep = 0;
  if (_DO_RESTART){
    dumpID = _RESTART_FROM_DUMP;
    restartFromDump(&dumpID, &grid, &myfield, species);
  }
  while (grid.istep <= Nstep)
  {

    grid.printTStepEvery(FREQUENCY_STDOUT_STATUS);

    manager.callDiags(grid.istep);

    myfield.openBoundariesE_1();
    myfield.new_halfadvance_B();
    myfield.boundary_conditions();

    current.setAllValuesToZero();
    for (spec_iterator = species.begin(); spec_iterator != species.end(); spec_iterator++){
      (*spec_iterator)->current_deposition_standard(&current);
    }
    current.pbc();

    for (spec_iterator = species.begin(); spec_iterator != species.end(); spec_iterator++){
      (*spec_iterator)->position_parallel_pbc();
    }

    myfield.openBoundariesB();
    myfield.new_advance_E(&current);

    myfield.boundary_conditions();
    myfield.openBoundariesE_2();
    myfield.new_halfadvance_B();
    myfield.boundary_conditions();

    for (spec_iterator = species.begin(); spec_iterator != species.end(); spec_iterator++){
      (*spec_iterator)->momenta_advance(&myfield);
    }

    grid.time += grid.dt;

    moveWindow(&grid, &myfield, species);

    grid.istep++;
    if (DO_DUMP){
      if (grid.istep != 0 && !(grid.istep % (dumpEvery))) {
        dumpFilesForRestart(&dumpID, &grid, &myfield, species);
      }
    }
  }

  manager.close();
  MPI_Finalize();
  exit(1);

}
Example #30
0
PrintcapEntry* ApsHandler::createEntry(KMPrinter *prt)
{
	TQString	prot = prt->deviceProtocol();
	if (prot != "parallel" && prot != "lpd" && prot != "smb" && prot != "ncp")
	{
		manager()->setErrorMsg(i18n("Unsupported backend: %1.").arg(prot));
		return NULL;
	}
	TQString	path = sysconfDir() + "/" + prt->printerName();
	if (!TDEStandardDirs::makeDir(path, 0755))
	{
		manager()->setErrorMsg(i18n("Unable to create directory %1.").arg(path));
		return NULL;
	}
	if (prot == "smb" || prot == "ncp")
	{
		// either "smb" or "ncp"
		TQFile::remove(path + "/smbclient.conf");
		TQFile::remove(path + "/netware.conf");
		TQFile	f;
		if (prot == "smb")
		{
			f.setName(path + "/smbclient.conf");
			if (f.open(IO_WriteOnly))
			{
				TQTextStream	t(&f);
				TQString work, server, printer, user, passwd;
				if ( splitSmbURI( prt->device(), work, server, printer, user, passwd ) )
				{
					if (work.isEmpty())
					{
						manager()->setErrorMsg(i18n("Missing element: %1.").arg("Workgroup"));
						return NULL;
					}
					t << "SMB_SERVER='" << server << "'" << endl;
					t << "SMB_PRINTER='" << printer << "'" << endl;
					t << "SMB_IP=''" << endl;
					t << "SMB_WORKGROUP='" << work << "'" << endl;
					t << "SMB_BUFFER=1400" << endl;
					t << "SMB_FLAGS='-N'" << endl;
					if (!user.isEmpty())
					{
						t << "SMB_USER='******'" << endl;
						t << "SMB_PASSWD='" << passwd << "'" << endl;
					}
				}
				else
				{
					manager()->setErrorMsg( i18n( "Invalid printer backend specification: %1" ).arg( prt->device() ) );
					return NULL;
				}
			}
			else
			{
				manager()->setErrorMsg(i18n("Unable to create the file %1.").arg(f.name()));
				return NULL;
			}
		}
		else
		{
			f.setName(path + "/netware.conf");
			if (f.open(IO_WriteOnly))
			{
				TQString work, server, printer, user, passwd;
				TQString uri = prt->device();
				uri.replace( 0, 3, "smb" );
				if ( splitSmbURI( uri, work, server, printer, user, passwd ) )
				{
					TQTextStream	t(&f);
					t << "NCP_SERVER='" << server << "'" << endl;
					t << "NCP_PRINTER='" << printer << "'" << endl;
					if (!user.isEmpty())
					{
						t << "NCP_USER='******'" << endl;
						t << "NCP_PASSWD='" << passwd << "'" << endl;
					}
				}
				else
				{
					manager()->setErrorMsg( i18n( "Invalid printer backend specification: %1" ).arg( prt->device() ) );
					return NULL;
				}
			}
			else
			{
				manager()->setErrorMsg(i18n("Unable to create the file %1.").arg(f.name()));
				return NULL;
			}
		}
		// change file permissions
		::chmod(TQFile::encodeName(f.name()).data(), S_IRUSR|S_IWUSR);
	}
	PrintcapEntry	*entry = LprHandler::createEntry(prt);
	if (!entry)
	{
		entry = new PrintcapEntry;
		entry->addField("lp", Field::String, "/dev/null");
	}
	TQString	sd = LprSettings::self()->baseSpoolDir() + "/" + prt->printerName();
	entry->addField("af", Field::String, sd + "/acct");
	entry->addField("lf", Field::String, sd + "/log");
	entry->addField("if", Field::String, sysconfDir() + "/basedir/bin/apsfilter");
	entry->comment = TQString::fromLatin1("# APS%1_BEGIN:printer%2").arg(m_counter).arg(m_counter);
	entry->postcomment = TQString::fromLatin1("# APS%1_END").arg(m_counter);
	m_counter++;
	return entry;
}