Пример #1
0
bool frame::safe_for_sender(JavaThread *thread) {

  address _SP = (address) sp();
  address _FP = (address) fp();
  address _UNEXTENDED_SP = (address) unextended_sp();
  // sp must be within the stack
  bool sp_safe = (_SP <= thread->stack_base()) &&
                 (_SP >= thread->stack_base() - thread->stack_size());

  if (!sp_safe) {
    return false;
  }

  // unextended sp must be within the stack and above or equal sp
  bool unextended_sp_safe = (_UNEXTENDED_SP <= thread->stack_base()) &&
                            (_UNEXTENDED_SP >= _SP);

  if (!unextended_sp_safe) return false;

  // an fp must be within the stack and above (but not equal) sp
  bool fp_safe = (_FP <= thread->stack_base()) &&
                 (_FP > _SP);

  // We know sp/unextended_sp are safe only fp is questionable here

  // If the current frame is known to the code cache then we can attempt to
  // to construct the sender and do some validation of it. This goes a long way
  // toward eliminating issues when we get in frame construction code

  if (_cb != NULL ) {

    // First check if frame is complete and tester is reliable
    // Unfortunately we can only check frame complete for runtime stubs and nmethod
    // other generic buffer blobs are more problematic so we just assume they are
    // ok. adapter blobs never have a frame complete and are never ok.

    if (!_cb->is_frame_complete_at(_pc)) {
      if (_cb->is_nmethod() || _cb->is_adapter_blob() || _cb->is_runtime_stub()) {
        return false;
      }
    }

    // Could just be some random pointer within the codeBlob
    if (!_cb->code_contains(_pc)) {
      return false;
    }

    // Entry frame checks
    if (is_entry_frame()) {
      // an entry frame must have a valid fp.

      if (!fp_safe) {
        return false;
      }

      // Validate the JavaCallWrapper an entry frame must have

      address jcw = (address)entry_frame_call_wrapper();

      bool jcw_safe = (jcw <= thread->stack_base()) && ( jcw > _FP);

      return jcw_safe;

    }

    intptr_t* younger_sp = sp();
    intptr_t* _SENDER_SP = sender_sp(); // sender is actually just _FP
    bool adjusted_stack = is_interpreted_frame();

    address   sender_pc = (address)younger_sp[I7->sp_offset_in_saved_window()] + pc_return_offset;


    // We must always be able to find a recognizable pc
    CodeBlob* sender_blob = CodeCache::find_blob_unsafe(sender_pc);
    if (sender_pc == NULL ||  sender_blob == NULL) {
      return false;
    }

    // Could be a zombie method
    if (sender_blob->is_zombie() || sender_blob->is_unloaded()) {
      return false;
    }

    // It should be safe to construct the sender though it might not be valid

    frame sender(_SENDER_SP, younger_sp, adjusted_stack);

    // Do we have a valid fp?
    address sender_fp = (address) sender.fp();

    // an fp must be within the stack and above (but not equal) current frame's _FP

    bool sender_fp_safe = (sender_fp <= thread->stack_base()) &&
                   (sender_fp > _FP);

    if (!sender_fp_safe) {
      return false;
    }


    // If the potential sender is the interpreter then we can do some more checking
    if (Interpreter::contains(sender_pc)) {
      return sender.is_interpreted_frame_valid(thread);
    }

    // Could just be some random pointer within the codeBlob
    if (!sender.cb()->code_contains(sender_pc)) {
      return false;
    }

    // We should never be able to see an adapter if the current frame is something from code cache
    if (sender_blob->is_adapter_blob()) {
      return false;
    }

    if( sender.is_entry_frame()) {
      // Validate the JavaCallWrapper an entry frame must have

      address jcw = (address)sender.entry_frame_call_wrapper();

      bool jcw_safe = (jcw <= thread->stack_base()) && ( jcw > sender_fp);

      return jcw_safe;
    }

    // If the frame size is 0 something (or less) is bad because every nmethod has a non-zero frame size
    // because you must allocate window space

    if (sender_blob->frame_size() <= 0) {
      assert(!sender_blob->is_nmethod(), "should count return address at least");
      return false;
    }

    // The sender should positively be an nmethod or call_stub. On sparc we might in fact see something else.
    // The cause of this is because at a save instruction the O7 we get is a leftover from an earlier
    // window use. So if a runtime stub creates two frames (common in fastdebug/debug) then we see the
    // stale pc. So if the sender blob is not something we'd expect we have little choice but to declare
    // the stack unwalkable. pd_get_top_frame_for_signal_handler tries to recover from this by unwinding
    // that initial frame and retrying.

    if (!sender_blob->is_nmethod()) {
      return false;
    }

    // Could put some more validation for the potential non-interpreted sender
    // frame we'd create by calling sender if I could think of any. Wait for next crash in forte...

    // One idea is seeing if the sender_pc we have is one that we'd expect to call to current cb

    // We've validated the potential sender that would be created

    return true;

  }

  // Must be native-compiled frame. Since sender will try and use fp to find
  // linkages it must be safe

  if (!fp_safe) return false;

  // could try and do some more potential verification of native frame if we could think of some...

  return true;
}
Пример #2
0
void
__bb_exit_func (void)
{
  fp (12, Ext ? Ext : "<none>");
}
Пример #3
0
void null_pointer_with_function_pointer() {
  int * (*fp)();
  fp = foo;
  int *x = fp();
  *x = 3;
}
Пример #4
0
int rom_installer_main(int argc, char *argv[])
{
    // Make stdout unbuffered
    setvbuf(stdout, nullptr, _IONBF, 0);

    std::string rom_id;
    std::string zip_file;

    int opt;

    static struct option long_options[] = {
        {"romid", required_argument, 0, 'r'},
        {"help",  no_argument,       0, 'h'},
        {0, 0, 0, 0}
    };

    int long_index = 0;

    while ((opt = getopt_long(argc, argv, "r:h", long_options, &long_index)) != -1) {
        switch (opt) {
        case 'r':
            rom_id = optarg;
            break;

        case 'h':
            rom_installer_usage(false);
            return EXIT_SUCCESS;

        default:
            rom_installer_usage(true);
            return EXIT_FAILURE;
        }
    }

    if (argc - optind != 1) {
        rom_installer_usage(true);
        return EXIT_FAILURE;
    }

    zip_file = argv[optind];

    if (rom_id.empty()) {
        fprintf(stderr, "-r/--romid must be specified\n");
        return EXIT_FAILURE;
    }

    if (zip_file.empty()) {
        fprintf(stderr, "Invalid zip file path\n");
        return EXIT_FAILURE;
    }


    // Translate paths
    char *emu_source_path = getenv("EMULATED_STORAGE_SOURCE");
    char *emu_target_path = getenv("EMULATED_STORAGE_TARGET");
    if (emu_source_path && emu_target_path) {
        if (util::starts_with(zip_file, emu_target_path)) {
            printf("Zip path uses EMULATED_STORAGE_TARGET\n");
            zip_file.erase(0, strlen(emu_target_path));
            zip_file.insert(0, emu_source_path);
        }
    }


    // Make sure install type is valid
    if (!Roms::is_valid(rom_id)) {
        fprintf(stderr, "Invalid ROM ID: %s\n", rom_id.c_str());
        return EXIT_FAILURE;
    }

    auto rom = Roms::get_current_rom();
    if (!rom) {
        fprintf(stderr, "Could not determine current ROM\n");
        return EXIT_FAILURE;
    }

    if (rom->id == rom_id) {
        fprintf(stderr, "Can't install over current ROM (%s)\n",
                rom_id.c_str());
        return EXIT_FAILURE;
    }


    if (geteuid() != 0) {
        fprintf(stderr, "rom-installer must be run as root\n");
        return EXIT_FAILURE;
    }


    // Since many stock ROMs, most notably TouchWiz, don't allow setting SELinux
    // to be globally permissive, we'll do the next best thing: modify the
    // policy to make every type permissive.

    bool selinux_supported = true;
    bool backup_successful = true;

    struct stat sb;
    if (stat("/sys/fs/selinux", &sb) < 0) {
        printf("SELinux not supported. No need to modify policy\n");
        selinux_supported = false;
    }

    if (selinux_supported) {
        backup_successful = backup_sepolicy(sepolicy_bak_path);

        printf("Patching SELinux policy to make all types permissive\n");
        if (!patch_sepolicy()) {
            fprintf(stderr, "Failed to patch current SELinux policy\n");
        }
    }

    auto restore_selinux = util::finally([&] {
        if (selinux_supported && backup_successful) {
            printf("Restoring backup SELinux policy\n");
            if (!restore_sepolicy(sepolicy_bak_path)) {
                fprintf(stderr, "Failed to restore SELinux policy\n");
            }
        }
    });


    autoclose::file fp(autoclose::fopen(MULTIBOOT_LOG_INSTALLER, "wb"));
    if (!fp) {
        fprintf(stderr, "Failed to open %s: %s\n",
                MULTIBOOT_LOG_INSTALLER, strerror(errno));
        return EXIT_FAILURE;
    }

    fix_multiboot_permissions();

    // mbtool logging
    util::log_set_logger(std::make_shared<util::StdioLogger>(fp.get(), false));

    // libmbp logging
    mbp::setLogCallback(mbp_log_cb);

    // Start installing!
    RomInstaller ri(zip_file, rom_id, fp.get());
    return ri.start_installation() ? EXIT_SUCCESS : EXIT_FAILURE;
}
Пример #5
0
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        Usage();
        return EXIT_FAILURE;
    }

    int cmd = !strcmp(argv[2], "list") ? CMD_LIST
            : !strcmp(argv[2], "get") ? CMD_GET
            : !strcmp(argv[2], "del") ? CMD_DEL
            : !strcmp(argv[2], "put") ? CMD_PUT
            : !strcmp(argv[2], "move") ? CMD_MOVE
            : !strcmp(argv[2], "rename") ? CMD_RENAME
            : !strcmp(argv[2], "type") ? CMD_TYPE
            : !strcmp(argv[2], "getpcx") ? CMD_GETPCX
            : !strcmp(argv[2], "putpcx") ? CMD_PUTPCX
            : CMD_INVALID;

    if (cmd == CMD_INVALID)
    {
        fprintf(stderr, "abuse-tool: unknown command `%s'\n", argv[2]);
        return EXIT_FAILURE;
    }

    /* Check argument count and file access mode */
    char const *mode = "rwb";
    int minargc = 3;

    switch (cmd)
    {
    case CMD_LIST:
        mode = "rb"; // Read-only access
        break;
    case CMD_GET:
        minargc = 4;
        mode = "rb"; // Read-only access
        break;
    case CMD_PUT:
        minargc = 6;
        break;
    case CMD_MOVE:
        minargc = 5;
        break;
    case CMD_RENAME:
        minargc = 5;
        break;
    case CMD_TYPE:
        minargc = 5;
        break;
    case CMD_DEL:
        minargc = 4;
        break;
    case CMD_GETPCX:
        minargc = 4;
        mode = "rb"; // Read-only access
        break;
    case CMD_PUTPCX:
        minargc = 6;
        break;
    }

    if (argc < minargc)
    {
        fprintf(stderr, "abuse-tool: too few arguments for command `%s'\n",
                         argv[2]);
        return EXIT_FAILURE;
    }

    /* Open the SPEC file */
    char tmpfile[4096];
    char const *file = argv[1];
    snprintf(tmpfile, 4096, "%s.tmp", file);

    jFILE fp(file, mode);
    if (fp.open_failure())
    {
        fprintf(stderr, "ERROR - could not open %s\n", file);
        return EXIT_FAILURE;
    }

    spec_directory dir(&fp);

    /* Now really execute commands */
    if (cmd == CMD_LIST)
    {
        printf("   id  type    bytes   crc  name & information\n");
        printf(" ----  ----  -------  ----  ----------------------------\n");

        dir.FullyLoad(&fp);

        for (int i = 0; i < dir.total; i++)
        {
            spec_entry *se = dir.entries[i];

            /* Print basic information */
            printf("% 5i   % 3i % 8i  %04x  %s", i, se->type, (int)se->size,
                   calc_crc(se->data, se->size), se->name);

            /* Is there anything special to say? */
            switch (se->type)
            {
            case SPEC_IMAGE:
            case SPEC_FORETILE:
            case SPEC_BACKTILE:
            case SPEC_CHARACTER:
            case SPEC_CHARACTER2:
              {
                image *im = new image(&fp, se);
                printf(" \t# %i x %i pixels", im->Size().x, im->Size().y);
                delete im;
                break;
              }
            case SPEC_PALETTE:
              {
                palette *pal = new palette(se, &fp);
                printf(" \t# %i colors", pal->pal_size());
                delete pal;
                break;
              }
#if 0
            default:
              {
                /* Try to print a representation of the item */
                int has_binary = 0;
                for (int i = 0; i < Min(20, (int)se->size); i++)
                {
                    uint8_t ch = ((uint8_t *)se->data)[i];
                    if (ch < 0x20 || ch >= 0x7f)
                        has_binary++;
                }
                if (has_binary <= 2 && se->size > 5)
                    has_binary = 0;

                printf(" \t# ");
                if (!has_binary)
                    putchar('\"');

                size_t max = Min(has_binary ? 15 : 30, (int)se->size);
                for (size_t i = 0; i < max; i++)
                {
                    uint8_t ch = ((uint8_t *)se->data)[i];
                    if (has_binary)
                        printf("%02x ", ch);
                    else if (ch && (ch < 0x20 || ch >= 0x7f))
                        printf("\\x%02x", ch);
                    else if (ch)
                        putchar(ch);
                    else
                        printf("\\0");
                }
                if (se->size > max)
                    printf("...");
                else if (!has_binary)
                    printf("\"");
                break;
              }
#endif
            }

            /* Finish line */
            putchar('\n');
        }

        return EXIT_SUCCESS;
    }
    else if (cmd == CMD_GET)
    {
        int id = atoi(argv[3]);

        if (id < 0 || id >= dir.total)
        {
            fprintf(stderr, "abuse-tool: id %i not found in %s\n", id, file);
            return EXIT_FAILURE;
        }

        spec_entry *se = dir.entries[id];
        fp.seek(se->offset, SEEK_SET);

        for (size_t todo = se->size; todo > 0; )
        {
            uint8_t buf[1024];
            int step = Min((int)todo, 1024);
            fp.read(buf, step);
            fwrite(buf, step, 1, stdout);
            todo -= step;
        }
        return EXIT_SUCCESS;
    }
    else if (cmd == CMD_GETPCX)
    {
        palette *pal;
        int imgid = atoi(argv[3]);
        int palid = argc > 4 ? atoi(argv[4]) : -1;

        for (int i = 0; palid == -1 && i < dir.total; i++)
            if (dir.entries[i]->type == SPEC_PALETTE)
                palid = i;

        if (palid == -1)
            pal = new palette(256);
        else
            pal = new palette(dir.entries[palid], &fp);

        image *im = new image(&fp, dir.entries[imgid]);
        write_PCX(im, pal, "/dev/stdout");
        delete im;
        delete pal;
        return EXIT_SUCCESS;
    }
    else if (cmd == CMD_MOVE)
    {
        int src = atoi(argv[3]);
        int dst = atoi(argv[4]);

        if (src < 0 || dst < 0 || src >= dir.total || dst >= dir.total)
        {
            fprintf(stderr, "abuse-tool: ids %i/%i out of range\n", src, dst);
            return EXIT_FAILURE;
        }

        dir.FullyLoad(&fp);

        spec_entry *tmp = dir.entries[src];
        for (int d = src < dst ? 1 : -1; src != dst; src += d)
            dir.entries[src] = dir.entries[src + d];
        dir.entries[dst] = tmp;
    }
    else if (cmd == CMD_RENAME || cmd == CMD_TYPE)
    {
        int id = atoi(argv[3]);

        if (id < 0 || id >= dir.total)
        {
            fprintf(stderr, "abuse-tool: id %i out of range\n", id);
            return EXIT_FAILURE;
        }

        dir.FullyLoad(&fp);
        if (cmd == CMD_RENAME)
            dir.entries[id]->name = argv[4];
        else
            dir.entries[id]->type = (uint8_t)atoi(argv[4]);
    }
    else if (cmd == CMD_DEL)
    {
        int id = atoi(argv[3]);

        if (id < 0 || id >= dir.total)
        {
            fprintf(stderr, "abuse-tool: id %i out of range\n", id);
            return EXIT_FAILURE;
        }

        dir.total--;
        for (int i = id; i < dir.total; i++)
            dir.entries[i] = dir.entries[i + 1];

        dir.FullyLoad(&fp);
    }
    else if (cmd == CMD_PUT || cmd == CMD_PUTPCX)
    {
        int id = atoi(argv[3]);
        uint8_t type = atoi(argv[4]);

        if (id == -1)
            id = dir.total;

        if (id < 0 || id > dir.total)
        {
            fprintf(stderr, "abuse-tool: id %i out of range\n", id);
            return EXIT_FAILURE;
        }

        dir.FullyLoad(&fp);
        dir.total++;
        dir.entries = (spec_entry **)realloc(dir.entries,
                                             dir.total * sizeof(spec_entry *));
        for (int i = dir.total - 1; i-- > id; )
            dir.entries[i + 1] = dir.entries[i];

        char *name = strrchr(argv[5], '/');
        if (!name)
            name = argv[5];

        uint8_t *data;
        size_t len;

        if (cmd == CMD_PUT)
        {
            jFILE fp2(argv[5], "rb");
            if (fp2.open_failure())
            {
                fprintf(stderr, "abuse-tool: cannot open %s\n", argv[5]);
                return EXIT_FAILURE;
            }
            len = fp2.file_size();
            data = (uint8_t *)malloc(len);
            fp2.read(data, len);
        }
        else
        {
            palette *pal = NULL;
            image *im = read_PCX(argv[5], pal);
            if (!im)
            {
                fprintf(stderr, "abuse-tool: cannot open %s\n", argv[5]);
                return EXIT_FAILURE;
            }
            vec2i size = im->Size();
            len = 2 * sizeof(uint16_t) + size.x * size.y;
            data = (uint8_t *)malloc(len);
            uint16_t x = lltl((uint16_t)size.x);
            uint16_t y = lltl((uint16_t)size.y);
            memcpy(data, &x, sizeof(x));
            memcpy(data + 2, &y, sizeof(y));
            memcpy(data + 4, im->scan_line(0), size.x * size.y);
        }
        dir.entries[id] = new spec_entry(type, name, NULL, len, 0);
        dir.entries[id]->data = data;
    }
    else
    {
        /* Not implemented yet */
        return EXIT_FAILURE;
    }

    /* If we get here, we need to write the directory back */
    dir.calc_offsets();
    fp.seek(0, SEEK_SET); // FIXME: create a new file
    dir.write(&fp);
    for (int i = 0; i < dir.total; i++)
        fp.write(dir.entries[i]->data, dir.entries[i]->size);

    return EXIT_SUCCESS;
}
Пример #6
0
bool MeshTablesSurface<PFP>::importTrian(const std::string& filename, std::vector<std::string>& attrNames)
{
	VertexAttribute<typename PFP::VEC3> positions =  m_map.template getAttribute<typename PFP::VEC3, VERTEX>("position") ;

	if (!positions.isValid())
		positions = m_map.template addAttribute<typename PFP::VEC3, VERTEX>("position") ;

	attrNames.push_back(positions.name()) ;

	AttributeContainer& container = m_map.template getAttributeContainer<VERTEX>() ;

	// open file
	std::ifstream fp(filename.c_str(), std::ios::in);
	if (!fp.good())
	{
		CGoGNerr << "Unable to open file " << filename << CGoGNendl;
		return false;
	}

	// read nb of points
	fp >> m_nbVertices;

	// read points
	std::vector<unsigned int> verticesID;
	verticesID.reserve(m_nbVertices);

	for (unsigned int i = 0; i < m_nbVertices; ++i)
	{
		VEC3 pos;
		fp >> pos[0];
		fp >> pos[1];
		fp >> pos[2];
		unsigned int id = container.insertLine();
		positions[id] = pos;
		verticesID.push_back(id);
	}

	// read nb of faces
	fp >> m_nbFaces;
	m_nbEdges.reserve(m_nbFaces);
	m_emb.reserve(3*m_nbFaces);

	// read indices of faces
	for (unsigned int i = 0; i < m_nbFaces; ++i)
	{
		m_nbEdges.push_back(3);
		// read the three vertices of triangle
		int pt;
		fp >> pt;
		m_emb.push_back(verticesID[pt]);
		fp >> pt;
		m_emb.push_back(verticesID[pt]);
		fp >> pt;
		m_emb.push_back(verticesID[pt]);

		// neighbour not always good in files !!
		int neigh;
		fp >> neigh;
		fp >> neigh;
		fp >> neigh;
	}

	fp.close();
	return true;
}
Пример #7
0
bool MeshTablesSurface<PFP>::importMeshBin(const std::string& filename, std::vector<std::string>& attrNames)
{
	VertexAttribute<typename PFP::VEC3> positions = m_map.template getAttribute<typename PFP::VEC3, VERTEX>("position") ;

	if (!positions.isValid())
	{
		positions = m_map.template addAttribute<typename PFP::VEC3, VERTEX>("position") ;
	}

	attrNames.push_back(positions.name()) ;

	AttributeContainer& container = m_map.template getAttributeContainer<VERTEX>() ;

	// open file
	std::ifstream fp(filename.c_str(), std::ios::in | std::ios::binary);
	if (!fp.good())
	{
		CGoGNerr << "Unable to open file " << filename << CGoGNendl;
		return false;
	}

	// Read header
    unsigned int Fmin, Fmax ;
    fp.read((char*)&m_nbVertices, sizeof(unsigned int)) ;
    fp.read((char*)&m_nbFaces, sizeof(unsigned int)) ;
    fp.read((char*)&Fmin, sizeof(unsigned int)) ;
    fp.read((char*)&Fmax, sizeof(unsigned int)) ;

    assert((Fmin == 3 && Fmax == 3) || !"Only triangular faces are handled yet") ;

    // Read foreach vertex
	std::vector<unsigned int> verticesID ;
	verticesID.reserve(m_nbVertices) ;

    for (unsigned int vxNum = 0 ; vxNum < m_nbVertices ; ++vxNum)
    {
    	Geom::Vec3f pos ;
    	fp.read((char*) &pos[0], sizeof(float)) ;
    	fp.read((char*) &pos[1], sizeof(float)) ;
    	fp.read((char*) &pos[2], sizeof(float)) ;

		unsigned int id = container.insertLine() ;
		positions[id] = pos ;

		verticesID.push_back(id) ;
    }

    // Read foreach face
	m_nbEdges.reserve(m_nbFaces) ;
	m_emb.reserve(m_nbVertices * 8) ;

	for (unsigned int fNum = 0; fNum < m_nbFaces; ++fNum)
	{
		const unsigned int faceSize = 3 ;
		fp.read((char*) &faceSize, sizeof(float)) ;
		m_nbEdges.push_back(faceSize) ;

		for (unsigned int i = 0 ; i < faceSize; ++i)
		{
			unsigned int index ; // index of embedding
			fp.read((char*) &index, sizeof(unsigned int)) ;
			m_emb.push_back(verticesID[index]) ;
		}
	}

	fp.close() ;
	return true ;
}
Пример #8
0
double ConfusionMatrix::precision(int category) {
  int denom = tp(category) + fp(category);
  if(denom == 0)
    return 0.0;
  return ((double)tp(category)) / denom;
}
Пример #9
0
//------------------------------------------------------------------------------
void CIwLayoutElementToolbar::LoadBar()
{
    wxTextFile fp(CIwTheApp->MakeAbsoluteFilename(m_FileName));
    if (!fp.Exists() || !fp.Open()) return;

    for (int i=0; i<(int)fp.GetLineCount(); i++)
    {
        std::vector<wxString> argv;
        CIwLayoutMenuDef* def;

        int argc=SuperSplit(fp[i],argv,L" \t\n");
        if (argc<1) continue;

        if (argv[0].IsSameAs(L"section",false))
        {
            if (argc<2) continue;

            m_Title=argv[1];
        }
        else if (argv[0].IsSameAs(L"tool",false))
        {
            if (argc<3) continue;

            def=new CIwLayoutMenuDef(NULL,FTOOLITEM_TOOL);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
        else if (argv[0].IsSameAs(L"icon",false))
        {
            if (argc<4) continue;

            def=new CIwLayoutMenuDef(NULL,FTOOLITEM_ICON);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
        else if (argv[0].IsSameAs(L"check",false))
        {
            if (argc<3) continue;

            def=new CIwLayoutMenuDef(NULL,FMENUITEM_CHECK);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
        else if (argv[0].IsSameAs(L"toggle",false))
        {
            if (argc<3) continue;

            def=new CIwLayoutMenuDef(NULL,FTOOLITEM_TOGGLE);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
        else if (argv[0].IsSameAs(L"list",false))
        {
            if (argc<3) continue;

            def=new CIwLayoutMenuDef(NULL,FMENUITEM_LIST);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
        else if (argv[0].IsSameAs(L"inlist",false))
        {
            if (argc<3) continue;

            def=new CIwLayoutMenuDef(NULL,FMENUITEM_INLIST);
            def->Setup(argv);
            m_MenuDef.push_back(def);
        }
    }
}
Пример #10
0
void mapping(QVector<T1>* _vec, T2 _var, T3 (*fp)(T1, T2))
{
    for(int i = 0;i < _vec.size(); ++i)  {
        fp(_vec[i], _var);
    }
}
Пример #11
0
void emitCIterFree(IRGS& env, int32_t iterId) {
  gen(env, CIterFree, IterId(iterId), fp(env));
}
Пример #12
0
intptr_t *frame::initial_deoptimization_info() {
  // unused... but returns fp() to minimize changes introduced by 7087445
  return fp();
}
Пример #13
0
BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) {
  assert(is_interpreted_frame(), "interpreted frame expected");
  Method* method = interpreter_frame_method();
  BasicType type = method->result_type();

  if (method->is_native()) {
    // Prior to notifying the runtime of the method_exit the possible result
    // value is saved to l_scratch and d_scratch.

#ifdef CC_INTERP
    interpreterState istate = get_interpreterState();
    intptr_t* l_scratch = (intptr_t*) &istate->_native_lresult;
    intptr_t* d_scratch = (intptr_t*) &istate->_native_fresult;
#else /* CC_INTERP */
    intptr_t* l_scratch = fp() + interpreter_frame_l_scratch_fp_offset;
    intptr_t* d_scratch = fp() + interpreter_frame_d_scratch_fp_offset;
#endif /* CC_INTERP */

    address l_addr = (address)l_scratch;
#ifdef _LP64
    // On 64-bit the result for 1/8/16/32-bit result types is in the other
    // word half
    l_addr += wordSize/2;
#endif

    switch (type) {
      case T_OBJECT:
      case T_ARRAY: {
#ifdef CC_INTERP
        *oop_result = istate->_oop_temp;
#else
        oop obj = cast_to_oop(at(interpreter_frame_oop_temp_offset));
        assert(obj == NULL || Universe::heap()->is_in(obj), "sanity check");
        *oop_result = obj;
#endif // CC_INTERP
        break;
      }

      case T_BOOLEAN : { jint* p = (jint*)l_addr; value_result->z = (jboolean)((*p) & 0x1); break; }
      case T_BYTE    : { jint* p = (jint*)l_addr; value_result->b = (jbyte)((*p) & 0xff); break; }
      case T_CHAR    : { jint* p = (jint*)l_addr; value_result->c = (jchar)((*p) & 0xffff); break; }
      case T_SHORT   : { jint* p = (jint*)l_addr; value_result->s = (jshort)((*p) & 0xffff); break; }
      case T_INT     : value_result->i = *(jint*)l_addr; break;
      case T_LONG    : value_result->j = *(jlong*)l_scratch; break;
      case T_FLOAT   : value_result->f = *(jfloat*)d_scratch; break;
      case T_DOUBLE  : value_result->d = *(jdouble*)d_scratch; break;
      case T_VOID    : /* Nothing to do */ break;
      default        : ShouldNotReachHere();
    }
  } else {
    intptr_t* tos_addr = interpreter_frame_tos_address();

    switch(type) {
      case T_OBJECT:
      case T_ARRAY: {
        oop obj = cast_to_oop(*tos_addr);
        assert(obj == NULL || Universe::heap()->is_in(obj), "sanity check");
        *oop_result = obj;
        break;
      }
      case T_BOOLEAN : { jint* p = (jint*)tos_addr; value_result->z = (jboolean)((*p) & 0x1); break; }
      case T_BYTE    : { jint* p = (jint*)tos_addr; value_result->b = (jbyte)((*p) & 0xff); break; }
      case T_CHAR    : { jint* p = (jint*)tos_addr; value_result->c = (jchar)((*p) & 0xffff); break; }
      case T_SHORT   : { jint* p = (jint*)tos_addr; value_result->s = (jshort)((*p) & 0xffff); break; }
      case T_INT     : value_result->i = *(jint*)tos_addr; break;
      case T_LONG    : value_result->j = *(jlong*)tos_addr; break;
      case T_FLOAT   : value_result->f = *(jfloat*)tos_addr; break;
      case T_DOUBLE  : value_result->d = *(jdouble*)tos_addr; break;
      case T_VOID    : /* Nothing to do */ break;
      default        : ShouldNotReachHere();
    }
  };

  return type;
}
Пример #14
0
intptr_t* frame::interpreter_frame_sender_sp() const {
  assert(is_interpreted_frame(), "interpreted frame expected");
  return fp();
}
Пример #15
0
void swap_polygon_model_data(ubyte *data)
{
	int i;
	short n;
	g3s_uvl *uvl_val;
	ubyte *p = data;
	
	short_swap(wp(p));
	
	while (w(p) != OP_EOF) {
		switch (w(p)) {
			case OP_DEFPOINTS:
				short_swap(wp(p + 2));
				n = w(p+2);
				for (i = 0; i < n; i++)
					vms_vector_swap(vp((p + 4) + (i * sizeof(vms_vector))));
					p += n*sizeof(struct vms_vector) + 4;
				break;
				
			case OP_DEFP_START:
				short_swap(wp(p + 2));
				short_swap(wp(p + 4));
				n = w(p+2);
				for (i = 0; i < n; i++)
					vms_vector_swap(vp((p + 8) + (i * sizeof(vms_vector))));
					p += n*sizeof(struct vms_vector) + 8;
				break;
				
			case OP_FLATPOLY:
				short_swap(wp(p+2));
				n = w(p+2);
				vms_vector_swap(vp(p + 4));
				vms_vector_swap(vp(p + 16));
				short_swap(wp(p+28));
				for (i=0; i < n; i++)
					short_swap(wp(p + 30 + (i * 2)));
					p += 30 + ((n&~1)+1)*2;
				break;
				
			case OP_TMAPPOLY:
				short_swap(wp(p+2));
				n = w(p+2);
				vms_vector_swap(vp(p + 4));
				vms_vector_swap(vp(p + 16));
				for (i=0;i<n;i++) {
					uvl_val = (g3s_uvl *)((p+30+((n&~1)+1)*2) + (i * sizeof(g3s_uvl)));
					fix_swap(&uvl_val->u);
					fix_swap(&uvl_val->v);
				}
					short_swap(wp(p+28));
				for (i=0;i<n;i++)
					short_swap(wp(p + 30 + (i * 2)));
					p += 30 + ((n&~1)+1)*2 + n*12;
				break;
				
			case OP_SORTNORM:
				vms_vector_swap(vp(p + 4));
				vms_vector_swap(vp(p + 16));
				short_swap(wp(p + 28));
				short_swap(wp(p + 30));
				swap_polygon_model_data(p + w(p+28));
				swap_polygon_model_data(p + w(p+30));
				p += 32;
				break;
				
			case OP_RODBM:
				vms_vector_swap(vp(p + 20));
				vms_vector_swap(vp(p + 4));
				short_swap(wp(p+2));
				fix_swap(fp(p + 16));
				fix_swap(fp(p + 32));
				p+=36;
				break;
				
			case OP_SUBCALL:
				short_swap(wp(p+2));
				vms_vector_swap(vp(p+4));
				short_swap(wp(p+16));
				swap_polygon_model_data(p + w(p+16));
				p += 20;
				break;
				
			case OP_GLOW:
				short_swap(wp(p + 2));
				p += 4;
				break;
				
			default:
				Error("invalid polygon model\n"); //Int3();
		}
		short_swap(wp(p));
	}
}
Пример #16
0
GrTexture* GaussianBlur(GrContext* context,
                        GrTexture* srcTexture,
                        bool canClobberSrc,
                        const SkRect& dstBounds,
                        const SkRect* srcBounds,
                        float sigmaX,
                        float sigmaY,
                        GrTextureProvider::SizeConstraint constraint) {
    SkASSERT(context);
    SkIRect clearRect;
    int scaleFactorX, radiusX;
    int scaleFactorY, radiusY;
    int maxTextureSize = context->caps()->maxTextureSize();
    sigmaX = adjust_sigma(sigmaX, maxTextureSize, &scaleFactorX, &radiusX);
    sigmaY = adjust_sigma(sigmaY, maxTextureSize, &scaleFactorY, &radiusY);

    SkPoint srcOffset = SkPoint::Make(-dstBounds.x(), -dstBounds.y());
    SkRect localDstBounds = SkRect::MakeWH(dstBounds.width(), dstBounds.height());
    SkRect localSrcBounds;
    SkRect srcRect;
    if (srcBounds) {
        srcRect = localSrcBounds = *srcBounds;
        srcRect.offset(srcOffset);
        srcBounds = &localSrcBounds;
    } else {
        srcRect = localDstBounds;
    }

    scale_rect(&srcRect, 1.0f / scaleFactorX, 1.0f / scaleFactorY);
    srcRect.roundOut(&srcRect);
    scale_rect(&srcRect, static_cast<float>(scaleFactorX),
                         static_cast<float>(scaleFactorY));

    // setup new clip
    GrClip clip(localDstBounds);

    SkASSERT(kBGRA_8888_GrPixelConfig == srcTexture->config() ||
             kRGBA_8888_GrPixelConfig == srcTexture->config() ||
             kAlpha_8_GrPixelConfig == srcTexture->config());

    GrSurfaceDesc desc;
    desc.fFlags = kRenderTarget_GrSurfaceFlag;
    desc.fWidth = SkScalarFloorToInt(dstBounds.width());
    desc.fHeight = SkScalarFloorToInt(dstBounds.height());
    desc.fConfig = srcTexture->config();

    GrTexture* dstTexture;
    GrTexture* tempTexture;
    SkAutoTUnref<GrTexture> temp1, temp2;

    temp1.reset(context->textureProvider()->createTexture(desc, constraint));
    dstTexture = temp1.get();
    if (canClobberSrc) {
        tempTexture = srcTexture;
    } else {
        temp2.reset(context->textureProvider()->createTexture(desc, constraint));
        tempTexture = temp2.get();
    }

    if (nullptr == dstTexture || nullptr == tempTexture) {
        return nullptr;
    }

    SkAutoTUnref<GrDrawContext> srcDrawContext;

    for (int i = 1; i < scaleFactorX || i < scaleFactorY; i *= 2) {
        GrPaint paint;
        SkMatrix matrix;
        matrix.setIDiv(srcTexture->width(), srcTexture->height());
        SkRect dstRect(srcRect);
        if (srcBounds && i == 1) {
            SkRect domain;
            matrix.mapRect(&domain, *srcBounds);
            domain.inset((i < scaleFactorX) ? SK_ScalarHalf / srcTexture->width() : 0.0f,
                         (i < scaleFactorY) ? SK_ScalarHalf / srcTexture->height() : 0.0f);
            SkAutoTUnref<const GrFragmentProcessor> fp(GrTextureDomainEffect::Create(
                srcTexture,
                matrix,
                domain,
                GrTextureDomain::kDecal_Mode,
                GrTextureParams::kBilerp_FilterMode));
            paint.addColorFragmentProcessor(fp);
            srcRect.offset(-srcOffset);
            srcOffset.set(0, 0);
        } else {
            GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kBilerp_FilterMode);
            paint.addColorTextureProcessor(srcTexture, matrix, params);
        }
        paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
        scale_rect(&dstRect, i < scaleFactorX ? 0.5f : 1.0f,
                             i < scaleFactorY ? 0.5f : 1.0f);

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        dstDrawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect);

        srcDrawContext.swap(dstDrawContext);
        srcRect = dstRect;
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);
        localSrcBounds = srcRect;
    }

    // For really small blurs (certainly no wider than 5x5 on desktop gpus) it is faster to just
    // launch a single non separable kernel vs two launches
    srcRect = localDstBounds;
    if (sigmaX > 0.0f && sigmaY > 0.0f &&
            (2 * radiusX + 1) * (2 * radiusY + 1) <= MAX_KERNEL_SIZE) {
        // We shouldn't be scaling because this is a small size blur
        SkASSERT((1 == scaleFactorX) && (1 == scaleFactorY));

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        convolve_gaussian_2d(dstDrawContext, clip, srcRect, srcOffset,
                             srcTexture, radiusX, radiusY, sigmaX, sigmaY, srcBounds);

        srcDrawContext.swap(dstDrawContext);
        srcRect.offsetTo(0, 0);
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);

    } else {
        scale_rect(&srcRect, 1.0f / scaleFactorX, 1.0f / scaleFactorY);
        srcRect.roundOut(&srcRect);
        const SkIRect srcIRect = srcRect.roundOut();
        if (sigmaX > 0.0f) {
            if (scaleFactorX > 1) {
                // TODO: if we pass in the source draw context we don't need this here
                if (!srcDrawContext) {
                    srcDrawContext.reset(context->drawContext(srcTexture->asRenderTarget()));
                    if (!srcDrawContext) {
                        return nullptr;
                    }        
                }

                // Clear out a radius to the right of the srcRect to prevent the
                // X convolution from reading garbage.
                clearRect = SkIRect::MakeXYWH(srcIRect.fRight, srcIRect.fTop,
                                              radiusX, srcIRect.height());
                srcDrawContext->clear(&clearRect, 0x0, false);
            }

            SkAutoTUnref<GrDrawContext> dstDrawContext(
                                             context->drawContext(dstTexture->asRenderTarget()));
            if (!dstDrawContext) {
                return nullptr;
            }
            convolve_gaussian(dstDrawContext, clip, srcRect,
                              srcTexture, Gr1DKernelEffect::kX_Direction, radiusX, sigmaX,
                              srcBounds, srcOffset);
            srcDrawContext.swap(dstDrawContext);
            srcTexture = dstTexture;
            srcRect.offsetTo(0, 0);
            SkTSwap(dstTexture, tempTexture);
            localSrcBounds = srcRect;
            srcOffset.set(0, 0);
        }

        if (sigmaY > 0.0f) {
            if (scaleFactorY > 1 || sigmaX > 0.0f) {
                // TODO: if we pass in the source draw context we don't need this here
                if (!srcDrawContext) {
                    srcDrawContext.reset(context->drawContext(srcTexture->asRenderTarget()));
                    if (!srcDrawContext) {
                        return nullptr;
                    }        
                }

                // Clear out a radius below the srcRect to prevent the Y
                // convolution from reading garbage.
                clearRect = SkIRect::MakeXYWH(srcIRect.fLeft, srcIRect.fBottom,
                                              srcIRect.width(), radiusY);
                srcDrawContext->clear(&clearRect, 0x0, false);
            }

            SkAutoTUnref<GrDrawContext> dstDrawContext(
                                               context->drawContext(dstTexture->asRenderTarget()));
            if (!dstDrawContext) {
                return nullptr;
            }
            convolve_gaussian(dstDrawContext, clip, srcRect,
                              srcTexture, Gr1DKernelEffect::kY_Direction, radiusY, sigmaY,
                              srcBounds, srcOffset);

            srcDrawContext.swap(dstDrawContext);
            srcTexture = dstTexture;
            srcRect.offsetTo(0, 0);
            SkTSwap(dstTexture, tempTexture);
        }
    }
    const SkIRect srcIRect = srcRect.roundOut();

    if (scaleFactorX > 1 || scaleFactorY > 1) {
        SkASSERT(srcDrawContext);

        // Clear one pixel to the right and below, to accommodate bilinear
        // upsampling.
        clearRect = SkIRect::MakeXYWH(srcIRect.fLeft, srcIRect.fBottom,
                                      srcIRect.width() + 1, 1);
        srcDrawContext->clear(&clearRect, 0x0, false);
        clearRect = SkIRect::MakeXYWH(srcIRect.fRight, srcIRect.fTop,
                                      1, srcIRect.height());
        srcDrawContext->clear(&clearRect, 0x0, false);
        SkMatrix matrix;
        matrix.setIDiv(srcTexture->width(), srcTexture->height());

        GrPaint paint;
        // FIXME:  this should be mitchell, not bilinear.
        GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kBilerp_FilterMode);
        paint.addColorTextureProcessor(srcTexture, matrix, params);
        paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);

        SkRect dstRect(srcRect);
        scale_rect(&dstRect, (float) scaleFactorX, (float) scaleFactorY);

        SkAutoTUnref<GrDrawContext> dstDrawContext(
                                context->drawContext(dstTexture->asRenderTarget()));
        if (!dstDrawContext) {
            return nullptr;
        }
        dstDrawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect);

        srcDrawContext.swap(dstDrawContext);
        srcRect = dstRect;
        srcTexture = dstTexture;
        SkTSwap(dstTexture, tempTexture);
    }

    return SkRef(srcTexture);
}
Пример #17
0
void g() {
  void (*fp)(S *) = f;
  // CHECK: call i1 @llvm.bitset.test(i8* {{.*}}, metadata ![[VOIDS:[0-9]+]])
  fp(0);
}
Пример #18
0
int wxStackWalker::InitFrames(wxStackFrame *arr, size_t n, void **addresses, char **syminfo)
{
    // we need to launch addr2line tool to get this information and we need to
    // have the program name for this
    wxString exepath = wxStackWalker::GetExePath();
    if ( exepath.empty() )
    {
        exepath = wxStandardPaths::Get().GetExecutablePath();
        if ( exepath.empty() )
        {
            wxLogDebug(wxT("Cannot parse stack frame because the executable ")
                       wxT("path could not be detected"));
            return 0;
        }
    }

    // build the command line for executing addr2line or atos under OS X using
    // char* directly to avoid the conversions from Unicode
#ifdef __WXOSX__
    int len = snprintf(g_buf, BUFSIZE, "atos -p %d", (int)getpid());
#else
    int len = snprintf(g_buf, BUFSIZE, "addr2line -C -f -e \"%s\"", (const char*) exepath.mb_str());
#endif
    len = (len <= 0) ? strlen(g_buf) : len;     // in case snprintf() is broken
    for (size_t i=0; i<n; i++)
    {
        snprintf(&g_buf[len], BUFSIZE - len, " %p", addresses[i]);
        len = strlen(g_buf);
    }

    //wxLogDebug(wxT("piping the command '%s'"), g_buf);  // for debug only

    wxStdioPipe fp(g_buf, "r");
    if ( !fp )
        return 0;

    // parse the output reusing the same buffer to avoid any big memory
    // allocations which could fail if our program is in a bad state
    wxString name, filename;
    unsigned long line = 0,
                  curr = 0;
    for  ( size_t i = 0; i < n; i++ )
    {
#ifdef __WXOSX__
        wxString buffer;
        if ( !ReadLine(fp, i, &buffer) )
            return false;

        line = 0;
        filename.clear();

        // We can get back either the string in the following format:
        //
        //      func(args) (in module) (file:line)
        //
        // or just the same address back if it couldn't be resolved.
        const size_t posIn = buffer.find("(in ");
        if ( posIn != wxString::npos )
        {
            name.assign(buffer, 0, posIn);

            size_t posAt = buffer.find(") (", posIn + 3);
            if ( posAt != wxString::npos )
            {
                posAt += 3; // Skip ") ("

                // Discard the two last characters which are ")\n"
                wxString location(buffer, posAt, buffer.length() - posAt - 2);

                wxString linenum;
                filename = location.BeforeFirst(':', &linenum);
                if ( !linenum.empty() )
                    linenum.ToULong(&line);
            }
        }
#else // !__WXOSX__
        // 1st line has function name
        if ( !ReadLine(fp, i, &name) )
            return false;

        name = wxString::FromAscii(g_buf);
        name.RemoveLast(); // trailing newline

        if ( name == wxT("??") )
            name.clear();

        // 2nd one -- the file/line info
        if ( !ReadLine(fp, i, &filename) )
            return false;

        const size_t posColon = filename.find(wxT(':'));
        if ( posColon != wxString::npos )
        {
            // parse line number (it's ok if it fails, this will just leave
            // line at its current, invalid, 0 value)
            wxString(filename, posColon + 1, wxString::npos).ToULong(&line);

            // remove line number from 'filename'
            filename.erase(posColon);
            if ( filename == wxT("??") )
                filename.clear();
        }
        else
        {
            wxLogDebug(wxT("Unexpected addr2line format: \"%s\" - ")
                       wxT("the semicolon is missing"),
                       filename.c_str());
        }
#endif // __WXOSX__/!__WXOSX__

        // now we've got enough info to initialize curr-th stack frame
        // (at worst, only addresses[i] and syminfo[i] have been initialized,
        //  but wxStackFrame::OnGetName may still be able to get function name):
        arr[curr++].Set(name, filename, syminfo[i], i, line, addresses[i]);
    }

    return curr;
}
Пример #19
0
bool MeshTablesSurface<PFP>::importOff(const std::string& filename, std::vector<std::string>& attrNames)
{
	VertexAttribute<typename PFP::VEC3> positions = m_map.template getAttribute<typename PFP::VEC3, VERTEX>("position") ;

	if (!positions.isValid())
		positions = m_map.template addAttribute<typename PFP::VEC3, VERTEX>("position") ;

	attrNames.push_back(positions.name()) ;

	AttributeContainer& container = m_map.template getAttributeContainer<VERTEX>() ;

	// open file
	std::ifstream fp(filename.c_str(), std::ios::in);
	if (!fp.good())
	{
		CGoGNerr << "Unable to open file " << filename << CGoGNendl;
		return false;
	}

    std::string ligne;

    // lecture de OFF
    std::getline (fp, ligne);
    if (ligne.rfind("OFF") == std::string::npos)
    {
		CGoGNerr << "Problem reading off file: not an off file" << CGoGNendl;
		CGoGNerr << ligne << CGoGNendl;
		return false;
    }

    // lecture des nombres de sommets/faces/aretes
	int nbe;
    {
    	do
    	{
    		std::getline (fp, ligne);
    	} while (ligne.size() == 0);

	    std::stringstream oss(ligne);
		oss >> m_nbVertices;
		oss >> m_nbFaces;
		oss >> nbe;
    }

	//lecture sommets
	std::vector<unsigned int> verticesID;
	verticesID.reserve(m_nbVertices);
	for (unsigned int i = 0; i < m_nbVertices;++i)
	{
    	do
    	{
    		std::getline (fp, ligne);
    	} while (ligne.size() == 0);

		std::stringstream oss(ligne);

		float x,y,z;
		oss >> x;
		oss >> y;
		oss >> z;
		// on peut ajouter ici la lecture de couleur si elle existe
		VEC3 pos(x,y,z);

		unsigned int id = container.insertLine();
		positions[id] = pos;

		verticesID.push_back(id);
	}

	// lecture faces
	// normalement nbVertices*8 devrait suffire largement
	m_nbEdges.reserve(m_nbFaces);
	m_emb.reserve(m_nbVertices*8);

	for (unsigned int i = 0; i < m_nbFaces; ++i)
	{
    	do
    	{
    		std::getline (fp, ligne);
    	} while (ligne.size() == 0);

		std::stringstream oss(ligne);
		unsigned int n;
		oss >> n;
		m_nbEdges.push_back(n);
		for (unsigned int j = 0; j < n; ++j)
		{
			int index; // index du plongement
			oss >> index;
			m_emb.push_back(verticesID[index]);
		}
		// on peut ajouter ici la lecture de couleur si elle existe
	}

	fp.close();
	return true;
}
Пример #20
0
std::vector<std::string> get_words(std::string file_path) {
    std::ifstream fp(file_path);
    std::stringstream iss;
    iss << fp.rdbuf();
    return split(iss.str(), std::vector<char> { ' ', '\n' } );
}
Пример #21
0
bool MeshTablesSurface<PFP>::importObj(const std::string& filename, std::vector<std::string>& attrNames)
{
	VertexAttribute<typename PFP::VEC3> positions =  m_map.template getAttribute<typename PFP::VEC3, VERTEX>("position") ;

	if (!positions.isValid())
		positions = m_map.template addAttribute<typename PFP::VEC3, VERTEX>("position") ;

	attrNames.push_back(positions.name()) ;

	AttributeContainer& container = m_map.template getAttributeContainer<VERTEX>() ;

	// open file
	std::ifstream fp(filename.c_str(), std::ios::binary);
	if (!fp.good())
	{
		CGoGNerr << "Unable to open file " << filename << CGoGNendl;
		return false;
	}

//	fp.seekg(0, std::ios::end);
//	int ab = fp.tellg();
//	fp.seekg(0, std::ios::beg);
//	int ac = fp.tellg();

    std::string ligne;
    std::string tag;

    do
    {
    	fp >> tag;
    	std::getline (fp, ligne);
    }while (tag != std::string("v"));

    // lecture des sommets
	std::vector<unsigned int> verticesID;
	verticesID.reserve(102400); // on tape large (400Ko wahouuuuu !!)

	unsigned int i = 0;
    do
    {
		if (tag == std::string("v"))
		{
			std::stringstream oss(ligne);
		
			float x,y,z;
			oss >> x;
			oss >> y;
			oss >> z;

			VEC3 pos(x,y,z);

			unsigned int id = container.insertLine();
			positions[id] = pos;

			verticesID.push_back(id);
			i++;
		}

		fp >> tag;
    	std::getline(fp, ligne);
    } while (!fp.eof());
Пример #22
0
/* TODO: I wonder why this function ALWAYS returns 0 */
int loadPNG(ePtr<gPixmap> &result, const char *filename, int accel)
{
	if (pixmapFromTable(result, filename) == 0)
		return 0;

	CFile fp(filename, "rb");

	if (!fp)
	{
		eDebug("[ePNG] couldn't open %s", filename );
		return 0;
	}
	{
		uint8_t header[8];
		if (!fread(header, 1, 8, fp))
		{
			eDebug("[ePNG] failed to get png header");
			return 0;
		}
		if (png_sig_cmp(header, 0, 8))
		{
			eDebug("[ePNG] header size mismatch");
			return 0;
		}
	}
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
	if (!png_ptr)
	{
		eDebug("[ePNG] failed to create read struct");
		return 0;
	}
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
	{
		eDebug("[ePNG] failed to create info struct");
		png_destroy_read_struct(&png_ptr, (png_infopp)0, (png_infopp)0);
		return 0;
	}
	png_infop end_info = png_create_info_struct(png_ptr);
	if (!end_info)
	{
		eDebug("[ePNG] failed to create end info struct");
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
		return 0;
	}
	if (setjmp(png_jmpbuf(png_ptr)))
	{
		eDebug("[ePNG] png setjump failed or activated");
		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
		result = 0;
		return 0;
	}
	png_init_io(png_ptr, fp);
	png_set_sig_bytes(png_ptr, 8);
	png_read_info(png_ptr, info_ptr);

	png_uint_32 width, height;
	int bit_depth;
	int color_type;
	int interlace_type;
	int channels;
	int trns;

	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, 0, 0);
	channels = png_get_channels(png_ptr, info_ptr);
	trns = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS);
	//eDebug("[ePNG] %s: before %dx%dx%dbpcx%dchan coltyp=%d", filename, (int)width, (int)height, bit_depth, channels, color_type);

	/*
	 * gPixmaps use 8 bits per channel. rgb pixmaps are stored as abgr.
	 * So convert 1,2 and 4 bpc to 8bpc images that enigma can blit
	 * so add 'empty' alpha channel
	 * Expand G+tRNS to GA, RGB+tRNS to RGBA
	 */
	if (bit_depth == 16)
		png_set_strip_16(png_ptr);
	if (bit_depth < 8)
		png_set_packing (png_ptr);

	if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
		png_set_expand_gray_1_2_4_to_8(png_ptr);
	if (color_type == PNG_COLOR_TYPE_GRAY && trns)
		png_set_tRNS_to_alpha(png_ptr);
	if ((color_type == PNG_COLOR_TYPE_GRAY && trns) || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
		png_set_gray_to_rgb(png_ptr);
		png_set_bgr(png_ptr);
	}

	if (color_type == PNG_COLOR_TYPE_RGB) {
		if (trns)
			png_set_tRNS_to_alpha(png_ptr);
		else
			png_set_add_alpha(png_ptr, 255, PNG_FILLER_AFTER);
	}

	if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA)
		png_set_bgr(png_ptr);

	// Update the info structures after the transformations take effect
	if (interlace_type != PNG_INTERLACE_NONE)
		png_set_interlace_handling(png_ptr);  // needed before read_update_info()
	png_read_update_info (png_ptr, info_ptr);
	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
	channels = png_get_channels(png_ptr, info_ptr);

	result = new gPixmap(width, height, bit_depth * channels, pixmapDisposed, accel);
	gUnmanagedSurface *surface = result->surface;

	png_bytep *rowptr = new png_bytep[height];
	for (unsigned int i = 0; i < height; i++)
		rowptr[i] = ((png_byte*)(surface->data)) + i * surface->stride;
	png_read_image(png_ptr, rowptr);

	delete [] rowptr;

	int num_palette = -1, num_trans = -1;
	if (color_type == PNG_COLOR_TYPE_PALETTE) {
		if (png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)) {
			png_color *palette;
			png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
			if (num_palette)
				surface->clut.data = new gRGB[num_palette];
			else
				surface->clut.data = 0;
			surface->clut.colors = num_palette;

			for (int i = 0; i < num_palette; i++) {
				surface->clut.data[i].a = 0;
				surface->clut.data[i].r = palette[i].red;
				surface->clut.data[i].g = palette[i].green;
				surface->clut.data[i].b = palette[i].blue;
			}
			if (trns) {
				png_byte *trans;
				png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, 0);
				for (int i = 0; i < num_trans; i++)
					surface->clut.data[i].a = 255 - trans[i];
				for (int i = num_trans; i < num_palette; i++)
					surface->clut.data[i].a = 0;
			}
		}
		else {
			surface->clut.data = 0;
			surface->clut.colors = 0;
		}
		surface->clut.start = 0;
	}
	pixmapToTable(result, filename);
	//eDebug("[ePNG] %s: after  %dx%dx%dbpcx%dchan coltyp=%d cols=%d trans=%d", filename, (int)width, (int)height, bit_depth, channels, color_type, num_palette, num_trans);

	png_read_end(png_ptr, end_info);
	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
	return 0;
}
Пример #23
0
int main(int argc, char **argv) {
    int i;
    int interact=false;

    c_word_file_name = (char*)malloc(sizeof(char) * MAX_FULLPATH_NAME);
    c_list_file_name = (char*)malloc(sizeof(char) * MAX_FULLPATH_NAME);
    c_vocab_file_name = (char*)malloc(sizeof(char) * MAX_FULLPATH_NAME);

    if (argc == 1) {
        printf("HPCA: Hellinger PCA for Word Embeddings, nearest neighbors\n");
        printf("Author: Remi Lebret ([email protected])\n\n");
        printf("Usage options:\n");
        printf("\t-verbose <int>\n");
        printf("\t\tSet verbosity: 0=off or 1=on (default)\n");
        printf("\t-word-file <file>\n");
        printf("\t\tFile containing word embeddings to evaluate\n");
        printf("\t-vocab-file <file>\n");
        printf("\t\tFile containing word vocabulary\n");
        printf("\t-list-file <file>\n");
        printf("\t\tFile containing a list of words from which the nearest neighbors will be computed, otherwise interactive mode\n");
        printf("\t-top <int>\n");
        printf("\t\tNumber of nearest neighbors; default 10\n");
        printf("\t-threads <int>\n");
        printf("\t\tNumber of threads; default 8\n");
        printf("\nExample usage:\n");
        printf("./eval -word-file path_to_words -vocab-file path_to_vocab -top 10\n\n");
        return 0;
    }

    if ((i = find_arg((char *)"-verbose", argc, argv)) > 0) verbose = atoi(argv[i + 1]);
    if ((i = find_arg((char *)"-word-file", argc, argv)) > 0) strcpy(c_word_file_name, argv[i + 1]);
    if ((i = find_arg((char *)"-list-file", argc, argv)) > 0) strcpy(c_list_file_name, argv[i + 1]);
    else interact=true;
    if ((i = find_arg((char *)"-vocab-file", argc, argv)) > 0) strcpy(c_vocab_file_name, argv[i + 1]);
    if ((i = find_arg((char *)"-top", argc, argv)) > 0) top = atoi(argv[i + 1]);
    if ((i = find_arg((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);


    if (verbose){
        fprintf(stderr, "HPCA: Hellinger PCA for Word Embeddings\n");
        fprintf(stderr, "Author: Remi Lebret ([email protected])\n");
        fprintf(stderr, "---------------------------------------\n");
        fprintf(stderr, "nearest neighbors\n" );
        fprintf(stderr, "---------------------------------------\n\n");
    }

    /* set the optimal number of threads */
    num_threads = MultiThread::optimal_nb_thread(num_threads, 1, num_threads);
    if (verbose) fprintf(stderr, "number of pthreads = %d\n", num_threads);
    // set threads
    Eigen::setNbThreads(num_threads);

    /* check whether files exist */
    is_file(c_word_file_name);
    is_file(c_vocab_file_name);

    /* get vocabulary */
    getvocab();

    /* get words */
    Eigen::MatrixXf words;
    readMatrix(c_word_file_name, words);

    int idx;
    fprintf(stderr, "---------------------------------------\n");
    if (interact){
        /* initialize random seed: */
        srand (time(NULL));

        fprintf(stderr,"Interactive mode, please enter words.\nAlternative options:\n - press 'R' key for a random sample\n - press 'Q' key to exit\n");
        fprintf(stderr, "---------------------------------------\n");
        while(1){
            char w[MAX_TOKEN];
            fprintf(stderr, "\nEnter a word: ");
            scanf("%s",&w);

            if ( (strcmp(w,"q") == 0) || (strcmp(w,"Q") == 0) ){ // exit
                break;
            }else{
                if ( (strcmp(w,"r") == 0) || (strcmp(w,"R") == 0) ){
                    idx = rand() % vocab_size + 1;
                }
                else{
                    if ( (idx = hash->value(w))==-1){
                        fprintf(stderr, "unknown word, please enter a new one\n\n");
                        continue;
                    }
                }
                fprintf(stderr, "computing nearest neighbors of %s...\n", tokename[idx]);
                getnn(stderr, words, idx);
            }
        }
    }else{
        is_file(c_list_file_name);
        fprintf(stderr, "computing nearest neighbors of words in %s...\n", c_list_file_name);
        File fp((std::string(c_list_file_name)));
        // open file
        fp.open();
        // get vocabulary
        char * line = NULL;
        int i=0;
        while( (line=fp.getline()) != NULL) {
            if ( (idx = hash->value(line))!=-1){
                fprintf(stdout, "%s --> ", line);
                getnn(stdout, words, idx);
            }
        }
        fp.close();
    }

    /* release memory */
    free(c_vocab_file_name);
    free(c_word_file_name);
    for (int i=0; i<vocab_size; i++) if (tokename[i]) free(tokename[i]);
    free(tokename);
    delete hash;

    if (verbose){
        fprintf(stderr, "\ndone\n");
        fprintf(stderr, "---------------------------------------\n");
    }
    return 0;
}
Пример #24
0
float chem_root(float (*f)(float), float (*fp)(float), float x) {
  while (fabsf(f(x))>EPS)
    x -= f(x)/fp(x);
  return x;
}
Пример #25
0
	virtual void call(ParamT t) {
		fp(t);
	}
Пример #26
0
void calc_light_table(palette *pal)
{
  white_light=(unsigned char *)malloc(256*64);
  green_light=(unsigned char *)malloc(256*64);
  for (int i=0; i<TTINTS; i++)
      tints[i]=(uchar *)malloc(256);

  jFILE fp("light.tbl","rb");
  int recalc=0;
  if (fp.open_failure()) recalc=1;
  else
  {
    if (fp.read_uint16()!=calc_crc((unsigned char *)pal->addr(),768))
      recalc=1;
    else
    {
      fp.read(white_light,256*64);
      fp.read(green_light,256*64);
      for (i=0; i<TTINTS; i++)
        fp.read(tints[i],256);
    }
  }

  if (recalc)
  {
    fprintf(stderr,"Palette has changed, recalculating light table...\n");
    fprintf(stderr,"white : ");
    for (int color=0; color<256; color++)
    {
      unsigned char r,g,b;
      pal->get(color,r,g,b);
      if (color%16==0)
        fprintf(stderr,"%d ",color);
      for (int intensity=63; intensity>=0; intensity--)
      {
    if (r>0 || g>0 || b>0)
          white_light[intensity*256+color]=pal->find_closest(r,g,b);
    else
          white_light[intensity*256+color]=0;
    if (r) r--;  if (g) g--;  if (b) b--;
      }
    }

    fprintf(stderr,"green : ");
    for (color=0; color<256; color++)
    {
      unsigned char r,g,b;
      pal->get(color,r,g,b);
      r=r*3/5; b=b*3/5; g+=7; if (g>255) g=255;
      if (color%16==0)
        fprintf(stderr,"%d ",color);
      for (int intensity=63; intensity>=0; intensity--)
      {
    if (r>0 || g>0 || b>0)
          green_light[intensity*256+color]=pal->find_closest(r,g,b);
    else
          green_light[intensity*256+color]=0;
    if (r) r--;
    if ((intensity&1)==1)
      if (g) g--;
    if (b) b--;
      }
    }

    dprintf("\ncalculating tints : \n");
    uchar t[TTINTS*6]={ 0,0,0,0,0,0, // normal
                   0,0,0,1,0,0,     // red
           0,0,0,1,1,0,     // yellow
           0,0,0,1,0,1,     // purple
           0,0,0,1,1,1,     // gray
           0,0,0,0,1,0,     // green
           0,0,0,0,0,1,     // blue
           0,0,0,0,1,1,     // cyan






           0,0,0,0,0,0   // reverse green  (night vision effect)
         } ;
    uchar *ti=t+6;
    uchar *c;
    for (i=0,c=tints[0]; i<256; i++,c++) *c=i;  // make the normal tint (maps everthing to itself)
    for (i=0,c=tints[TTINTS-1]; i<256; i++,c++)  // reverse green
    {
      int r=pal->red(i)/2,g=255-pal->green(i)-30,b=pal->blue(i)*3/5+50;
      if (g<0) g=0;
      if (b>255) b=0;
      *c=pal->find_closest(r,g,b);
    }

    // make the colored tints
    for (i=1; i<TTINTS-1; i++)
    {
      calc_tint(tints[i],ti[0],ti[1],ti[2],ti[3],ti[4],ti[5],pal);
      ti+=6;
    }



    jFILE f("light.tbl","wb");
    f.write_uint16(calc_crc((unsigned char *)pal->addr(),768));
    f.write(white_light,256*64);
    f.write(green_light,256*64);
    for (int i=0; i<TTINTS; i++)
      f.write(tints[i],256);
  }
}
Пример #27
0
void Rescaler:: rebuild( Bubble &bubble )
{
    //static int fid = 0;
    
    const size_t n  = bubble.size;
    const size_t n1 = n+1;
    assert( s.size()     == n1 );
    assert( ax.size()    == n1 );
    assert( ay.size()    == n1 );
    assert(period>0);
    assert(bubble.area>0);
    assert(a_list.size >= 3);
    
#if 0
    {
        ios::ocstream fp( vformat("org%d.dat",fid), false);
        for( size_t i=1; i <= n1; ++i )
        {
            fp("%g %g %g\n", s[i], ax[i], ay[i]);
        }
        fp("%g %g %g\n", period, ax[1], ay[1]);
    }
#endif
    
    Real sa[4] = { 0 };
    Real xa[4] = { 0 };
    Real ya[4] = { 0 };
    
    //--------------------------------------------------------------------------
    // rebuild the bubble
    //--------------------------------------------------------------------------
    //std::cerr << "rebuilding " << a_list.size << " points" << std::endl;
    bubble.empty();
    for( const abscissa *a = a_list.head; a; a=a->next )
    {
        const Real s_i = a->s;
        assert(s_i>=0);
        assert(s_i<period);
        //-- locate the abscissa
        const size_t j1  = __locate_abscissa(s_i, s);
        const size_t j2  = j1+1;
        
        //-- fill the middle points
        sa[1] = s[j1]; xa[1] = ax[j1]; ya[1] = ay[j1];
        sa[2] = s[j2]; xa[2] = ax[j2]; ya[2] = ay[j2];
        
        //-- fill the left point
        if( j1 <= 1 )
        {
            sa[0] = sa[1] - (s[n1] - s[n]); xa[0] = ax[n]; ya[0] = ay[n];
        }
        else
        {
            const size_t j0 = j1-1; assert(j0>0);
            sa[0] = s[j0]; xa[0] = ax[j0]; ya[0] = ay[j0];
        }
        
        //-- fill the right point
        if( j2 >= n1 )
        {
            sa[3] = s[n1] + (s[2]-s[1]);
            xa[3] = ax[1];
            ya[3] = ay[1];
        }
        else
        {
            const size_t j3 = j2+1;
            sa[3] = s[j3]; xa[3] = ax[j3]; ya[3] = ay[j3];
        }
#if 1
        const Vertex v = __interpv(s_i, sa, xa, ya, 4);
#else
        const Real    fac = (s_i - sa[1])/(sa[2]-sa[1]);
        const Vertex  v( xa[1] + fac * ( xa[2] - xa[1]), ya[1] + fac * ( ya[2] - ya[1]) );
#endif
        bubble.append()->vertex = v;
    }
    assert(bubble.size==a_list.size);
    
#if 0
    {
        ios::ocstream fp( vformat("ref%d.dat",fid), false);
        const abscissa *a = a_list.head;
        const Tracer   *p = bubble.root;
        while(a)
        {
            fp("%g %g %g\n", a->s, p->vertex.x, p->vertex.y);
            a=a->next;
            p=p->next;
        }
        fp("%g %g %g\n", period, p->vertex.x, p->vertex.y);
        
        ++fid;
    }
#endif
    
    //--------------------------------------------------------------------------
    // rebuild its metrics
    //--------------------------------------------------------------------------
    build_metrics(bubble,RescaleWithConstantPressure);
    
}
Пример #28
0
void vms_vector_swap(vms_vector *v)
{
	fix_swap(fp(&v->x));
	fix_swap(fp(&v->y));
	fix_swap(fp(&v->z));
}
Пример #29
0
void ADMMCut::WriteStiffness(string offset, string rotation)
{
	string path = path_;

	string offset_path = path + "/" + offset;
	string rotation_path = path + "/" + rotation;

	vector<FILE*> fp(2);
	fp[0] = fopen(offset_path.c_str(), "w+");
	fp[1] = fopen(rotation_path.c_str(), "w+");

	fprintf(fp[0], "#offset colormap#\r\n");
	fprintf(fp[1], "#rotation colormap#\r\n",
		0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

	int N = ptr_frame_->SizeOfVertList();
	vector<vector<double>> ss(N);
	for (int i = 0; i < N; i++)
	{
		ss[i].resize(2);
		if (ptr_dualgraph_->isExistingVert(i) && !ptr_frame_->isFixed(i))
		{
			int j = ptr_dualgraph_->v_dual_id(i);

			VX offset(3);
			VX rotation(3);
			for (int k = 0; k < 3; k++)
			{
				offset[k] = D_[j * 6 + k];
				rotation[k] = D_[j * 6 + k + 3];
			}

			if (offset.norm() >= Dt_tol_ || rotation.norm() >= Dr_tol_)
			{
				printf(".............. %lf %lf\n", offset.norm(), rotation.norm());
				getchar();
			}
			ss[i][0] = offset.norm() / Dt_tol_;
			ss[i][1] = rotation.norm() / Dr_tol_;
		}
		else
		{
			ss[i][0] = 0.0;
			ss[i][1] = 0.0;
		}

		//if (ptr_dualgraph_->isExistingVert(i))
		{
			point p = ptr_frame_->GetVert(i)->RenderPos();
			for (int j = 0; j < 2; j++)
			{
				fprintf(fp[j], "%lf %lf %lf ", p.x(), p.y(), p.z());

				double r;
				double g;
				double b;

				if (ss[i][j] < 0.25)
				{
					r = 0.0;
					g = ss[i][j] * 4.0;
					b = 1.0;
				}
				else
					if (ss[i][j] < 0.5)
					{
						r = 0.0;
						g = 1.0;
						b = (0.5 - ss[i][j]) * 4.0;
					}
					else
						if (ss[i][j] < 0.75)
						{
							r = (ss[i][j] - 0.5) * 4.0;
							g = 1.0;
							b = 0.0;
						}
						else
						{
							r = 1.0;
							g = (1.0 - ss[i][j]) * 4.0;
							b = 0.0;
						}

				fprintf(fp[j], "%lf %lf %lf\r\n", r, g, b);
			}
		}
	}

	fclose(fp[0]);
	fclose(fp[1]);
}
Пример #30
0
void SFTPWorkerThread::ProcessRequest(ThreadRequest* request)
{
    SFTPThreadRequet* req = dynamic_cast<SFTPThreadRequet*>(request);
    // Check if we need to open an ssh connection
    wxString currentAccout = m_sftp ? m_sftp->GetAccount() : "";
    wxString requestAccount = req->GetAccount().GetAccountName();

    if(currentAccout.IsEmpty() || currentAccout != requestAccount) {
        m_sftp.reset(NULL);
        DoConnect(req);
    }

    if(req->GetDirection() == SFTPThreadRequet::kConnect) {
        // Nothing more to be done here
        // Disconnect
        m_sftp.reset(NULL);
        return;
    }

    wxString msg;
    wxString accountName = req->GetAccount().GetAccountName();
    if(m_sftp && m_sftp->IsConnected()) {

        try {

            msg.Clear();
            if(req->GetDirection() == SFTPThreadRequet::kUpload) {
                DoReportStatusBarMessage(wxString() << _("Uploading file: ") << req->GetRemoteFile());
                m_sftp->CreateRemoteFile(req->GetRemoteFile(), wxFileName(req->GetLocalFile()));
                msg << "Successfully uploaded file: " << req->GetLocalFile() << " -> " << req->GetRemoteFile();
                DoReportMessage(accountName, msg, SFTPThreadMessage::STATUS_OK);
                DoReportStatusBarMessage("");

            } else if(req->GetDirection() == SFTPThreadRequet::kDownload ||
                      req->GetDirection() == SFTPThreadRequet::kDownloadAndOpenContainingFolder ||
                      req->GetDirection() == SFTPThreadRequet::kDownloadAndOpenWithDefaultApp) {
                DoReportStatusBarMessage(wxString() << _("Downloading file: ") << req->GetRemoteFile());
                wxMemoryBuffer buffer;
                m_sftp->Read(req->GetRemoteFile(), buffer);
                wxFFile fp(req->GetLocalFile(), "w+b");
                if(fp.IsOpened()) {
                    fp.Write(buffer.GetData(), buffer.GetDataLen());
                    fp.Close();
                }

                msg << "Successfully downloaded file: " << req->GetLocalFile() << " <- " << req->GetRemoteFile();
                DoReportMessage(accountName, msg, SFTPThreadMessage::STATUS_OK);
                DoReportStatusBarMessage("");

                // We should also notify the parent window about download completed
                if(req->GetDirection() == SFTPThreadRequet::kDownload) {
                    m_plugin->CallAfter(&SFTP::FileDownloadedSuccessfully, req->GetLocalFile());

                } else if(req->GetDirection() == SFTPThreadRequet::kDownloadAndOpenContainingFolder) {
                    m_plugin->CallAfter(&SFTP::OpenContainingFolder, req->GetLocalFile());

                } else {
                    m_plugin->CallAfter(&SFTP::OpenWithDefaultApp, req->GetLocalFile());
                }
            }

        } catch(clException& e) {

            msg.Clear();
            msg << "SFTP error: " << e.What();
            DoReportMessage(accountName, msg, SFTPThreadMessage::STATUS_ERROR);
            DoReportStatusBarMessage(msg);
            m_sftp.reset(NULL);

            // Requeue our request
            if(req->GetRetryCounter() == 0) {
                msg.Clear();
                msg << "Retrying to upload file: " << req->GetRemoteFile();
                DoReportMessage(req->GetAccount().GetAccountName(), msg, SFTPThreadMessage::STATUS_NONE);

                // first time trying this request, requeue it
                SFTPThreadRequet* retryReq = static_cast<SFTPThreadRequet*>(req->Clone());
                retryReq->SetRetryCounter(1);
                Add(retryReq);
            }
        }
    }
}