Esempio n. 1
0
static void
logToAllLevels(
    void               *v_name)
{
#define ST_ND_TH(c) \
    ((((c) % 10) == 1) ? "st" : ((((c) % 10) == 2) ? "nd" : "th"))

    int c;
    char *name = (char *)v_name;

    pthread_mutex_lock(&count_mutex);
    c = ++global_count;
    pthread_mutex_unlock(&count_mutex);

    if (test_emerg) {
        EMERGMSG("Writing a EMERGMSG for the %d%s time [%s]",
                 c, ST_ND_TH(c), name);
    }
    ALERTMSG("Writing a ALERTMSG for the %d%s time [%s]",
             c, ST_ND_TH(c), name);
    CRITMSG("Writing a CRITMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    ERRMSG("Writing a ERRMSG for the %d%s time [%s]",
           c, ST_ND_TH(c), name);
    WARNINGMSG("Writing a WARNINGMSG for the %d%s time [%s]",
               c, ST_ND_TH(c), name);
    NOTICEMSG("Writing a NOTICEMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    INFOMSG("Writing a INFOMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    DEBUGMSG("Writing a DEBUGMSG for the %d%s time [%s]",
             c, ST_ND_TH(c), name);
}
Esempio n. 2
0
bool RegistryGetDouble(const string& section, const string& name, double *value)
{
    wxString regStr = registry.Get(section, name).c_str();
    if (regStr.size() == 0 || !regStr.ToDouble(value)) {
        WARNINGMSG("Can't get double from registry: " << section << ", " << name);
        return false;
    }
    return true;
}
Esempio n. 3
0
bool RegistryGetString(const string& section, const string& name, string *value)
{
    string regStr = registry.Get(section, name);
    if (regStr.size() == 0) {
        WARNINGMSG("Can't get string from registry: " << section << ", " << name);
        return false;
    }
    *value = regStr;
    return true;
}
Esempio n. 4
0
bool RegistryGetInteger(const string& section, const string& name, int *value)
{
    wxString regStr = registry.Get(section, name).c_str();
    long l;
    if (regStr.size() == 0 || !regStr.ToLong(&l)) {
        WARNINGMSG("Can't get long from registry: " << section << ", " << name);
        return false;
    }
    *value = (int) l;
    return true;
}
Esempio n. 5
0
void SetUpWorkingDirectories(const char* argv0)
{
    // set up working directories
    workingDir = wxGetCwd().c_str();
#ifdef __WXGTK__
    if (getenv("CN3D_HOME") != NULL)
        programDir = getenv("CN3D_HOME");
    else
#endif
    if (wxIsAbsolutePath(argv0))
        programDir = wxPathOnly(argv0).c_str();
    else if (wxPathOnly(argv0) == "")
        programDir = workingDir;
    else
        programDir = workingDir + wxFILE_SEP_PATH + wxPathOnly(argv0).c_str();
    workingDir = workingDir + wxFILE_SEP_PATH;
    programDir = programDir + wxFILE_SEP_PATH;

    // find or create preferences folder
    wxString localDir;
    wxSplitPath((wxFileConfig::GetLocalFileName("unused")).c_str(), &localDir, NULL, NULL);
    wxString prefsDirLocal = localDir + wxFILE_SEP_PATH + "Cn3D_User";
    wxString prefsDirProg = wxString(programDir.c_str()) + wxFILE_SEP_PATH + "Cn3D_User";
    if (wxDirExists(prefsDirLocal))
        prefsDir = prefsDirLocal.c_str();
    else if (wxDirExists(prefsDirProg))
        prefsDir = prefsDirProg.c_str();
    else {
        // try to create the folder
        if (wxMkdir(prefsDirLocal) && wxDirExists(prefsDirLocal))
            prefsDir = prefsDirLocal.c_str();
        else if (wxMkdir(prefsDirProg) && wxDirExists(prefsDirProg))
            prefsDir = prefsDirProg.c_str();
    }
    if (prefsDir.size() == 0)
        WARNINGMSG("Can't create Cn3D_User folder at either:"
            << "\n    " << prefsDirLocal
            << "\nor  " << prefsDirProg);
    else
        prefsDir += wxFILE_SEP_PATH;

    // set data dir, and register the path in C toolkit registry (mainly for BLAST code)
#ifdef __WXMAC__
    dataDir = programDir + "../Resources/data/";
#else
    dataDir = programDir + "data" + wxFILE_SEP_PATH;
#endif

    TRACEMSG("working dir: " << workingDir.c_str());
    TRACEMSG("program dir: " << programDir.c_str());
    TRACEMSG("data dir: " << dataDir.c_str());
    TRACEMSG("prefs dir: " << prefsDir.c_str());
}
Esempio n. 6
0
bool RegistryGetBoolean(const string& section, const string& name, bool *value)
{
    string regStr = registry.Get(section, name);
    if (regStr.size() == 0 || !(
            toupper((unsigned char) regStr[0]) == 'T' || toupper((unsigned char) regStr[0]) == 'F' ||
            toupper((unsigned char) regStr[0]) == 'Y' || toupper((unsigned char) regStr[0]) == 'N')) {
        WARNINGMSG("Can't get boolean from registry: " << section << ", " << name);
        return false;
    }
    *value = (toupper((unsigned char) regStr[0]) == 'T' || toupper((unsigned char) regStr[0]) == 'Y');
    return true;
}
Esempio n. 7
0
void ArchiveProcessEvents<T>::process (const std::shared_ptr<Archive> &archive, std::map<DTuint64, std::shared_ptr<BaseClass>> &objects)
{
	// write the actual object
	if (archive->is_writing()) {
		
		// Nothing to do here.
		
	// Connect events
	} else {
    
		for (std::size_t i = 0; i < _connections.size(); ++i) {
    
            // Good to check but probably won't happen
            if (_connections[i]._src_node_id == 0 || _dst_node_id == 0)
                return;
            
            // Check to see if the object is already read. It better be! If not, check if all 
            // objects have been created. I bet they haven't.
            auto src_obj = objects.find(_connections[i]._src_node_id);
            ERROR(src_obj != objects.end(), "Unable to connect events");
            
            auto dst_obj = objects.find(_dst_node_id);
            ERROR(dst_obj != objects.end(), "Unable to connect events");
            
            // Convert to EventNodes
            std::shared_ptr<PlugNode> src_node = checked_cast<PlugNode>(src_obj->second);
            std::shared_ptr<PlugNode> dst_node = checked_cast<PlugNode>(dst_obj->second);
            
            if (src_node && dst_node) {
            
                // get Events
                Event *src_event = src_node->event_by_name(_connections[i]._src_name);
                Event *dst_event = dst_node->event_by_name(_dst_name);
                                
                // If everything is good, then connect them
                if (src_event && dst_event) {
                    // Check if inputs were swapped
                    if ( (dst_event->is_output() && src_event->is_input()) && !(src_event->is_output() && dst_event->is_input())) {
                        std::swap(src_event,dst_event);
                        WARNINGMSG("Event input and output were swapped.");
                    }

                    dst_event->add_incoming_connection(src_event);
                }
            }
            
        }

	}
}
Esempio n. 8
0
double ComputeRMSD(int nCoords, const Vector * const *masterCoords,
    const Vector * const *dependentCoords, const Matrix *transformDependentToMaster)
{
    Vector x;
    double rmsd = 0.0;
    int n = 0;
    for (int c=0; c<nCoords; ++c) {
        if (!dependentCoords[c] || !masterCoords[c]) continue;
        x = *(dependentCoords[c]);
        if (transformDependentToMaster)
            ApplyTransformation(&x, *transformDependentToMaster);
        rmsd += (*(masterCoords[c]) - x).lengthSquared();
        ++n;
    }
    if (n == 0) {
        WARNINGMSG("ComputeRMSD() - received no non-NULL coordinates");
        return 0.0;
    }
    rmsd = sqrt(rmsd / n);
    return rmsd;
}
Esempio n. 9
0
/*
 *    This function is called by the handleConnection() function in
 *    rwtransfer.c once the connection has been established.  This
 *    function returns -1 on error, 0 if no files were transferred, or
 *    1 if one or more files were successfully received.
 */
int
transferFiles(
    sk_msg_queue_t     *q,
    skm_channel_t       channel,
    transfer_t         *sndr)
{
    static pthread_mutex_t open_file_mutex = PTHREAD_MUTEX_INITIALIZER;
    int fd = -1;
    uint64_t size = 0;
    uint64_t pa_size = 0;
    uint8_t *map = NULL;
    char *name = NULL;
    char *dotname = NULL;
    char dotpath[PATH_MAX];
    char destpath[sizeof(dotpath)-1];
    struct stat st;
    ino_t *inode;
    int proto_err;
    int rv;
    sk_dll_iter_t iter;
    const char *duplicate_dir;
    enum transfer_state {File_info, File_info_ack,
                         Send_file, Complete_ack, Error} state;
    int thread_exit;
    int transferred_file = 0;

    state = File_info;
    proto_err = 0;
    thread_exit = 0;
    destpath[0] = '\0';
    dotpath[0] = '\0';
    memset(&st, 0, sizeof(st));

    while (!shuttingdown && !proto_err && !thread_exit && !sndr->disconnect
           && (state != Error))
    {
        sk_msg_t *msg;

        /* Handle reads */
        switch (state) {
          case File_info:
          case Send_file:
            rv = skMsgQueueGetMessage(q, &msg);
            if (rv == -1) {
                ASSERT_ABORT(shuttingdown);
                continue;
            }
            if (handleDisconnect(msg, sndr->ident)) {
                state = Error;
            }
            break;
          case Error:
            ASSERT_ABORT(0);
            break;
          default:
            msg = NULL;
        }

        /* Handle all states */
        switch (state) {
          case File_info:
            /* Create the placeholder and dot files and mmap() the
             * space. */
            {
                file_info_t *finfo;
                uint32_t len;
                mode_t mode;
                off_t offrv;

                if ((proto_err = checkMsg(msg, q, CONN_NEW_FILE))) {
                    break;
                }
                DEBUG_PRINT1("Received CONN_NEW_FILE");
                finfo = (file_info_t *)skMsgMessage(msg);
                size = (uint64_t)ntohl(finfo->high_filesize) << 32 |
                       ntohl(finfo->low_filesize);
                pa_size = size;
                /* blocksize = ntohl(finfo->block_size); --- UNUSED */
                mode = ntohl(finfo->mode) & 0777;
                len = skMsgLength(msg) - offsetof(file_info_t, filename);
                dotname = (char *)calloc(1, len + 1);
                CHECK_ALLOC(dotname);
                name = dotname + 1;
                dotname[0] = '.';
                memcpy(name, finfo->filename, len);
                if (!memchr(name, '\0', len)) {
                    sendString(q, channel, EXTERNAL, SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Illegal filename (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    break;
                }

                INFOMSG("Receiving from %s: '%s' (%" PRIu64 " bytes)",
                        sndr->ident, name, size);

                /* Check filesystem for enough space for file */
                if (CHECK_DISK_SPACE(pa_size)) {
                    WARNINGMSG(("Not enough space on filesystem for %" PRIu64
                                " byte file '%s'"),
                               pa_size, name);
                    pa_size = 0;
                    state = FILESYSTEM_FULL_ERROR_STATE(sndr);
                    break;
                }

                /* Create the placeholder file */
                rv = snprintf(destpath, sizeof(destpath), "%s/%s",
                              destination_dir, name);
                if ((size_t)rv >= sizeof(destpath)) {
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Filename too long (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    destpath[0] = '\0';
                    break;
                }

                assert((size_t)rv < sizeof(destpath));

                pthread_mutex_lock(&open_file_mutex);
              reopen:
                fd = open(destpath, O_CREAT | O_EXCL | O_WRONLY, 0);
                if (fd == -1) {
                    if (errno != EEXIST) {
                        CRITMSG("Could not create '%s': %s",
                                destpath, strerror(errno));
                        thread_exit = 1;
                        pthread_mutex_unlock(&open_file_mutex);
                        break;
                    }

                    if (stat(destpath, &st) == -1) {
                        WARNINGMSG("Unable to stat '%s': %s",
                                   destpath, strerror(errno));
                    } else if (S_ISREG(st.st_mode)
                               && ((st.st_mode & 0777) == 0)
                               && ((st.st_size == 0)))
                    {
                        /* looks like a placeholder file.  are we
                         * receiving a file with the same name from a
                         * different rwsender? */
                        int found = 0;
                        skDLLAssignIter(&iter, open_file_list);
                        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                            if (st.st_ino == *inode) {
                                WARNINGMSG(("Multiple rwsenders attempting"
                                            " to send file '%s'"),
                                           name);
                                found = 1;
                                break;
                            }
                        }
                        if (!found) {
                            WARNINGMSG(("Filename already exists (from a"
                                        " previous run?). Removing '%s'"),
                                       destpath);
                            if (unlink(destpath) == 0) {
                                goto reopen;
                            }
                            WARNINGMSG("Failed to unlink '%s': %s",
                                       destpath, strerror(errno));
                            /* treat file as a duplicate */
                        }
                    }
                    /* else file is a duplicate */
                    st.st_ino = 0;
                    destpath[0] = dotpath[0] = '\0';
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_DUPLICATE(sndr),
                               LOG_WARNING,
                               "Filename already exists (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                /* else, successfully opened placeholder file */
                if (fstat(fd, &st) == -1) {
                    CRITMSG("Could not fstat newly created file '%s': %s",
                            destpath, strerror(errno));
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                if (skDLListPushTail(open_file_list, &st.st_ino)) {
                    CRITMSG("Unable to grow open file list");
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                pthread_mutex_unlock(&open_file_mutex);

                DEBUGMSG("Created '%s'", destpath);

                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            destpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Create the dotfile */
                rv = snprintf(dotpath, sizeof(dotpath), "%s/%s",
                              destination_dir, dotname);
              reopen2:
                fd = open(dotpath, O_RDWR | O_CREAT | O_EXCL, mode);
                if (fd == -1) {
                    int saveerrno = errno;
                    if (errno == EEXIST) {
                        WARNINGMSG("Filename already exists. Removing '%s'",
                                   dotpath);
                        if (unlink(dotpath) == 0) {
                            goto reopen2;
                        }
                        WARNINGMSG("Failed to unlink '%s': %s",
                                   dotpath, strerror(errno));
                    }
                    CRITMSG("Could not create '%s': %s",
                            dotpath, strerror(saveerrno));
                    thread_exit = 1;
                    dotpath[0] = '\0';
                    break;
                }
                DEBUGMSG("Created '%s'", dotpath);

                /* Allocate space on disk */
                offrv = lseek(fd, size - 1, SEEK_SET);
                if (offrv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = write(fd, "", 1);
                if (rv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Map space */
                map = (uint8_t *)mmap(0, size, PROT_READ | PROT_WRITE,
                                      MAP_SHARED, fd, 0);
                if ((void *)map == MAP_FAILED) {
                    CRITMSG("Could not map '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                GOT_DISK_SPACE(pa_size);
                pa_size = 0;
                state = File_info_ack;
            }
            break;

          case File_info_ack:
            DEBUG_PRINT1("Sending CONN_NEW_FILE_READY");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_NEW_FILE_READY, NULL, 0);
            state = Send_file;
            break;

          case Send_file:
            /* Get the content of the file and write into the dot file */
            {
                block_info_t *block;
                uint64_t offset;
                uint32_t len;

                if (skMsgType(msg) != CONN_FILE_BLOCK) {
                    if ((proto_err = checkMsg(msg, q, CONN_FILE_COMPLETE))) {
                        break;
                    }
                    DEBUG_PRINT1("Received CONN_FILE_COMPLETE");
                    state = Complete_ack;
                    break;
                }

                block = (block_info_t *)skMsgMessage(msg);
                len = skMsgLength(msg) - offsetof(block_info_t, block);
                offset = (uint64_t)ntohl(block->high_offset) << 32 |
                         ntohl(block->low_offset);
                DEBUG_CONTENT_PRINT("Receiving offset=%" PRIu64 " len=%" PRIu32,
                                    offset, len);
                if (offset + len > size) {
                    sendString(q, channel, EXTERNAL, CONN_DISCONNECT,
                               LOG_WARNING,
                               ("Illegal block (offset/size %" PRIu64
                                "/%" PRIu32 ")"), offset, len);
                    state = Error;
                    break;
                }
                memcpy(map + offset, block->block, len);
            }
            break;

          case Complete_ack:
            /* Un-mmap() the file, create any duplicate files, and
             * move the dotfile over the placeholder file */
            rv = munmap(map, size);
            map = NULL;
            if (rv == -1) {
                CRITMSG("Could not unmap file '%s': %s",
                        dotpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* Handle duplicate-destinations. Any errors here are
             * simply logged and processing continues. */
            skDLLAssignIter(&iter, duplicate_dirs);
            while (skDLLIterForward(&iter, (void **)&duplicate_dir) == 0) {
                char path[sizeof(destpath)];

                snprintf(path, sizeof(path), "%s/%s", duplicate_dir, name);
                if (unique_duplicates) {
                    rv = skCopyFile(dotpath, path);
                    if (rv != 0) {
                        WARNINGMSG("Could not copy '%s' to '%s': %s",
                                   dotpath, path, strerror(rv));
                    }
                } else {
                    DEBUGMSG("Linking '%s' as '%s'", dotpath, path);
                    rv = link(dotpath, path);
                    if (EXDEV == errno) {
                        DEBUGMSG("Link failed EXDEV; copying '%s' to '%s'",
                                 dotpath, path);
                        rv = skCopyFile(dotpath, path);
                        if (rv != 0) {
                            WARNINGMSG("Could not copy '%s' to '%s': %s",
                                       dotpath, path, strerror(rv));
                        }
                    } else if (rv != 0) {
                        WARNINGMSG("Could not link '%s' as '%s': %s",
                                   dotpath, path, strerror(errno));
                    }
                }
            }

            DEBUGMSG("Renaming '%s' to '%s'", dotpath, destpath);
            rv = rename(dotpath, destpath);
            if (rv != 0) {
                CRITMSG("Failed rename of '%s' to '%s': %s",
                        dotpath, destpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* remove the file from the open_file_list */
            pthread_mutex_lock(&open_file_mutex);
            skDLLAssignIter(&iter, open_file_list);
            while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                if (st.st_ino == *inode) {
                    skDLLIterDel(&iter);
                    break;
                }
            }
            st.st_ino = 0;
            pthread_mutex_unlock(&open_file_mutex);

            DEBUG_PRINT1("Sending CONN_FILE_COMPLETE");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_FILE_COMPLETE, NULL, 0);
            if (proto_err == 0) {
                /* Run the post command on the file */
                if (post_command) {
                    runPostCommand(post_command, destpath, sndr->ident);
                }
                destpath[0] = '\0';
                INFOMSG("Finished receiving from %s: '%s'", sndr->ident, name);
                free(dotname);
                dotname = NULL;
            }

            destpath[0] = dotpath[0] = '\0';
            transferred_file = 1;

            state = File_info;
            break;

          case Error:
            break;
        }

        if (msg != NULL) {
            skMsgDestroy(msg);
        }
    }

    if (fd != -1) {
        close(fd);
    }
    if (map != NULL) {
        munmap(map, size);
    }
    if (dotname != NULL) {
        free(dotname);
    }
    if (dotpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", dotpath);
        unlink(dotpath);
    }
    if (destpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", destpath);
        unlink(destpath);
    }
    if (st.st_ino != 0) {
        skDLLAssignIter(&iter, open_file_list);
        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
            if (st.st_ino == *inode) {
                skDLLIterDel(&iter);
                break;
            }
        }
    }
    if (pa_size) {
        GOT_DISK_SPACE(pa_size);
    }
    if (thread_exit) {
        return -1;
    }

    return transferred_file;
}
Esempio n. 10
0
/*
 *  runPostCommand(command, filename, ident);
 *
 *    Spawn a new subprocess to run 'command'.  Formatting directives
 *    in 'command' may be expanded to hold to the 'filename' that has
 *    just been received and the 'ident' of the rwsender that sent the
 *    file.
 */
static void
runPostCommand(
    const char         *command,
    const char         *file,
    const char         *ident)
{
    sigset_t sigs;
    pid_t pid;
    size_t len;
    size_t file_len;
    size_t ident_len;
    const char *cp;
    const char *sp;
    char *expanded_cmd;
    char *exp_cp;

    /* Parent (original process) forks to create Child 1 */
    pid = fork();
    if (-1 == pid) {
        ERRMSG("Could not fork to run command: %s", strerror(errno));
        return;
    }

    /* Parent reaps Child 1 and returns */
    if (0 != pid) {
        /* Wait for Child 1 to exit. */
        while (waitpid(pid, NULL, 0) == -1) {
            if (EINTR != errno) {
                NOTICEMSG("Error waiting for child %ld: %s",
                          (long)pid, strerror(errno));
                break;
            }
        }
        return;
    }

    /* Disable log rotation in Child 1 */
    sklogDisableRotation();

    /* Child 1 forks to create Child 2 */
    pid = fork();
    if (pid == -1) {
        ERRMSG("Child could not fork for to run command: %s", strerror(errno));
        _exit(EXIT_FAILURE);
    }

    /* Child 1 immediately exits, so Parent can stop waiting */
    if (pid != 0) {
        _exit(EXIT_SUCCESS);
    }

    /* Only Child 2 makes it here */

    /* Unmask signals */
    sigemptyset(&sigs);
    sigprocmask(SIG_SETMASK, &sigs, NULL);

    /* Determine length of buffer needed for the expanded command
     * string and allocate it.  */
    len = strlen(command);
    file_len = strlen(file);
    ident_len = strlen(ident);
    cp = command;
    while (NULL != (cp = strchr(cp, (int)'%'))) {
        ++cp;
        switch (*cp) {
          case '%':
            --len;
            break;
          case 's':
            len += file_len - 2;
            break;
          case 'I':
            len += ident_len - 2;
            break;
          default:
            skAbortBadCase((int)(*cp));
        }
        ++cp;
    }
    expanded_cmd = (char*)malloc(len + 1);
    if (expanded_cmd == NULL) {
        WARNINGMSG("Unable to allocate memory to create command string");
        _exit(EXIT_FAILURE);
    }

    /* Copy command into buffer, handling %-expansions */
    cp = command;
    exp_cp = expanded_cmd;
    while (NULL != (sp = strchr(cp, (int)'%'))) {
        /* copy text we just jumped over */
        strncpy(exp_cp, cp, sp - cp);
        exp_cp += (sp - cp);
        /* handle conversion */
        switch (*(sp + 1)) {
          case '%':
            *exp_cp = '%';
            ++exp_cp;
            break;
          case 's':
            strcpy(exp_cp, file);
            exp_cp += file_len;
            break;
          case 'I':
            strcpy(exp_cp, ident);
            exp_cp += ident_len;
            break;
          default:
            skAbortBadCase((int)(*(sp+1)));
        }
        cp = sp + 2;
        assert(len >= (size_t)(exp_cp - expanded_cmd));
    }
    strcpy(exp_cp, cp);
    expanded_cmd[len] = '\0';

    /* Execute the command */
    DEBUGMSG("Invoking /bin/sh -c %s", expanded_cmd);
    if (execl("/bin/sh", "sh", "-c", expanded_cmd, (char*)NULL)
        == -1)
    {
        ERRMSG(("Error invoking /bin/sh: %s"),
               strerror(errno));
        _exit(EXIT_FAILURE);
    }

    /* Should never get here. */
    skAbort();
}
Esempio n. 11
0
// draw atom spheres and residue labels here
bool Residue::Draw(const AtomSet *atomSet) const
{
    if (!atomSet) {
        ERRORMSG("Residue::Draw(data) - NULL AtomSet*");
        return false;
    }

    // verify presense of OpenGLRenderer
    if (!parentSet->renderer) {
        WARNINGMSG("Residue::Draw() - no renderer");
        return false;
    }

    // get Molecule parent
    const Molecule *molecule;
    if (!GetParentOfType(&molecule)) return false;

    // get object parent
    const StructureObject *object;
    if (!GetParentOfType(&object)) return false;

    // is this residue labeled?
    const StyleSettings& settings = parentSet->styleManager->GetStyleForResidue(object, molecule->id, id);
    bool proteinLabel = (IsAminoAcid() && settings.proteinLabels.spacing > 0 &&
        (id-1)%settings.proteinLabels.spacing == 0);
    bool nucleotideLabel = (IsNucleotide() && settings.nucleotideLabels.spacing > 0 &&
        (id-1)%settings.nucleotideLabels.spacing == 0);

    bool overlayEnsembles = parentSet->showHideManager->OverlayConfEnsembles();
    AtomStyle atomStyle;
    const AtomCoord *atom, *l1 = NULL, *l2 = NULL, *l3 = NULL;
    Vector labelColor;
    bool alphaVisible = false, alphaOnly = false;

    // iterate atoms; key is atomID
    AtomInfoMap::const_iterator a, ae = atomInfos.end();
    for (a=atomInfos.begin(); a!=ae; ++a) {

        // get AtomCoord* for appropriate altConf
        AtomPntr ap(molecule->id, id, a->first);
        atom = atomSet->GetAtom(ap, overlayEnsembles, true);
        if (!atom) continue;

        // get Style
        if (!parentSet->styleManager->GetAtomStyle(this, ap, atom, &atomStyle))
            return false;

        // highlight atom if necessary
        if (atomStyle.isHighlighted)
            atomStyle.color = GlobalColors()->Get(Colors::eHighlight);

        // draw the atom
        if (atomStyle.style != StyleManager::eNotDisplayed && atomStyle.radius > 0.0)
            parentSet->renderer->DrawAtom(atom->site, atomStyle);

        // store coords for positioning label, based on backbone coordinates
        if ((proteinLabel || nucleotideLabel) && a->second->classification != eSideChainAtom) {
            if (IsAminoAcid()) {
                if (a->second->name == " CA ") {
                    l1 = atom;
                    labelColor = atomStyle.color;
                    alphaVisible = (atomStyle.style != StyleManager::eNotDisplayed);
                }
                else if (a->second->name == " C  ") l2 = atom;
                else if (a->second->name == " N  ") l3 = atom;
            } else if (IsNucleotide()) {
                if (a->second->name == " P  ") {
                    l1 = atom;
                    labelColor = atomStyle.color;
                    alphaVisible = (atomStyle.style != StyleManager::eNotDisplayed);
                }
                // labeling by alphas seems to work better for nucleotides
//                else if (a->second->name == " C4*") l2 = atom;
//                else if (a->second->name == " C5*") l3 = atom;
            }
        }
    }

    // if not all backbone atoms present (e.g. alpha only), use alpha coords of neighboring residues
    if (l1 && (!l2 || !l3)) {
        Molecule::ResidueMap::const_iterator prevRes, nextRes;
        const AtomCoord *prevAlpha, *nextAlpha;
        if ((prevRes=molecule->residues.find(id - 1)) != molecule->residues.end() &&
            prevRes->second->alphaID != NO_ALPHA_ID &&
            (prevAlpha=atomSet->GetAtom(AtomPntr(molecule->id, id - 1, prevRes->second->alphaID))) != NULL &&
            (nextRes=molecule->residues.find(id + 1)) != molecule->residues.end() &&
            nextRes->second->alphaID != NO_ALPHA_ID &&
            (nextAlpha=atomSet->GetAtom(AtomPntr(molecule->id, id + 1, nextRes->second->alphaID))) != NULL)
        {
            l2 = prevAlpha;
            l3 = nextAlpha;
            alphaOnly = true;
        }
    }

    // draw residue (but not terminus) labels, assuming we have the necessary coordinates and
    // that alpha atoms are visible
    if (alphaVisible && (proteinLabel|| nucleotideLabel)) {
        Vector labelPosition;
        CNcbiOstrstream oss;

        double contrast = Colors::IsLightColor(settings.backgroundColor) ? 0 : 1;

        // protein label
        if (IsAminoAcid() && l1 && l2 && l3) {
            // position
            if (alphaOnly) {
                Vector forward = - ((l2->site - l1->site) + (l3->site - l1->site));
                forward.normalize();
                labelPosition = l1->site + 1.5 * forward;
            } else {
                Vector up = vector_cross(l2->site - l1->site, l3->site - l1->site);
                up.normalize();
                Vector forward = (-((l2->site - l1->site) + (l3->site - l1->site)) / 2);
                forward.normalize();
                labelPosition = l1->site + 1.5 * forward + 1.5 * up;
            }
            // text
            if (settings.proteinLabels.type == StyleSettings::eOneLetter) {
                oss << code;
            } else if (settings.proteinLabels.type == StyleSettings::eThreeLetter) {
                for (unsigned int i=0; i<nameGraph.size() && i<3; ++i)
                    oss << ((i == 0) ? (char) toupper((unsigned char) nameGraph[0]) : (char) tolower((unsigned char) nameGraph[i]));
            }
            // add number if necessary
            if (settings.proteinLabels.numbering == StyleSettings::eSequentialNumbering)
                oss << ' ' << id;
            else if (settings.proteinLabels.numbering == StyleSettings::ePDBNumbering)
                oss << namePDB;
            // contrasting color? (default to CA's color)
            if (settings.proteinLabels.white) labelColor.Set(contrast, contrast, contrast);
        }

        // nucleotide label
        else if (IsNucleotide() && l2 && l3) {
            if (alphaOnly) {
                Vector forward = - ((l2->site - l1->site) + (l3->site - l1->site));
                forward.normalize();
                labelPosition = l1->site + 3 * forward;
            } else {
                labelPosition = l3->site + 3 * (l3->site - l2->site);
            }
            // text
            if (settings.nucleotideLabels.type == StyleSettings::eOneLetter) {
                oss << code;
            } else if (settings.nucleotideLabels.type == StyleSettings::eThreeLetter) {
                for (unsigned int i=0; i<3; ++i)
                    if (nameGraph.size() > i && nameGraph[i] != ' ')
                        oss << nameGraph[i];
            }
            // add number if necessary
            if (settings.nucleotideLabels.numbering == StyleSettings::eSequentialNumbering)
                oss << ' ' << id;
            else if (settings.nucleotideLabels.numbering == StyleSettings::ePDBNumbering)
                oss << namePDB;
            // contrasting color? (default to C4*'s color)
            if (settings.nucleotideLabels.white) labelColor.Set(contrast, contrast, contrast);
        }

        // draw label
        if (oss.pcount() > 0) {
            string labelText = (string) CNcbiOstrstreamToString(oss);

            // apply highlight color if necessary
            if (GlobalMessenger()->IsHighlighted(molecule, id))
                labelColor = GlobalColors()->Get(Colors::eHighlight);

            parentSet->renderer->DrawLabel(labelText, labelPosition, labelColor);
        }
    }

    return true;
}
Esempio n. 12
-1
DTerr	ImporterGeometryTWM::import(GeometryResource *target, std::string args)
{
	FilePath pathname(target->path());
	
    // open the file
    BinaryFileStream	file;
	FileManager::open(file, pathname, true);
     
    // 
	// Read_ in header
	//
	
	DTuint magic;
	file >> magic;
    if (magic != MAGIC) {
        return DT3_ERR_FILE_WRONG_TYPE;
    }
	
	DTuint version;
	file >> version;
	
	//
	// Read_ in data
	//
	
	_normals_count = 0;
	_uv_set_0_count = 0;
	_uv_set_1_count = 0;
	_weights_count = 0;
	
	DTint section,size;
	file >> section >> size;
	switch(section) {
		case FILE:		read_file(file, size);			break;
		default:		WARNINGMSG("Invalid section");	break;
	};
	
	//
	// Build Streams
	//
    
	// Calculate sizes needed
	DTuint joints_size = 0;
	
	for (DTuint i = 0; i < _meshes.size(); ++i) {
		joints_size += _meshes[i]._joint_names.size();
	}

	// allocate joint names, force first one to always be identity
	std::vector<std::string>	joint_names;
	joint_names.resize(joints_size);	
	DTuint joint_offset = 0;	// Account for identity above

	for (DTuint i = 0; i < _meshes.size(); ++i) {
		MeshData &meshdata = _meshes[i];

        if (meshdata._vertices.size() == 0)
            continue;
    
        std::shared_ptr<Mesh> mesh = Mesh::create();
		
		// copy joint names
		for (DTuint j = 0; j < meshdata._joint_names.size(); ++j) {
			joint_names[joint_offset + j] = meshdata._joint_names[j];
		}
        
        std::vector<Vector3> vertex_stream;
        std::vector<Vector3> normals_stream;
        std::vector<Vector2> uvs_stream_0;
        std::vector<Vector2> uvs_stream_1;
        std::vector<Vector4> weights_strength;
        std::vector<WeightsIndex> weights_index;
        std::vector<Triangle> indices;
        
        vertex_stream = meshdata._vertices;
        normals_stream = meshdata._normals;
        uvs_stream_0 = meshdata._uv_sets[0]._uvs;
        uvs_stream_1 = meshdata._uv_sets[1]._uvs;
        indices = meshdata._indices;
		
        if (meshdata._weights.size()) {
            
            weights_index.resize(meshdata._weights.size());
            weights_strength.resize(meshdata._weights.size());
        
            for (DTuint j = 0; j < meshdata._weights.size(); ++j) {
                weights_strength[j] = Vector4(      meshdata._weights[j].weight_1(),
                                                    meshdata._weights[j].weight_2(),
                                                    meshdata._weights[j].weight_3(),
                                                    meshdata._weights[j].weight_4()    );

                weights_index[j] = WeightsIndex(    meshdata._weights[j].bone_1(),
                                                    meshdata._weights[j].bone_2(),
                                                    meshdata._weights[j].bone_3(),
                                                    meshdata._weights[j].bone_4()    );
            
            }
        }

        mesh->set_vertex_stream(vertex_stream);
        mesh->set_normals_stream(normals_stream);
        mesh->set_uv_stream0(uvs_stream_0);
        mesh->set_uv_stream1(uvs_stream_1);
        mesh->set_index_stream(indices);
        mesh->set_weights_index_stream(weights_index);
        mesh->set_weights_strength_stream(weights_strength);

        // Some stuff we can generate
        if (normals_stream.size() == 0)     mesh->generate_normals();
        if (uvs_stream_0.size() != 0)       mesh->generate_tangents();
        
        // Add the mesh
        target->add_mesh(mesh);

		joint_offset += (DTushort) meshdata._joint_names.size();
	}
		 	
	
	// Build skeleton
	std::vector<SkeletonJoint> s;
	build_skeleton(joint_names, _skeleton._joints, s);
    
    Skeleton skeleton;
    skeleton.set_skeleton(s);
    
	target->set_skeleton(skeleton);

	return DT3_ERR_NONE;
}