void logProcessMonitoringInit(char* processName, pid_t pid)
{
    LogReport report;
    char* message = stringJoin("Initializing monitoring of process '", processName);
    char* message2 = stringJoin(message, "' (PID ");
    free(message);
    message = stringNumberJoin(message2, (int)pid);
    free(message2);
    message2 = stringJoin(message, ")");
    free(message);
    message = NULL;
    report.message = message2;
    report.type = ACTION;
    saveLogReport(report, false);
    free(message2);
}
Exemple #2
0
/*
 *  captureProtoSignature()
 *
 *      Input:  sa (output from cpp, by line)
 *              start (starting index to search; never a comment line)
 *              stop (index of line on which pattern is completed)
 *              charindex (char index of completing ')' character)
 *      Return: cleanstr (prototype string), or NULL on error
 *
 *  Notes:
 *      (1) Return all characters, ending with a ';' after the ')'
 */
static char *
captureProtoSignature(SARRAY  *sa,
                      l_int32  start,
                      l_int32  stop,
                      l_int32  charindex)
{
char    *str, *newstr, *protostr, *cleanstr;
SARRAY  *sap;
l_int32  i;

    PROCNAME("captureProtoSignature");

    if (!sa)
        return (char *)ERROR_PTR("sa not defined", procName, NULL);

    sap = sarrayCreate(0);
    for (i = start; i < stop; i++) {
        str = sarrayGetString(sa, i, L_COPY);
        sarrayAddString(sap, str, L_INSERT);
    }
    str = sarrayGetString(sa, stop, L_COPY);
    str[charindex + 1] = '\0';
    newstr = stringJoin(str, ";");
    sarrayAddString(sap, newstr, L_INSERT);
    LEPT_FREE(str);
    protostr = sarrayToString(sap, 2);
    sarrayDestroy(&sap);
    cleanstr = cleanProtoSignature(protostr);
    LEPT_FREE(protostr);

    return cleanstr;
}
Exemple #3
0
/*
 *  parseForProtos()
 *
 *      Input:  filein (output of cpp)
 *              prestring (<optional> string that prefaces each decl;
 *                        use NULL to omit)
 *      Return: parsestr (string of function prototypes), or NULL on error
 *
 *  Notes:
 *      (1) We parse the output of cpp:
 *              cpp -ansi <filein> 
 *          Three plans were attempted, with success on the third. 
 *      (2) Plan 1.  A cursory examination of the cpp output indicated that
 *          every function was preceeded by a cpp comment statement.
 *          So we just need to look at statements beginning after comments.
 *          Unfortunately, this is NOT the case.  Some functions start
 *          without cpp comment lines, typically when there are no
 *          comments in the source that immediately precede the function.
 *      (3) Plan 2.  Consider the keywords in the language that start
 *          parts of the cpp file.  Some, like 'typedef', 'enum',
 *          'union' and 'struct', are followed after a while by '{',
 *          and eventually end with '}, plus an optional token and a
 *          final ';'  Others, like 'extern' and 'static', are never
 *          the beginnings of global function definitions.   Function
 *          prototypes have one or more sets of '(' followed eventually
 *          by a ')', and end with ';'.  But function definitions have
 *          tokens, followed by '(', more tokens, ')' and then
 *          immediately a '{'.  We would generate a prototype from this
 *          by adding a ';' to all tokens up to the ')'.  So we use
 *          these special tokens to decide what we are parsing.  And
 *          whenever a function definition is found and the prototype
 *          extracted, we skip through the rest of the function
 *          past the corresponding '}'.  This token ends a line, and
 *          is often on a line of its own.  But as it turns out,
 *          the only keyword we need to consider is 'static'.
 *      (4) Plan 3.  Consider the parentheses and braces for various
 *          declarations.  A struct, enum, or union has a pair of
 *          braces followed by a semicolon.  They cannot have parentheses
 *          before the left brace, but a struct can have lots of parentheses
 *          within the brace set.  A function prototype has no braces.
 *          A function declaration can have sets of left and right
 *          parentheses, but these are followed by a left brace.
 *          So plan 3 looks at the way parentheses and braces are
 *          organized.  Once the beginning of a function definition
 *          is found, the prototype is extracted and we search for
 *          the ending right brace.
 *      (5) To find the ending right brace, it is necessary to do some
 *          careful parsing.  For example, in this file, we have
 *          left and right braces as characters, and these must not
 *          be counted.  Somewhat more tricky, the file fhmtauto.c
 *          generates code, and includes a right brace in a string.
 *          So we must not include braces that are in strings.  But how
 *          do we know if something is inside a string?  Keep state,
 *          starting with not-inside, and every time you hit a double quote
 *          that is not escaped, toggle the condition.  Any brace
 *          found in the state of being within a string is ignored.
 *      (6) When a prototype is extracted, it is put in a canonical
 *          form (i.e., cleaned up).  Finally, we check that it is
 *          not static and save it.  (If static, it is ignored).
 *      (7) The @prestring for unix is NULL; it is included here so that
 *          you can use Microsoft's declaration for importing or
 *          exporting to a dll.  See environ.h for examples of use.
 *          Here, we set: @prestring = "LEPT_DLL ".  Note in particular
 *          the space character that will separate 'LEPT_DLL' from
 *          the standard unix prototype that follows.
 */
char *
parseForProtos(const char *filein,
               const char *prestring)
{
char    *strdata, *str, *newstr, *parsestr, *secondword;
l_int32  nbytes, start, next, stop, charindex, found;
SARRAY  *sa, *saout, *satest;

    PROCNAME("parseForProtos");

    if (!filein)
        return (char *)ERROR_PTR("filein not defined", procName, NULL);

        /* Read in the cpp output into memory, one string for each
         * line in the file, omitting blank lines.  */
    strdata = (char *)arrayRead(filein, &nbytes);
    sa = sarrayCreateLinesFromString(strdata, 0);

    saout = sarrayCreate(0);
    next = 0;
    while (1) {  /* repeat after each non-static prototype is extracted */
        searchForProtoSignature(sa, next, &start, &stop, &charindex, &found);
        if (!found)
            break;
/*        fprintf(stderr, "  start = %d, stop = %d, charindex = %d\n",
                start, stop, charindex); */
        str = captureProtoSignature(sa, start, stop, charindex);

            /* Make sure it is not static.  Note that 'extern' has
             * been prepended to the prototype, so the 'static'
             * keyword, if it exists, would be the second word. */
        satest = sarrayCreateWordsFromString(str);
        secondword = sarrayGetString(satest, 1, 0);
        if (strcmp(secondword, "static")) {  /* not static */
            if (prestring) {  /* prepend it to the prototype */
                newstr = stringJoin(prestring, str);
                sarrayAddString(saout, newstr, L_INSERT);
                FREE(str);
            }
            else
                sarrayAddString(saout, str, L_INSERT);
        }
        else
            FREE(str);
        sarrayDestroy(&satest);

        skipToEndOfFunction(sa, stop, charindex, &next);
        if (next == -1) break;
    }

        /* Flatten into a string with newlines between prototypes */
    parsestr = sarrayToString(saout, 1);
    FREE(strdata);
    sarrayDestroy(&sa);
    sarrayDestroy(&saout);

    return parsestr;
}
void logProcessKill(pid_t pid, const char* name, uint32_t duration)
{
    LogReport report;
    char* message = stringNumberJoin("PID ", pid);
    char* message2 = stringJoin(message, " (");
    free(message);
    message = stringJoin(message2, name);
    free(message2);
    message2 = stringJoin(message, ") killed after exceeding ");
    free(message);
    message = stringULongJoin(message2, duration);
    free(message2);
    message2 = stringJoin(message, " seconds");
    free(message);
    report.message = message2;
    report.type = ACTION;
    saveLogReport(report, false);
    free(report.message);
}
void logSelfDying(pid_t pid, const char* name, uint32_t duration)
{
    LogReport report;
    char* message = stringNumberJoin("PID ", pid);
    char* message2 = stringJoin(message, " (");
    free(message);
    message = stringJoin(message2, name);
    free(message2);
    message2 = stringJoin(message, ") died on its own by ");
    free(message);
    message = stringULongJoin(message2, duration);
    free(message2);
    message2 = stringJoin(message, " seconds");
    free(message);
    report.message = message2;
    report.type = INFO;
    saveLogReport(report, false);
    free(report.message);
}
Exemple #6
0
/*!
 * \brief   regTestCleanup()
 *
 * \param[in]    rp regression test parameters
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This copies anything written to the temporary file to the
 *          output file /tmp/lept/reg_results.txt.
 * </pre>
 */
l_int32
regTestCleanup(L_REGPARAMS  *rp)
{
char     result[512];
char    *results_file;  /* success/failure output in 'compare' mode */
char    *text, *message;
l_int32  retval;
size_t   nbytes;

    PROCNAME("regTestCleanup");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);

    fprintf(stderr, "Time: %7.3f sec\n", stopTimerNested(rp->tstart));
    fprintf(stderr, "################################################\n");

        /* If generating golden files or running in display mode, release rp */
    if (!rp->fp) {
        LEPT_FREE(rp->testname);
        LEPT_FREE(rp->tempfile);
        LEPT_FREE(rp);
        return 0;
    }

        /* Compare mode: read back data from temp file */
    fclose(rp->fp);
    text = (char *)l_binaryRead(rp->tempfile, &nbytes);
    LEPT_FREE(rp->tempfile);
    if (!text) {
        rp->success = FALSE;
        LEPT_FREE(rp->testname);
        LEPT_FREE(rp);
        return ERROR_INT("text not returned", procName, 1);
    }

        /* Prepare result message */
    if (rp->success)
        snprintf(result, sizeof(result), "SUCCESS: %s_reg\n", rp->testname);
    else
        snprintf(result, sizeof(result), "FAILURE: %s_reg\n", rp->testname);
    message = stringJoin(text, result);
    LEPT_FREE(text);
    results_file = genPathname("/tmp/lept", "reg_results.txt");
    fileAppendString(results_file, message);
    retval = (rp->success) ? 0 : 1;
    LEPT_FREE(results_file);
    LEPT_FREE(message);

    LEPT_FREE(rp->testname);
    LEPT_FREE(rp);
    return retval;
}
/*!
 *  pixAddText()
 *
 *      Input:  pix
 *              textstring
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This adds the new textstring to any existing text.
 *      (2) Either or both the existing text and the new text
 *          string can be null.
 */
l_int32
pixAddText(PIX         *pix,
           const char  *textstring)
{
char  *newstring;

    PROCNAME("pixAddText");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    newstring = stringJoin(pixGetText(pix), textstring);
    stringReplace(&pix->text, newstring);
    FREE(newstring);
    return 0;
}
Exemple #8
0
/*!
 *  regTestCleanup()
 *
 *      Input:  argc (to regtest: either 1 or 2)
 *              argv (to regtest: if @argc == 2, @argv[1] is either
 *                    "generate" or a log file name)
 *              fp (stream that was used writing to a temporary file;
 *                  null for the "generate" case)
 *              success (overall for this reg test)
 *              rp (regression test params; can be null)
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This outputs anything written to the temporary file and
 *          closes the stream to that file.
 *      (2) If a rp struct is made in regTestSetup(), it must be
 *          passed in here for destruction.
 */
l_int32
regTestCleanup(l_int32       argc,
               char        **argv,
               FILE         *fp,
               l_int32       success,
               L_REGPARAMS  *rp)
{
char     result[128];
char    *tempname, *text, *message;
l_int32  nbytes;

    PROCNAME("regTestCleanup");

    if (!fp) {  /* for generating golden files; release rp if it exists */
        if (rp) FREE(rp);
        return 0;
    }
    fclose(fp);

        /* Read back data from temp file */
    tempname = genTempFilename("/tmp", "regtest_output.txt", 1);
    text = (char *)arrayRead(tempname, &nbytes);
    FREE(tempname);
    if (!text) {
        if (rp) FREE(rp);
        return ERROR_INT("text not returned", procName, 1);
    }

        /* Prepare result message */
    if (rp)  /* if either is 0, success == FALSE */
        success = rp->success && success;
    if (success)
        snprintf(result, sizeof(result), "SUCCESS: %s\n", argv[0]);
    else
        snprintf(result, sizeof(result), "FAILURE: %s\n", argv[0]);
    message = stringJoin(text, result);
    FREE(text);

    if (argc == 1)
        fprintf(stderr, "%s", message);
    else
        fileAppendString(argv[1], message);
    FREE(message);

    if (rp) FREE(rp);
    return 0;
}
void BinaryOutput::commit(bool flush) {
    debugAssertM(! m_committed, "Cannot commit twice");
    m_committed = true;
    debugAssertM(m_beginEndBits == 0, "Missing endBits before commit");

    if (m_filename == "<memory>") {
        return;
    }

    // Make sure the directory exists.
    std::string root, base, ext, path;
    Array<std::string> pathArray;
    parseFilename(m_filename, root, pathArray, base, ext); 

    path = root + stringJoin(pathArray, '/');
    if (! FileSystem::exists(path, false)) {
        FileSystem::createDirectory(path);
    }

    const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb";

    alwaysAssertM(m_filename != "<memory>", "Writing to memory file");
    FILE* file = FileSystem::fopen(m_filename.c_str(), mode);

    if (! file) {
        logPrintf("Error %d while trying to open \"%s\"\n", errno, m_filename.c_str());
    }
    m_ok = (file != NULL) && m_ok;

    if (m_ok) {
        debugAssertM(file, std::string("Could not open '") + m_filename + "'");

        if (m_buffer != NULL) {
            m_alreadyWritten += m_bufferLen;

            size_t success = fwrite(m_buffer, m_bufferLen, 1, file);
            (void)success;
            debugAssertM(success == 1, std::string("Could not write to '") + m_filename + "'");
        }
        if (flush) {
            fflush(file);
        }
        FileSystem::fclose(file);
        file = NULL;
    }
}
Exemple #10
0
void BinaryOutput::commit(bool flush) {
    debugAssertM(! m_committed, "Cannot commit twice");
    m_committed = true;
    debugAssertM(m_beginEndBits == 0, "Missing endBits before commit");

    // Make sure the directory exists.
    std::string root, base, ext, path;
    Array<std::string> pathArray;
    parseFilename(m_filename, root, pathArray, base, ext); 

    path = root + stringJoin(pathArray, '/');
    if (! fileExists(path, false)) {
        createDirectory(path);
    }

    const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb";

    FILE* file = fopen(m_filename.c_str(), mode);

    m_ok = (file != NULL) && m_ok;

    if (m_ok) {
        debugAssertM(file, std::string("Could not open '") + m_filename + "'");

        if (m_buffer != NULL) {
            m_alreadyWritten += m_bufferLen;

            int success = fwrite(m_buffer, m_bufferLen, 1, file);
            (void)success;
            debugAssertM(success == 1, std::string("Could not write to '") + m_filename + "'");
        }
        if (flush) {
            fflush(file);
        }
        fclose(file);
        file = NULL;
    }
}
Exemple #11
0
main(int    argc,
     char **argv)
{
PIX         *pixs;
char        *filein, *fileout, *base, *ext;
const char  *format;
char         error_msg[] = "Valid formats: BMP, JPEG, PNG, TIFF, TIFF_G4, PNM";
l_int32      d;
static char  mainName[] = "convertformat";

    if (argc != 3 && argc != 4) {
        fprintf(stderr, "Syntax: convertformat filein fileout [format]\n");
        fprintf(stderr, "%s\n", error_msg);
        fprintf(stderr, "If you don't specify a format, the output file needs");
	fprintf(stderr, " an extension such as:\n");
	fprintf(stderr, " .bmp, .jpg, .png, .tif or .pnm\n");
        return 1;
    }

    filein = argv[1];
    fileout = argv[2];

    if (argc == 3) {
        splitPathAtExtension(fileout, NULL, &ext);
        if (!strcmp(ext, ".bmp"))
            format = "BMP";
        else if (!strcmp(ext, ".jpg"))
            format = "JPEG";
        else if (!strcmp(ext, ".png"))
            format = "PNG";
        else if (!strcmp(ext, ".tif"))
            format = "TIFF_G4";
        else if (!strcmp(ext, ".pnm"))
            format = "PNM";
        else
            return ERROR_INT(error_msg, mainName, 1);
        lept_free(ext);
    }
    else
        format = argv[3];

    pixs = pixRead(filein);
    d = pixGetDepth(pixs);
    if (d != 1 && !strcmp(format, "TIFF_G4")) {
        L_WARNING("can't convert to tiff_g4; converting to tiff", mainName);
        format = "TIFF";
    }
    if (d < 8 && !strcmp(format, "JPEG")) {
        L_WARNING("can't convert to jpeg; converting to png", mainName);
        splitPathAtExtension(fileout, &base, &ext);
        fileout = stringJoin(base, ".png");
        format = "PNG";
    }

    if (strcmp(format, "BMP") == 0)
        pixWrite(fileout, pixs, IFF_BMP);
    else if (strcmp(format, "JPEG") == 0)
        pixWrite(fileout, pixs, IFF_JFIF_JPEG);
    else if (strcmp(format, "PNG") == 0)
        pixWrite(fileout, pixs, IFF_PNG);
    else if (strcmp(format, "TIFF") == 0)
        pixWrite(fileout, pixs, IFF_TIFF_ZIP);
    else if (strcmp(format, "TIFF_G4") == 0)
        pixWrite(fileout, pixs, IFF_TIFF_G4);
    else if (strcmp(format, "PNM") == 0)
        pixWrite(fileout, pixs, IFF_PNM);
    else
        return ERROR_INT(error_msg, mainName, 1);

    return 0;
}
int main(int    argc,
         char **argv)
{
PIX         *pixs;
char        *filein, *fileout, *base, *ext;
const char  *formatstr;
l_int32      format;
l_int32      d;
static char  mainName[] = "convertformat";

    if (argc != 3 && argc != 4) {
        fprintf(stderr, "Syntax: convertformat filein fileout [format]\n"
                        "If you don't specify a format, the output file\n"
                        "needs one of these seven extensions:\n"
                        "   bmp, jpg, png, tif, pnm, gif, webp\n");
        return 1;
    }

    filein = argv[1];
    fileout = argv[2];

    if (argc == 3) {
        splitPathAtExtension(fileout, NULL, &ext);
        if (!strcmp(ext, ".bmp"))
            format = IFF_BMP;
        else if (!strcmp(ext, ".jpg"))
            format = IFF_JFIF_JPEG;
        else if (!strcmp(ext, ".png"))
            format = IFF_PNG;
        else if (!strcmp(ext, ".tif"))  /* requesting g4-tiff binary comp */
            format = IFF_TIFF_G4;
        else if (!strcmp(ext, ".pnm"))
            format = IFF_PNM;
        else if (!strcmp(ext, ".gif"))
            format = IFF_GIF;
        else if (!strcmp(ext, ".webp"))
            format = IFF_WEBP;
        else {
            return ERROR_INT(
                "Valid extensions: bmp, jpg, png, tif, pnm, gif, webp",
                mainName, 1);
        }
        lept_free(ext);
    }
    else {
        formatstr = argv[3];
        if (!strcmp(formatstr, "BMP"))
            format = IFF_BMP;
        else if (!strcmp(formatstr, "JPEG"))
            format = IFF_JFIF_JPEG;
        else if (!strcmp(formatstr, "PNG"))
            format = IFF_PNG;
        else if (!strcmp(formatstr, "TIFF"))
            format = IFF_TIFF_G4;
        else if (!strcmp(formatstr, "PNM"))
            format = IFF_PNM;
        else if (!strcmp(formatstr, "GIF"))
            format = IFF_GIF;
        else if (!strcmp(formatstr, "WEBP"))
            format = IFF_WEBP;
        else {
            return ERROR_INT(
                "Valid formats: BMP, JPEG, PNG, TIFF, PNM, GIF, WEBP",
                mainName, 1);
        }
    }

    if ((pixs = pixRead(filein)) == NULL) {
        L_ERROR("read fail for %s\n", mainName, filein);
        return 1;
    }

    d = pixGetDepth(pixs);
    if (d != 1 && format == IFF_TIFF_G4) {
        L_WARNING("can't convert to tiff_g4; converting to png\n", mainName);
        format = IFF_PNG;
    }
    if (d < 8 && format == IFF_JFIF_JPEG) {
        L_WARNING("can't convert to jpeg; converting to png\n", mainName);
        splitPathAtExtension(fileout, &base, &ext);
        fileout = stringJoin(base, ".png");
        format = IFF_PNG;
    }
    if (d < 8 && format == IFF_WEBP) {
        L_WARNING("can't convert to webp; converting to png\n", mainName);
        splitPathAtExtension(fileout, &base, &ext);
        fileout = stringJoin(base, ".png");
        format = IFF_PNG;
    }

    pixWrite(fileout, pixs, format);
    return 0;
}
Exemple #13
0
void  App::onGraphics (RenderDevice *rd, Array< SurfaceRef > &posed3D, Array< Surface2DRef > &posed2D) {
    rd->setColorClearValue(Color3::white());
    rd->clear();

    doFunStuff();

    rd->push2D();

        int w = rd->width();
        int h = rd->height();

        ///////////////////////////////////////
        // Left panel
#       define LABEL(str) p.y += titleFont->draw2D(rd, str, p - Vector2((float)w * 0.0075f, 0), s * 2, Color3::white() * 0.4f).y
#       define PRINT(str) p.y += reportFont->draw2D(rd, str, p, s, Color3::black()).y

        int x0 = int(w * 0.015f);
        // Cursor position
        Vector2 p(x0, h * 0.02f);

        // Font size
        float s = w * 0.013;

        LABEL("Shaders");
        PRINT(std::string("Combiners: ") + combineShader);
        PRINT(std::string("Assembly:   ") + asmShader);
        PRINT(std::string("GLSL:         ") + glslShader);

        p.y += s * 2;
        LABEL("Extensions");
        PRINT(std::string("FSAA:                           ") + ((GLCaps::supports("WGL_ARB_multisample") || GLCaps::supports("GL_ARB_multisample")) ? "Yes" : "No"));
        PRINT(std::string("Two-sided Stencil:        ") + ((GLCaps::supports_two_sided_stencil() ? "Yes" : "No")));
        PRINT(std::string("Stencil Wrap:               ") + (GLCaps::supports("GL_EXT_stencil_wrap") ? "Yes" : "No"));
        PRINT(std::string("Texture Compression: ") + (GLCaps::supports("GL_EXT_texture_compression_s3tc") ? "Yes" : "No"));
        PRINT(std::string("Shadow Maps:             ") + (GLCaps::supports("GL_ARB_shadow") ? "Yes" : "No"));
        PRINT(std::string("Frame Buffer Object:   ") + (GLCaps::supports("GL_EXT_framebuffer_object") ? "Yes" : "No"));
        PRINT(std::string("Vertex Arrays:              ") + (GLCaps::supports_GL_ARB_vertex_buffer_object() ? "Yes" : "No"));
        
            
        ///////////////////////////////////////
        // Right Panel
        x0 = int(w * 0.6f);
        // Cursor position
        p = Vector2(x0, h * 0.02f);

        // Graphics Card
        LABEL("Graphics Card");
        rd->setTexture(0, cardLogo);
        Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y, s * 5, s * 5), rd);
        rd->setTexture(0, NULL);

        PRINT(GLCaps::vendor().c_str());
        PRINT(GLCaps::renderer().c_str());
        PRINT(format("Driver Version %s", GLCaps::driverVersion().c_str()));

#       ifdef G3D_WIN32        
            PRINT(format("%d MB Video RAM", DXCaps::videoMemorySize() / (1024 * 1024)));
            {
                uint32 ver = DXCaps::version();
                PRINT(format("DirectX %d.%d", ver/100, ver%100));
            }
#       endif

        p.y += s * 2;

        // Processor
        LABEL("Processor");
        rd->setTexture(0, chipLogo);
        Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y, s * 5, s * 5), rd);
        rd->setTexture(0, NULL);

        PRINT(System::cpuVendor().c_str());
        PRINT(System::cpuArchitecture().c_str());

        Array<std::string> features;
        if (System::has3DNow()) {
            features.append("3DNow");
        }
        if (System::hasMMX()) {
            features.append("MMX");
        }
        if (System::hasSSE()) {
            features.append("SSE");
        }
        if (System::hasSSE2()) {
            features.append("SSE2");
        }
        if (chipSpeed != "") {
            PRINT(chipSpeed + " " + stringJoin(features, '/'));
        } else {
            PRINT(stringJoin(features, '/'));
        }

        p.y += s * 2;

        // Operating System
        LABEL("OS");
        rd->setTexture(0, osLogo);
        Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y - s * 2, s * 5, s * 5), rd);
        rd->setTexture(0, NULL);


        if (beginsWith(System::operatingSystem(), "Windows 5.0")) {
            PRINT("Windows 2000");
        } else if (beginsWith(System::operatingSystem(), "Windows 5.1")) {
            PRINT("Windows XP");
        }
        PRINT(System::operatingSystem().c_str());

        p.y += s * 3;

        x0 = int(w - s * 10);
        titleFont->draw2D(rd, "Features", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f);
        p.y += reportFont->draw2D(rd, format("f%d", featureRating), Vector2(x0, p.y), s*2, Color3::red() * 0.5).y;
        drawBar(rd, featureRating, p);

        // Designed to put NV40 at 50
        performanceRating = log(rd->stats().frameRate) * 15.0f;

        p.y += s * 4;
        performanceButton =
            Rect2D::xywh(p,
                         titleFont->draw2D(rd, "Speed", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f));

        {
            float spd = iRound(performanceRating * 10) / 10.0f;
            p.y += reportFont->draw2D(rd, format("%5.1f", spd), Vector2(x0 - s*2, p.y), s*2, Color3::red() * 0.5).y;
        }
        drawBar(rd, (int)min(performanceRating, 100.0f), p);

        p.y += s * 4;
        titleFont->draw2D(rd, "Quality", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f);
        p.y += reportFont->draw2D(rd, quality(bugCount), Vector2(x0, p.y), s*2, Color3::red() * 0.5f).y;
        drawBar(rd, iClamp(100 - bugCount * 10, 0, 100), p);

#       undef PRINT


        p.y = h - 50;
#       define PRINT(str) p.y += reportFont->draw2D(rd, str, p, 8, Color3::black()).y;

        PRINT("These ratings are based on the performance of G3D apps.");
        PRINT("They may not be representative of overall 3D performance.");
        PRINT("Speed is based on both processor and graphics card. Upgrading");
        PRINT("your graphics driver may improve Quality and Features.");
#       undef  PRINT
#       undef LABEL

        switch (popup) {
        case NONE:
            break;

        case PERFORMANCE:
            {
                //  Draw the popup box
                Rect2D box = drawPopup("Performance Details");
                p.x = box.x0() + 10;
                p.y = box.y0() + 30;

                Vector2 spacing(box.width() / 6.5, 0);

                std::string str;

                float factor = 3 * vertexPerformance.numTris / 1e6;

#               define PRINT(cap, val)   \
                    reportFont->draw2D(rd, cap, p, s, Color3::black());\
                    reportFont->draw2D(rd, (vertexPerformance.val[0] > 0) ? \
                        format("%5.1f", vertexPerformance.val[0]) : \
                        std::string("X"), p + spacing * 3, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\
                    reportFont->draw2D(rd, (vertexPerformance.val[0] > 0) ? \
                        format("%5.1f", factor * vertexPerformance.val[0]) : \
                        std::string("X"), p + spacing * 4, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\
                    reportFont->draw2D(rd, (vertexPerformance.val[1] > 0) ? \
                        format("%5.1f", vertexPerformance.val[1]) : \
                        std::string("X"), p + spacing * 5, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\
                    p.y += reportFont->draw2D(rd, (vertexPerformance.val[1] > 0) ? \
                        format("%5.1f", factor * vertexPerformance.val[1]) : \
                        std::string("X"), p + spacing * 6, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT).y;

                reportFont->draw2D(rd, "Incoherent", p + spacing * 3.5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT);
                p.y += reportFont->draw2D(rd, "Coherent", p + spacing * 5.5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y;

                reportFont->draw2D(rd, "FPS*", p + spacing * 3, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT);
                reportFont->draw2D(rd, "MVerts/s", p + spacing * 4, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT);
                reportFont->draw2D(rd, "FPS*", p + spacing * 5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y;
                p.y += reportFont->draw2D(rd, "MVerts/s", p + spacing * 6, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y;
                
                PRINT("glBegin/glEnd", beginEndFPS);
                PRINT("glDrawElements", drawElementsRAMFPS); 
                PRINT("  + VBO", drawElementsVBOFPS);
                PRINT("  + uint16", drawElementsVBO16FPS);
                PRINT("  + gl interleave", drawElementsVBOIFPS);
                PRINT("  + manual interleave", drawElementsVBOIMFPS);
                PRINT("  (without shading)", drawElementsVBOPeakFPS);

                reportFont->draw2D(rd, "glDrawArrays", p, s, Color3::black());
                reportFont->draw2D(rd, (vertexPerformance.drawArraysVBOPeakFPS > 0) ? \
                    format("%5.1f", vertexPerformance.drawArraysVBOPeakFPS) : \
                    std::string("X"), p + spacing * 5, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\
                p.y += reportFont->draw2D(rd, (vertexPerformance.drawArraysVBOPeakFPS > 0) ? \
                    format("%5.1f", factor * vertexPerformance.drawArraysVBOPeakFPS) : \
                    std::string("X"), p + spacing * 6, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT).y;

#               undef PRINT

                p.y += s;
                p.y += reportFont->draw2D(rd, format("* FPS at %d k polys/frame.", 
                    iRound(vertexPerformance.numTris / 1000.0)), p + Vector2(20, 0), s, Color3::black()).y;
            }
        }

    rd->pop2D();
}
Exemple #14
0
/*
 *  parseForProtos()
 *
 *      Input:  filein (output of cpp)
 *              prestring (<optional> string that prefaces each decl;
 *                        use NULL to omit)
 *      Return: parsestr (string of function prototypes), or NULL on error
 *
 *  Notes:
 *      (1) We parse the output of cpp:
 *              cpp -ansi <filein>
 *          Three plans were attempted, with success on the third.
 *      (2) Plan 1.  A cursory examination of the cpp output indicated that
 *          every function was preceded by a cpp comment statement.
 *          So we just need to look at statements beginning after comments.
 *          Unfortunately, this is NOT the case.  Some functions start
 *          without cpp comment lines, typically when there are no
 *          comments in the source that immediately precede the function.
 *      (3) Plan 2.  Consider the keywords in the language that start
 *          parts of the cpp file.  Some, like 'typedef', 'enum',
 *          'union' and 'struct', are followed after a while by '{',
 *          and eventually end with '}, plus an optional token and a
 *          final ';'  Others, like 'extern' and 'static', are never
 *          the beginnings of global function definitions.   Function
 *          prototypes have one or more sets of '(' followed eventually
 *          by a ')', and end with ';'.  But function definitions have
 *          tokens, followed by '(', more tokens, ')' and then
 *          immediately a '{'.  We would generate a prototype from this
 *          by adding a ';' to all tokens up to the ')'.  So we use
 *          these special tokens to decide what we are parsing.  And
 *          whenever a function definition is found and the prototype
 *          extracted, we skip through the rest of the function
 *          past the corresponding '}'.  This token ends a line, and
 *          is often on a line of its own.  But as it turns out,
 *          the only keyword we need to consider is 'static'.
 *      (4) Plan 3.  Consider the parentheses and braces for various
 *          declarations.  A struct, enum, or union has a pair of
 *          braces followed by a semicolon.  They cannot have parentheses
 *          before the left brace, but a struct can have lots of parentheses
 *          within the brace set.  A function prototype has no braces.
 *          A function declaration can have sets of left and right
 *          parentheses, but these are followed by a left brace.
 *          So plan 3 looks at the way parentheses and braces are
 *          organized.  Once the beginning of a function definition
 *          is found, the prototype is extracted and we search for
 *          the ending right brace.
 *      (5) To find the ending right brace, it is necessary to do some
 *          careful parsing.  For example, in this file, we have
 *          left and right braces as characters, and these must not
 *          be counted.  Somewhat more tricky, the file fhmtauto.c
 *          generates code, and includes a right brace in a string.
 *          So we must not include braces that are in strings.  But how
 *          do we know if something is inside a string?  Keep state,
 *          starting with not-inside, and every time you hit a double quote
 *          that is not escaped, toggle the condition.  Any brace
 *          found in the state of being within a string is ignored.
 *      (6) When a prototype is extracted, it is put in a canonical
 *          form (i.e., cleaned up).  Finally, we check that it is
 *          not static and save it.  (If static, it is ignored).
 *      (7) The @prestring for unix is NULL; it is included here so that
 *          you can use Microsoft's declaration for importing or
 *          exporting to a dll.  See environ.h for examples of use.
 *          Here, we set: @prestring = "LEPT_DLL ".  Note in particular
 *          the space character that will separate 'LEPT_DLL' from
 *          the standard unix prototype that follows.
 */
char *
parseForProtos(const char *filein,
               const char *prestring)
{
char    *strdata, *str, *newstr, *parsestr, *secondword;
l_int32  start, next, stop, charindex, found;
size_t   nbytes;
SARRAY  *sa, *saout, *satest;

    PROCNAME("parseForProtos");

    if (!filein)
        return (char *)ERROR_PTR("filein not defined", procName, NULL);

        /* Read in the cpp output into memory, one string for each
         * line in the file, omitting blank lines.  */
    strdata = (char *)l_binaryRead(filein, &nbytes);
    sa = sarrayCreateLinesFromString(strdata, 0);

    saout = sarrayCreate(0);
    next = 0;
    while (1) {  /* repeat after each non-static prototype is extracted */
        searchForProtoSignature(sa, next, &start, &stop, &charindex, &found);
        if (!found)
            break;
/*        fprintf(stderr, "  start = %d, stop = %d, charindex = %d\n",
                start, stop, charindex); */
        str = captureProtoSignature(sa, start, stop, charindex);

            /* Make sure that the signature found by cpp is neither
             * static nor extern.  We get 'extern' declarations from
             * header files, and with some versions of cpp running on
             * #include <sys/stat.h> we get something of the form:
             *    extern ... (( ... )) ... ( ... ) { ...
             * For this, the 1st '(' is the lp, the 2nd ')' is the rp,
             * and there is a lot of garbage between the rp and the lb.
             * It is easiest to simply reject any signature that starts
             * with 'extern'.  Note also that an 'extern' token has been
             * prepended to each prototype, so the 'static' or
             * 'extern' keywords we are looking for, if they exist,
             * would be the second word. */
        satest = sarrayCreateWordsFromString(str);
        secondword = sarrayGetString(satest, 1, L_NOCOPY);
        if (strcmp(secondword, "static") &&  /* not static */
            strcmp(secondword, "extern")) {  /* not extern */
            if (prestring) {  /* prepend it to the prototype */
                newstr = stringJoin(prestring, str);
                sarrayAddString(saout, newstr, L_INSERT);
                LEPT_FREE(str);
            } else {
                sarrayAddString(saout, str, L_INSERT);
            }
        } else {
            LEPT_FREE(str);
        }
        sarrayDestroy(&satest);

        skipToEndOfFunction(sa, stop, charindex, &next);
        if (next == -1) break;
    }

        /* Flatten into a string with newlines between prototypes */
    parsestr = sarrayToString(saout, 1);
    LEPT_FREE(strdata);
    sarrayDestroy(&sa);
    sarrayDestroy(&saout);

    return parsestr;
}
Exemple #15
0
/*!
 *  pixHtmlViewer()
 *
 *      Input:  dirin:  directory of input image files
 *              dirout: directory for output files
 *              rootname: root name for output files
 *              thumbwidth:  width of thumb images
 *                           (in pixels; use 0 for default)
 *              viewwidth:  maximum width of view images (no up-scaling)
 *                           (in pixels; use 0 for default)
 *              copyorig:  1 to copy originals to dirout; 0 otherwise
 *      Return: 0 if OK; 1 on error
 *
 *  Notes:
 *      (1) The thumb and view reduced images are generated,
 *          along with two html files:
 *             <rootname>.html and <rootname>-links.html
 *      (2) The thumb and view files are named
 *             <rootname>_thumb_xxx.jpg
 *             <rootname>_view_xxx.jpg
 *          With this naming scheme, any number of input directories
 *          of images can be processed into views and thumbs
 *          and placed in the same output directory.
 */
l_int32
pixHtmlViewer(const char  *dirin,
              const char  *dirout,
              const char  *rootname,
              l_int32      thumbwidth,
              l_int32      viewwidth,
              l_int32      copyorig)
{
char      *fname, *fullname, *outname;
char      *mainname, *linkname, *linknameshort;
char      *viewfile, *thumbfile;
char      *shtml, *slink;
char       charbuf[L_BUF_SIZE];
char       htmlstring[] = "<html>";
char       framestring[] = "</frameset></html>";
l_int32    i, nfiles, index, w, nimages, ret;
l_float32  factor;
PIX       *pix, *pixthumb, *pixview;
SARRAY    *safiles, *sathumbs, *saviews, *sahtml, *salink;

    PROCNAME("pixHtmlViewer");

    if (!dirin)
        return ERROR_INT("dirin not defined", procName, 1);
    if (!dirout)
        return ERROR_INT("dirout not defined", procName, 1);
    if (!rootname)
        return ERROR_INT("rootname not defined", procName, 1);

    if (thumbwidth == 0)
        thumbwidth = DEFAULT_THUMB_WIDTH;
    if (thumbwidth < MIN_THUMB_WIDTH) {
        L_WARNING("thumbwidth too small; using min value\n", procName);
        thumbwidth = MIN_THUMB_WIDTH;
    }
    if (viewwidth == 0)
        viewwidth = DEFAULT_VIEW_WIDTH;
    if (viewwidth < MIN_VIEW_WIDTH) {
        L_WARNING("viewwidth too small; using min value\n", procName);
        viewwidth = MIN_VIEW_WIDTH;
    }

        /* Make the output directory if it doesn't already exist */
#ifndef _WIN32
    sprintf(charbuf, "mkdir -p %s", dirout);
    ret = system(charbuf);
#else
    ret = CreateDirectory(dirout, NULL) ? 0 : 1;
#endif  /* !_WIN32 */
    if (ret) {
        L_ERROR("output directory %s not made\n", procName, dirout);
        return 1;
    }

        /* Capture the filenames in the input directory */
    if ((safiles = getFilenamesInDirectory(dirin)) == NULL)
        return ERROR_INT("safiles not made", procName, 1);

        /* Generate output text file names */
    sprintf(charbuf, "%s/%s.html", dirout, rootname);
    mainname = stringNew(charbuf);
    sprintf(charbuf, "%s/%s-links.html", dirout, rootname);
    linkname = stringNew(charbuf);
    linknameshort = stringJoin(rootname, "-links.html");

    if ((sathumbs = sarrayCreate(0)) == NULL)
        return ERROR_INT("sathumbs not made", procName, 1);
    if ((saviews = sarrayCreate(0)) == NULL)
        return ERROR_INT("saviews not made", procName, 1);

        /* Generate the thumbs and views */
    nfiles = sarrayGetCount(safiles);
    index = 0;
    for (i = 0; i < nfiles; i++) {
        fname = sarrayGetString(safiles, i, L_NOCOPY);
        fullname = genPathname(dirin, fname);
        fprintf(stderr, "name: %s\n", fullname);
        if ((pix = pixRead(fullname)) == NULL) {
            fprintf(stderr, "file %s not a readable image\n", fullname);
            FREE(fullname);
            continue;
        }
        FREE(fullname);
        if (copyorig) {
            outname = genPathname(dirout, fname);
            pixWrite(outname, pix, IFF_JFIF_JPEG);
            FREE(outname);
        }

            /* Make and store the thumb */
        w = pixGetWidth(pix);
        factor = (l_float32)thumbwidth / (l_float32)w;
        if ((pixthumb = pixScale(pix, factor, factor)) == NULL)
            return ERROR_INT("pixthumb not made", procName, 1);
        sprintf(charbuf, "%s_thumb_%03d.jpg", rootname, index);
        sarrayAddString(sathumbs, charbuf, L_COPY);
        outname = genPathname(dirout, charbuf);
        pixWrite(outname, pixthumb, IFF_JFIF_JPEG);
        FREE(outname);
        pixDestroy(&pixthumb);

            /* Make and store the view */
        factor = (l_float32)viewwidth / (l_float32)w;
        if (factor >= 1.0) {
            pixview = pixClone(pix);   /* no upscaling */
        } else {
            if ((pixview = pixScale(pix, factor, factor)) == NULL)
                return ERROR_INT("pixview not made", procName, 1);
        }
        sprintf(charbuf, "%s_view_%03d.jpg", rootname, index);
        sarrayAddString(saviews, charbuf, L_COPY);
        outname = genPathname(dirout, charbuf);
        pixWrite(outname, pixview, IFF_JFIF_JPEG);
        FREE(outname);
        pixDestroy(&pixview);

        pixDestroy(&pix);
        index++;
    }

        /* Generate the main html file */
    if ((sahtml = sarrayCreate(0)) == NULL)
        return ERROR_INT("sahtml not made", procName, 1);
    sarrayAddString(sahtml, htmlstring, L_COPY);
    sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30);
    sarrayAddString(sahtml, charbuf, L_COPY);
    sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort);
    sarrayAddString(sahtml, charbuf, L_COPY);
    sprintf(charbuf, "<frame name=\"views\" src=\"%s\">",
            sarrayGetString(saviews, 0, L_NOCOPY));
    sarrayAddString(sahtml, charbuf, L_COPY);
    sarrayAddString(sahtml, framestring, L_COPY);
    shtml = sarrayToString(sahtml, 1);
    l_binaryWrite(mainname, "w", shtml, strlen(shtml));
    FREE(shtml);
    FREE(mainname);

        /* Generate the link html file */
    nimages = sarrayGetCount(saviews);
    fprintf(stderr, "num. images = %d\n", nimages);
    if ((salink = sarrayCreate(0)) == NULL)
        return ERROR_INT("salink not made", procName, 1);
    for (i = 0; i < nimages; i++) {
        viewfile = sarrayGetString(saviews, i, L_NOCOPY);
        thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY);
        sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>",
            viewfile, thumbfile);
        sarrayAddString(salink, charbuf, L_COPY);
    }
    slink = sarrayToString(salink, 1);
    l_binaryWrite(linkname, "w", slink, strlen(slink));
    FREE(slink);
    FREE(linkname);
    FREE(linknameshort);

    sarrayDestroy(&safiles);
    sarrayDestroy(&sathumbs);
    sarrayDestroy(&saviews);
    sarrayDestroy(&sahtml);
    sarrayDestroy(&salink);

    return 0;
}
Exemple #16
0
int DataLoader::loadMultiplePhenotype(const std::string& multiplePhenotype,
                                      const std::string& pheno,
                                      const std::string& covar) {
  this->FLAG_pheno = pheno;
  this->FLAG_cov = covar;
  this->FLAG_multiplePheno = multiplePhenotype;

  if (covar.empty()) {
    this->FLAG_cov = this->FLAG_pheno;
  }

  // read in analysis template
  TextMatrix textMat;
  textMat.readFile(FLAG_multiplePheno, TextMatrix::HAS_HEADER);
  if (textMat.nrow() == 0 || which(textMat.header(), "pheno") < 0 ||
      which(textMat.header(), "covar") < 0) {
    logger->warn(
        "Wrong multiple phenotype analysis file (no correct headers: \"pheno "
        "covar\")");
    exit(1);
  }

  const int nTests = textMat.nrow();
  const int phenoCol = which(textMat.getColName(), "pheno");
  const int covCol = which(textMat.getColName(), "covar");
  for (int i = 0; i < nTests; ++i) {
    formula.add(textMat[i][phenoCol], textMat[i][covCol]);
  }
  logger->info("Load [ %d ] test formulae", (int)formula.size());

  std::vector<std::string> phenoLabel = formula.extractResponse();
  std::vector<std::string> covarLabel =
      formula.extractPredictor(FormulaVector::NO_INTERCEPT);
  // std::vector<std::string> phenoLabel = textMat.extractCol("pheno");
  // std::vector<std::string> covarLabel =
  // extractCovariate(textMat.extractCol("covar"));

  // read in ped
  TextMatrix pedMat;
  if (pedMat.readFile(FLAG_pheno, TextMatrix::HAS_HEADER)) {
    logger->error("Failed to load phenotype file [ %s ]!", FLAG_pheno.c_str());
    exit(1);
  }
  if (pedMat.nrow() == 0 || pedMat.header()[0] != "fid" ||
      pedMat.header()[1] != "iid") {
    logger->warn("Wrong phenotype file [ %s ]", pheno.c_str());
    exit(1);
  }
  pedMat.setRowNameByCol("iid");
  pedMat.keepCol(phenoLabel);
  if (pedMat.ncol() != (int)phenoLabel.size()) {
    logger->error(
        "Required responses [ %s ] cannot be found in [ %s ]",
        stringJoin(setSubtract(phenoLabel, pedMat.getColName()), ' ').c_str(),
        FLAG_pheno.c_str());
    exit(1);
  }

  // read in cov
  TextMatrix covMat;
  if (covMat.readFile(FLAG_cov, TextMatrix::HAS_HEADER)) {
    logger->error("Failed to load covariate file [ %s ]!", FLAG_cov.c_str());
    exit(1);
  }
  if (covMat.nrow() == 0 || tolower(covMat.header()[0]) != "fid" ||
      tolower(covMat.header()[1]) != "iid") {
    logger->warn(
        "Wrong covariate file - empty or unrecognized header line [ %s ]",
        covar.c_str());
    exit(1);
  }
  covMat.setRowNameByCol("iid");
  covMat.keepCol(covarLabel);
  if (covMat.ncol() != (int)covarLabel.size()) {
    logger->error(
        "Required covariates [ %s ] cannot be found in [ %s ]",
        stringJoin(setSubtract(covarLabel, covMat.getColName()), ' ').c_str(),
        FLAG_cov.c_str());
    exit(1);
  }

  // orangize ped/cov
  pedMat.convert(&phenotype);
  covMat.convert(&covariate);

  // make sure covarite and phenotype have the sample sets of samples
  std::vector<std::string> commonSample =
      intersect((phenotype.getRowName()), (covariate.getRowName()));
  phenotype.keepRow(commonSample);
  covariate.keepRow(commonSample);

  // drop all missing rows
  std::vector<int> missing =
      intersect((phenotype.allMissingRows()), (covariate.allMissingRows()));
  phenotype.dropRow(missing);
  covariate.dropRow(missing);

  // NOTE: do not take imputePheno, imputeCov
  // NOTE: do not center, scale ...
  // Actual regression model will center phenotype and covariate
  return 0;
}
Exemple #17
0
std::string
stringJoin(ContainerT const & a, C const & padding)
{
  return stringJoin(a.begin(), a.end(), padding);
}
main(int    argc,
     char **argv)
{
char        *filename, *filein, *str, *prestring;
const char  *spacestr = " ";
char         buf[L_BUF_SIZE];
l_int32      i, firstfile, len, ret;
SARRAY      *sa;
static char  mainName[] = "xtractprotos";

        /* Output extern C head */
    sa = sarrayCreate(0);
    sarrayAddString(sa, (char *)"/*", 1);
    snprintf(buf, L_BUF_SIZE,
             " *  This file was autogen'd by xtractprotos, v. %s", version);
    sarrayAddString(sa, buf, 1);
    sarrayAddString(sa, (char *)" */", 1);
    sarrayAddString(sa, (char *)"#ifdef __cplusplus", 1);
    sarrayAddString(sa, (char *)"extern \"C\" {", 1);
    sarrayAddString(sa, (char *)"#endif  /* __cplusplus */\n", 1);
    str = sarrayToString(sa, 1);
    fprintf(stdout, str);
    sarrayDestroy(&sa);
    FREE(str);

        /* Prepend 'prestring' if requested */
    firstfile = 1;
    prestring = NULL;
    if (argv[1][0] == '-') {
        firstfile = 2;
        if (sscanf(argv[1], "-prestring=%s", buf) != 1)
            L_WARNING("Failure to parse prestring; omitting!", mainName);
        else {
            if ((len = strlen(buf)) > L_BUF_SIZE - 3)
                L_WARNING("prestring too large; omitting!", mainName);
            else {
                buf[len] = ' ';
                buf[len + 1] = '\0';
                prestring = stringNew(buf);
            }
        }
    }
        
    for (i = firstfile; i < argc; i++) {
        filein = argv[i];
	len = strlen(filein);
	if (filein[len - 1] == 'h')
	    continue;
	snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s",
	         filein, tempfile);
	ret = system(buf);
	if (ret) {
            fprintf(stderr, "cpp failure for %s; continuing\n", filein);
	    continue;
	}

#ifndef _CYGWIN_ENVIRON
        filename = stringNew(tempfile);
#else
        filename = stringJoin(tempfile, ".exe");
#endif  /* ~ _CYGWIN_ENVIRON */

	if ((str = parseForProtos(filename, prestring)) == NULL) {
            fprintf(stderr, "parse failure for %s; continuing\n", filein);
	    continue;
	}
	if (strlen(str) > 1)  /* strlen(str) == 1 is a file without protos */
            fprintf(stdout, str);
        FREE(str);
	FREE(filename);
    }

        /* Output extern C tail */
    sa = sarrayCreate(0);
    sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", 1);
    sarrayAddString(sa, (char *)"}", 1);
    sarrayAddString(sa, (char *)"#endif  /* __cplusplus */", 1);
    str = sarrayToString(sa, 1);
    fprintf(stdout, str);
    sarrayDestroy(&sa);
    FREE(str);
    if (prestring)
        FREE(prestring);

    return 0;
}
//private
void setupMonitoring(bool isRetry, char* processName, unsigned long int duration, RegisterEntry* tail)
{
    int num = 0;
    Process** runningProcesses = searchRunningProcesses(&num, processName, false, saveLogReport);
    if (runningProcesses == NULL)
    {
        // Nothing to be done
        if (num == 0)
        {
            if (!isRetry)
            {
                LogReport report;
                report.message = stringJoin("No process found with name: ", processName);
                report.type = INFO;
                saveLogReport(report, false);
                free(report.message);
            }

            return;
        }
        exit(-1);
    }

    int i;
    for(i = 0; i < num; ++i)
    {
        Process* p = runningProcesses[i];

        if (p -> pid == getpid())
        {
            // If procnannys were killed in the beginning, but a new one was started in between and the user expects to track that.
            // Should never happen/be done.
            LogReport report;
            report.message = "Config file had procnanny as one of the entries. It will be ignored if no other procnanny is found.";
            report.type = WARNING;
            saveLogReport(report, false);
            continue;
        }

        if (isProcessAlreadyBeingMonitored(p->pid))
        {
            continue;
        }

        logProcessMonitoringInit(processName, p->pid);

        RegisterEntry* freeChild = getFirstFreeChild();
        if (freeChild == NULL)
        {
            // fork a new child
            int writeToChildFD[2];
            int readFromChildFD[2];
            if (pipe(writeToChildFD) < 0)
            {
                destroyProcessArray(runningProcesses, num);
                LogReport report;
                report.message = "Pipe creation error when trying to monitor new process.";
                report.type = ERROR;
                saveLogReport(report, true);
                // TODO: Kill all children
                // TODO: Log all final kill count
                exit(-1);
            }

            if (pipe(readFromChildFD) < 0)
            {
                destroyProcessArray(runningProcesses, num);
                LogReport report;
                report.message = "Pipe creation error when trying to monitor new process.";
                report.type = ERROR;
                saveLogReport(report, true);
                // TODO: Kill all children
                // TODO: Log all final kill count
                exit(-1);
            }

            pid_t forkPid = fork();
            switch (forkPid)
            {
                case -1:
                    destroyProcessArray(runningProcesses, num);
                    exit(-1);

                case CHILD:
                    close(writeToChildFD[1]);
                    close(readFromChildFD[0]);
                    writingToParent = readFromChildFD[1];
                    readingFromParent = writeToChildFD[0];
                    pid_t targetPid = p->pid;
                    destroyProcessArray(runningProcesses, num);
                    cleanupGlobals();

                    while (true)
                    {
                        ProcessStatusCode childStatus = childMain(targetPid, duration);
                        write(writingToParent, &childStatus, 1);

                        MonitorMessage message;
                        assert(read(readingFromParent, &message, sizeof(MonitorMessage)) == sizeof(MonitorMessage));
                        targetPid = message.targetPid;
                        duration = message.monitorDuration;
                    }

                    break;

                default:
                     // parent
                    close(writeToChildFD[0]);
                    close(readFromChildFD[1]);
                    tail->monitoringProcess = forkPid;
                    tail->monitoredProcess = p->pid;
                    tail->monitorDuration = duration;
                    tail->monitoredName = copyString(p->command);
                    tail->startingTime = time(NULL);
                    tail->isAvailable = false;
                    tail->writeToChildFD = writeToChildFD[1];
                    tail->readFromChildFD = readFromChildFD[0];
                    FD_SET(tail->readFromChildFD, &activeFds);
                    tail->next = constuctorRegisterEntry((pid_t)0, NULL, NULL);
                    tail = tail->next;
                    break;
            }

        }
        else
        {
            // use freeChild
            freeChild->isAvailable = false;
            freeChild->monitoredProcess = p->pid;
            free(freeChild->monitoredName);
            freeChild->monitoredName = copyString(p->command);
            freeChild->monitorDuration = duration;
            freeChild->startingTime = time(NULL);
            MonitorMessage message;
            message.targetPid = p->pid;
            message.monitorDuration = duration;
            write(freeChild->writeToChildFD, &message, sizeof(MonitorMessage));
        }
    }

    destroyProcessArray(runningProcesses, num);
}
Exemple #20
0
Any Scene::load(const std::string& scene) {
    std::string filename;
    clear();
    m_modelTable.clear();
    m_name = scene;

    bool isFilename = endsWith(toLower(scene), ".scn.any") || endsWith(toLower(scene), ".Scene.Any");

    if (isFilename) {
        filename = scene;
    } else {
        const std::string* f = filenameTable().getPointer(scene);
        if (f == NULL) {
            throw "No scene with name '" + scene + "' found in (" + 
                stringJoin(filenameTable().getKeys(), ", ") + ")";
        }

        filename = *f;
    }

    Any any;
    any.load(filename);

    {
        const std::string& n = any.get("name", filename);

        // Ensure that this name appears in the filename table if it does not already,
        // so that it can be loaded by name in the future.
        if (! filenameTable().containsKey(n)) {
            filenameTable().set(n, filename);
        }
    }

    m_sourceAny = any;

    // Load the lighting environment (do this before loading entities, since some of them may
    // be lights that will enter this array)
    bool hasEnvironmentMap = false;
    if (any.containsKey("localLightingEnvironment")) {
         m_localLightingEnvironment = any["localLightingEnvironment"];
         hasEnvironmentMap = any["localLightingEnvironment"].containsKey("environmentMap");
    }
        

    // Load the models
    if (any.containsKey("models")) {
        Any models = any["models"];
        if (models.size() > 0) {
            for (Any::AnyTable::Iterator it = models.table().begin(); it.isValid(); ++it) {
                const std::string name = it->key;
                Any v = it->value;
                createModel(v, name);
            }
        }
    }

    // Instance the models
    if (any.containsKey("entities")) { 
        Any entities = any["entities"];
        if (entities.size() > 0) {
            for (Table<std::string, Any>::Iterator it = entities.table().begin(); it.isValid(); ++it) {
                const std::string& name = it->key;
                const std::string& entityType = it->value.name();

                createEntity(entityType, name, it->value);
            }
        }
    }
    
    shared_ptr<Texture> skyboxTexture = Texture::whiteCube();

    Any skyAny;

    // Use the environment map as a skybox if there isn't one already, and vice versa
    Array<shared_ptr<Skybox> > skyboxes;
    getTypedEntityArray<Skybox>(skyboxes);
    if ( skyboxes.size() == 0 ) {
        if (any.containsKey("skybox")) {
            createEntity("Skybox", "skybox", any["skybox"]);
            m_skybox = typedEntity<Skybox>("skybox");
        } else if (hasEnvironmentMap) {
            m_skybox = Skybox::create("skybox", this, Array<ScaledTexture>(m_localLightingEnvironment.environmentMapArray[0]), Array<SimTime>(0.0), 0, SplineExtrapolationMode::CLAMP, false, false);
            insert(m_skybox);
        } else {
            m_skybox = Skybox::create("skybox", this, Array<ScaledTexture>(ScaledTexture(Texture::whiteCube(), 1.0f)), Array<SimTime>(0.0), 0, SplineExtrapolationMode::CLAMP, false, false);
            insert(m_skybox);
        }
    }

    if (any.containsKey("environmentMap")) {
        throw std::string("environmentMap field has been replaced with localLightingEnvironment");
    }


    // Default to using the skybox as an environment map if none is specified.
    if (! hasEnvironmentMap) {
        m_localLightingEnvironment.environmentMapArray.append(ScaledTexture(m_skybox->keyframeArray()[0].texture, m_skybox->keyframeArray()[0].constant));
    }


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

    if (m_cameraArray.size() == 0) {
        // Create a default camera, back it up from the origin
        m_cameraArray.append(Camera::create("camera"));
        m_cameraArray.last()->setFrame(CFrame::fromXYZYPRDegrees(0,1,-5,0,-5));
    }

    setTime(any.get("time", 0.0));
    m_lastVisibleChangeTime = m_lastLightChangeTime = m_lastStructuralChangeTime = System::time();

    m_defaultCameraName = (std::string)any.get("defaultCamera", "");


    // Set the initial positions, repeating a few times to allow
    // objects defined relative to others to reach a fixed point
    for (int i = 0; i < 3; ++i) {
        for (int e = 0; e < m_entityArray.size(); ++e) {
            m_entityArray[e]->onSimulation(m_time, nan());
        }
    }

    // Pose objects so that they have bounds.
    {
        Array< shared_ptr<Surface> > ignore;
        onPose(ignore);
    }

    return any;
}