Пример #1
0
void print_root()
{
	dlx_node *Node, *N;

	for (Node = Root->Right; Node != Root; Node = Node->Right) {
		cout << "printing column ";
		print_position(Node);
		cout << endl;
		for (N = Node->Down; N != Node; N = N->Down) {
			cout << "Node ";
			print_position(N);
			cout << endl;
			}
		}
}
Пример #2
0
static Node *find_node_for_position(const QuadNode * const quad_node,
                                    const Rectangle2D * const qrects,
                                    const Position2D * const position,
                                    Rectangle2D * const rect_pnt,
                                    unsigned int *part_id)
{
    unsigned int t = 4U;
    
    assert(quad_node->type == NODE_TYPE_QUAD_NODE);
    do {
        t--;
        if (position_is_in_rect(position, &qrects[t])) {
            if (rect_pnt != NULL) {
                *rect_pnt = qrects[t];
            }
            if (part_id != NULL) {
                *part_id = t;
            }
            return quad_node->nodes[t];
        }
    } while (t > 0U);
#ifdef DEBUG
    print_position(position);    
    print_quad_rects(qrects);
#endif
    assert(0);
    
    return NULL;
}
Пример #3
0
/**
 * Checks for memory leaks.
 *
 * @return  zero if no leakage is found; the number of leaks otherwise
 */
int check_leaks()
{
    int leak_cnt = 0;
    fast_mutex_autolock lock_ptr(new_ptr_lock);
    fast_mutex_autolock lock_output(new_output_lock);
    new_ptr_list_t* ptr = new_ptr_list.next;
    while (ptr != &new_ptr_list)
    {
        const char* const pointer = (char*)ptr + ALIGNED_LIST_ITEM_SIZE;
        if (ptr->magic != MAGIC)
        {
            fprintf(new_output_fp,
                    "warning: heap data corrupt near %p\n",
                    pointer);
        }
#if _DEBUG_NEW_TAILCHECK
        if (!check_tail(ptr))
        {
            fprintf(new_output_fp,
                    "warning: overwritten past end of object at %p\n",
                    pointer);
        }
#endif
        fprintf(new_output_fp,
                "Leaked object at %p (size %lu, ",
                pointer,
                (unsigned long)ptr->size);
        if (ptr->line != 0)
            print_position(ptr->file, ptr->line);
        else
            print_position(ptr->addr, ptr->line);
		if( new_verbose_flag )
		{
			fprintf(new_output_fp, "):\n");
			dump_leak(pointer, ptr);
		}
		else
		{
			fprintf(new_output_fp, ")\n");
		}
        ptr = ptr->next;
        ++leak_cnt;
    }
    if (new_verbose_flag || leak_cnt)
        fprintf(new_output_fp, "*** %d leaks found\n", leak_cnt);
    return leak_cnt;
}
Пример #4
0
/**
 * Checks for heap corruption.
 *
 * @return  zero if no problem is found; the number of found memory
 *          corruptions otherwise
 */
int check_mem_corruption()
{
    int corrupt_cnt = 0;
    fast_mutex_autolock lock_ptr(new_ptr_lock);
    fast_mutex_autolock lock_output(new_output_lock);
    fprintf(new_output_fp, "*** Checking for memory corruption: START\n");
    for (new_ptr_list_t* ptr = new_ptr_list.next;
            ptr != &new_ptr_list;
            ptr = ptr->next)
    {
        const char* const pointer = (char*)ptr + ALIGNED_LIST_ITEM_SIZE;
        if (ptr->magic == MAGIC
#if _DEBUG_NEW_TAILCHECK
                && check_tail(ptr)
#endif
                )
            continue;
#if _DEBUG_NEW_TAILCHECK
        if (ptr->magic != MAGIC)
        {
#endif
            fprintf(new_output_fp,
                    "Heap data corrupt near %p (size %lu, ",
                    pointer,
                    (unsigned long)ptr->size);
#if _DEBUG_NEW_TAILCHECK
        }
        else
        {
            fprintf(new_output_fp,
                    "Overwritten past end of object at %p (size %lu, ",
                    pointer,
                    (unsigned long)ptr->size);
        }
#endif
        if (ptr->line != 0)
            print_position(ptr->file, ptr->line);
        else
            print_position(ptr->addr, ptr->line);
        fprintf(new_output_fp, ")\n");
        ++corrupt_cnt;
    }
    fprintf(new_output_fp, "*** Checking for memory corruption: %d FOUND\n",
            corrupt_cnt);
    return corrupt_cnt;
}
Пример #5
0
/*
 * refresh window content
 */
static void refresh_text_box(WINDOW *dialog, WINDOW *box, int boxh, int boxw,
							  int cur_y, int cur_x)
{
	print_page(box, boxh, boxw);
	print_position(dialog);
	wmove(dialog, cur_y, cur_x);	/* Restore cursor position */
	wrefresh(dialog);
}
Пример #6
0
/**
 * Placement deallocation function.  For details, please check Section
 * 5.3.4 of the C++ 1998 Standard.
 *
 * @param pointer   pointer to the previously allocated memory
 * @param file      null-terminated string of the file name
 * @param line      line number
 */
void operator delete[](void* pointer, const char* file, int line) throw()
{
    if (new_verbose_flag)
    {
        fast_mutex_autolock lock(new_output_lock);
        fprintf(new_output_fp,
                "info: exception thrown on initializing objects at %p (",
                pointer);
        print_position(file, line);
        fprintf(new_output_fp, ")\n");
    }
    operator delete[](pointer);
}
Пример #7
0
void print_frame(int len) {
    int i;
    ui8_t byte;

    if (option_raw) {
        for (i = 0; i < len; i++) {
            //byte = frame[i];
            byte = xorbyte(i);
            fprintf(stdout, "%02x", byte);
        }
        fprintf(stdout, "\n");
    }
    else print_position();
}
Пример #8
0
main() {
  struct person iwao   = {"Iwao", 0, 0};
  struct person naoaki = {"Naoaki", 0, 0};
  int i;
  int rand_num;
  //srand(0);

  for (i = 0; i < 10; i++) {
    update_step(&iwao);
    update_step(&naoaki);
    if (i % 2 == 0) {
      iwao.x   += iwao.step;
      naoaki.x += naoaki.step;
    } else {
      iwao.y   += iwao.step;
      naoaki.y += naoaki.step;
    }
  }

  print_position(iwao);
  print_position(naoaki);
  return 0;
}
Пример #9
0
int main(int argc, char *argv[]) {
    int dims = 2;
    int nr_particles = 5;
    if (argc > 1)
        dims = atoi(argv[1]);
    if (argc > 2)
        nr_particles = atoi(argv[2]);
    System *system = init_system(nr_particles, dims);
    print_system(system);
    printf("total mass = %lf\n", total_mass(system));
    double cms[dims];
    center_of_mass(system, cms);
    print_position(cms, dims);
    free_system(system);
    return EXIT_SUCCESS;
}
Пример #10
0
int main(void)
{
	enum cmd_pos pos;
	char* argv[MAX_ARGV_SIZE];
	char str[MAX_CMD_SIZE] = "cat parse.c | grep argv | wc -l";
	do{
		int i;
		pos = next_command(str, argv);
		for(i = 0; argv[i] != NULL; i++)
		{
			printf("argv[%d]: %s\n", i, argv[i]);
		}
		print_position(pos);
	}while(pos != single && pos != last);
	return 0;
}
Пример #11
0
void print_frame(rs_data_t *rs_data) {
    int i;

    if (!option_raw && option_verbose) fprintf(stdout, "\n");  // fflush(stdout);

    (rs_data->rs_process)(rs_data, option_raw, option_verbose);

    if (option_raw) {
        for (i = 0; i < rs_data->pos; i++) {
            fprintf(stdout, "%02x", rs_data->frame_bytes[i]);
        }

        if (rs_data->ecc >= 0) fprintf(stdout, " [OK]"); else fprintf(stdout, " [NO]");
        if (rs_data->ecc >  0) fprintf(stdout, " (%d)", rs_data->ecc);

        fprintf(stdout, "\n");
    }
    else {
        print_position(rs_data);
    }
}
Пример #12
0
static void
track_disp_wpt_cb(const waypoint *wpt)
{
    waypoint *prev = cur_info->prev_wpt;
    time_t delta;
    double dist, depth;

    gbfprintf(fout, "Trackpoint\t");

    print_position(wpt);
    print_date_and_time(wpt->creation_time, 0);
    if IS_VALID_ALT(wpt->altitude)
        print_distance(wpt->altitude, 1, 0, 0);

    gbfprintf(fout, "\t");
    depth = WAYPT_GET(wpt, depth, unknown_alt);
    if (depth != unknown_alt)
        print_distance(depth, 1, 0, 1);

    if (prev != NULL) {
        float temp;
        gbfprintf(fout, "\t");
        delta = wpt->creation_time - prev->creation_time;
        temp = WAYPT_GET(wpt, temperature, -999);
        if (temp != -999)
            print_temperature(temp);
        gbfprintf(fout, "\t");
        dist = waypt_distance_ex(prev, wpt);
        print_distance(dist, 0, 1, 0);
        print_date_and_time(delta, 1);
        print_speed(&dist, &delta);
        print_course(prev, wpt);
    }
    gbfprintf(fout, "\r\n");

    cur_info->prev_wpt = (waypoint *)wpt;
}
Пример #13
0
void print_particle(Particle *particle) {
    print_position(particle->position, particle->dims);
    printf(": %lf\n", particle->mass);
}
Пример #14
0
#include "star_cluster.h"


star_cluster::star_cluster()
{
}

 void star_cluster::add(stars n){
    number_stars++;
    all_stars.push_back(n);
}
void star_cluster::print_position(ofsteam &output, ofstream &output2, vector<stars> vec){
    print_position(output, output2, vec, 3)
}
void star_cluster::print_position(ofsteam &output, ofstream &output2, vector<stars> vec, int n){
    if (n>3 || n<=0) n = 3;
    for (int i = 0; i<vec.size(); i++){
        stars &this = vec[i];
        std::cout << std::scientific;
        for(int j = 0; j<n; j++){
            std::cout << this.position[j] << "   ";
            output << std::scientific << this.position[j] << "   ";
            output2 << std::scientific << this.velocity[j] << "   ";
        }
        std::cout << "     ";
        output << "       ";
        output2 << "        ";
        std::cout << std::endl;
        output << endl;
        output2 << endl;
Пример #15
0
void console()
{
    char str[100];
    Move movelist[256];
    int n;
    int depth_limit = 8;
    setup_position(start_fen);
    
    printf("white or black?\n");
    while(1)
    {
        gets(str);
        if(!strcmp(str, "white") || ! strcmp(str, "black"))
        {
            break;
        }
    }
    int is_reversed;
    if(!strcmp(str, "black"))
    {
        is_reversed = 1;
        print_position(is_reversed);
        Move bestmove = search(depth_limit);
        make_move(bestmove);
    }
    else
    {
        is_reversed = 0;
    }
    
    while(1)
    {
        print_position(is_reversed);
        n = generate_moves(movelist);
        if(n == 0)
        {
            while(1);
        }
        int flag = 1;
        while(flag)
        {
            gets(str);
            Move move = str_to_move(str);
            for(int i = 0; i < n; i += 1)
            {
                Move i_move = movelist[i]; 
                if(move == i_move)
                {
                    make_move(move);
                    flag = 0;
                    break;
                }
            }
            if(flag)
            {
                printf("Incorrect\n");
            }
        }
        
        print_position(is_reversed);
        Move bestmove = search(depth_limit);
        if(bestmove == 0)
        {
            while(1);
        }
        make_move(bestmove);
    }
}
Пример #16
0
/**
 * Frees memory and adjusts pointers.
 *
 * @param pointer   pointer to the previously allocated memory
 * @param addr      pointer to the caller
 * @param is_array  flag indicating whether it is invoked by a
 *                  <code>delete[]</code> call
 */
static void free_pointer(void* pointer, void* addr, bool is_array)
{
    if (pointer == NULL)
        return;
    new_ptr_list_t* ptr =
            (new_ptr_list_t*)((char*)pointer - ALIGNED_LIST_ITEM_SIZE);
    if (ptr->magic != MAGIC)
    {
        {
            fast_mutex_autolock lock(new_output_lock);
            fprintf(new_output_fp, "delete%s: invalid pointer %p (",
                    is_array ? "[]" : "", pointer);
            print_position(addr, 0);
            fprintf(new_output_fp, ")\n");
        }
        check_mem_corruption();
        fflush(new_output_fp);
        _DEBUG_NEW_ERROR_ACTION;
    }
    if (is_array != ptr->is_array)
    {
        const char* msg;
        if (is_array)
            msg = "delete[] after new";
        else
            msg = "delete after new[]";
        fast_mutex_autolock lock(new_output_lock);
        fprintf(new_output_fp,
                "%s: pointer %p (size %lu)\n\tat ",
                msg,
                (char*)ptr + ALIGNED_LIST_ITEM_SIZE,
                (unsigned long)ptr->size);
        print_position(addr, 0);
        fprintf(new_output_fp, "\n\toriginally allocated at ");
        if (ptr->line != 0)
            print_position(ptr->file, ptr->line);
        else
            print_position(ptr->addr, ptr->line);
        fprintf(new_output_fp, "\n");
        fflush(new_output_fp);
        _DEBUG_NEW_ERROR_ACTION;
    }
#if _DEBUG_NEW_TAILCHECK
    if (!check_tail(ptr))
    {
        check_mem_corruption();
        fflush(new_output_fp);
        _DEBUG_NEW_ERROR_ACTION;
    }
#endif
    {
        fast_mutex_autolock lock(new_ptr_lock);
        total_mem_alloc -= ptr->size;
        ptr->magic = 0;
        ptr->prev->next = ptr->next;
        ptr->next->prev = ptr->prev;
    }
    if (new_verbose_flag)
    {
        fast_mutex_autolock lock(new_output_lock);
        fprintf(new_output_fp,
                "delete%s: freed %p (size %lu, %lu bytes still allocated)\n",
                is_array ? "[]" : "",
                (char*)ptr + ALIGNED_LIST_ITEM_SIZE,
                (unsigned long)ptr->size, (unsigned long)total_mem_alloc);
    }
    free(ptr);
    return;
}
Пример #17
0
/**
 * Allocates memory and initializes control data.
 *
 * @param size      size of the required memory block
 * @param file      null-terminated string of the file name
 * @param line      line number
 * @param is_array  boolean value whether this is an array operation
 * @return          pointer to the user-requested memory area; \c NULL
 *                  if memory allocation is not successful
 */
static void* alloc_mem(size_t size, const char* file, int line, bool is_array)
{
    assert(line >= 0);
#if _DEBUG_NEW_TYPE == 1
    STATIC_ASSERT(_DEBUG_NEW_ALIGNMENT >= PLATFORM_MEM_ALIGNMENT,
                  Alignment_too_small);
#endif
    STATIC_ASSERT((_DEBUG_NEW_ALIGNMENT & (_DEBUG_NEW_ALIGNMENT - 1)) == 0,
                  Alignment_must_be_power_of_two);
    STATIC_ASSERT(_DEBUG_NEW_TAILCHECK >= 0, Invalid_tail_check_length);
    size_t s = size + ALIGNED_LIST_ITEM_SIZE + _DEBUG_NEW_TAILCHECK;
    new_ptr_list_t* ptr = (new_ptr_list_t*)malloc(s);
    if (ptr == NULL)
    {
#if _DEBUG_NEW_STD_OPER_NEW
        return NULL;
#else
        fast_mutex_autolock lock(new_output_lock);
        fprintf(new_output_fp,
                "Out of memory when allocating %lu bytes\n",
                (unsigned long)size);
        fflush(new_output_fp);
        _DEBUG_NEW_ERROR_ACTION;
#endif
    }
    void* pointer = (char*)ptr + ALIGNED_LIST_ITEM_SIZE;
#if _DEBUG_NEW_FILENAME_LEN == 0
    ptr->file = file;
#else
    if (line)
        strncpy(ptr->file, file, _DEBUG_NEW_FILENAME_LEN - 1)
                [_DEBUG_NEW_FILENAME_LEN - 1] = '\0';
    else
        ptr->addr = (void*)file;
#endif
    ptr->line = line;
    ptr->is_array = is_array;
    ptr->size = size;
    ptr->magic = MAGIC;
    {
        fast_mutex_autolock lock(new_ptr_lock);
        ptr->prev = new_ptr_list.prev;
        ptr->next = &new_ptr_list;
        new_ptr_list.prev->next = ptr;
        new_ptr_list.prev = ptr;
    }
#if _DEBUG_NEW_TAILCHECK
    memset((char*)pointer + size, _DEBUG_NEW_TAILCHECK_CHAR,
                                  _DEBUG_NEW_TAILCHECK);
#endif
    if (new_verbose_flag)
    {
        fast_mutex_autolock lock(new_output_lock);
        fprintf(new_output_fp,
                "new%s: allocated %p (size %lu, ",
                is_array ? "[]" : "",
                pointer, (unsigned long)size);
        if (line != 0)
            print_position(ptr->file, ptr->line);
        else
            print_position(ptr->addr, ptr->line);
        fprintf(new_output_fp, ")\n");
    }
    total_mem_alloc += size;
    return pointer;
}
Пример #18
0
/*
 * Display text from a file in a dialog box.
 */
int
dialog_textbox (const char *title, const char *file, int height, int width)
{
    int i, x, y, cur_x, cur_y, fpos, key = 0, dir, temp, temp1;
#ifdef HAVE_LIBNCURSES
    int passed_end;
#endif
    char search_term[MAX_LEN + 1], *tempptr, *found;
    WINDOW *dialog, *text;

    search_term[0] = '\0';	/* no search term entered yet */

    /* Open input file for reading */
    if ((fd = open (file, O_RDONLY)) == -1) {
	endwin ();
	fprintf (stderr,
		 "\nCan't open input file in dialog_textbox().\n");
	exit (-1);
    }
    /* Get file size. Actually, 'file_size' is the real file size - 1,
       since it's only the last byte offset from the beginning */
    if ((file_size = lseek (fd, 0, SEEK_END)) == -1) {
	endwin ();
	fprintf (stderr, "\nError getting file size in dialog_textbox().\n");
	exit (-1);
    }
    /* Restore file pointer to beginning of file after getting file size */
    if (lseek (fd, 0, SEEK_SET) == -1) {
	endwin ();
	fprintf (stderr, "\nError moving file pointer in dialog_textbox().\n");
	exit (-1);
    }
    /* Allocate space for read buffer */
    if ((buf = malloc (BUF_SIZE + 1)) == NULL) {
	endwin ();
	fprintf (stderr, "\nCan't allocate memory in dialog_textbox().\n");
	exit (-1);
    }
    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
	endwin ();
	fprintf (stderr, "\nError reading file in dialog_textbox().\n");
	exit (-1);
    }
    buf[bytes_read] = '\0';	/* mark end of valid data */
    page = buf;			/* page is pointer to start of page to be displayed */

    /* center dialog box on screen */
    x = (COLS - width) / 2;
    y = (LINES - height) / 2;

#ifdef HAVE_LIBNCURSES
    if (use_shadow)
	draw_shadow (stdscr, y, x, height, width);
#endif
    dialog = newwin (height, width, y, x);
    mouse_setbase (x, y);
    keypad (dialog, TRUE);

    /* Create window for text region, used for scrolling text */
    text = subwin (dialog, height - 4, width - 2, y + 1, x + 1);

    keypad (text, TRUE);

    /* register the new window, along with its borders */
    mouse_mkbigregion (0, 0, height - 2, width, 1, 0, 2 /* not normal */ );
    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);

    wattrset (dialog, border_attr);
    wmove (dialog, height - 3, 0);
    waddch (dialog, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
	waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    waddch (dialog, ACS_RTEE);
    wmove (dialog, height - 2, 1);
    for (i = 0; i < width - 2; i++)
	waddch (dialog, ' ');

    if (title != NULL) {
	wattrset (dialog, title_attr);
	wmove (dialog, 0, (width - strlen (title)) / 2 - 1);
	waddch (dialog, ' ');
	waddstr (dialog, title);
	waddch (dialog, ' ');
    }
    print_button (dialog, " EXIT ", height - 2, width / 2 - 4, TRUE);
    wnoutrefresh (dialog);
    getyx (dialog, cur_y, cur_x);	/* Save cursor position */

    /* Print first page of text */
    attr_clear (text, height - 4, width - 2, dialog_attr);
    print_page (text, height - 4, width - 2);
    print_position (dialog, height, width);
    wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
    wrefresh (dialog);

    while ((key != ESC) && (key != '\n')) {
	key = mouse_wgetch (dialog);
	switch (key) {
	case M_EVENT + 'E':
	case 'E':		/* Exit */
	case 'e':
	    delwin (dialog);
	    free (buf);
	    close (fd);
	    return 0;
	case 'g':		/* First page */
	case KEY_HOME:
	    if (!begin_reached) {
		begin_reached = 1;
		/* First page not in buffer? */
		if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1) {
		    endwin ();
		    fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		    exit (-1);
		}
		if (fpos > bytes_read) {	/* Yes, we have to read it in */
		    if (lseek (fd, 0, SEEK_SET) == -1) {
			endwin ();
			fprintf (stderr, "\nError moving file pointer in "
				 "dialog_textbox().\n");
			exit (-1);
		    }
		    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
			endwin ();
			fprintf (stderr,
			     "\nError reading file in dialog_textbox().\n");
			exit (-1);
		    }
		    buf[bytes_read] = '\0';
		}
		page = buf;
		print_page (text, height - 4, width - 2);
		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case 'G':		/* Last page */
#ifdef HAVE_LIBNCURSES
	case KEY_END:
#endif
	    end_reached = 1;
	    /* Last page not in buffer? */
	    if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1) {
		endwin ();
		fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		exit (-1);
	    }
	    if (fpos < file_size) {	/* Yes, we have to read it in */
		if (lseek (fd, -BUF_SIZE, SEEK_END) == -1) {
		    endwin ();
		    fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		    exit (-1);
		}
		if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
		    endwin ();
		    fprintf (stderr,
			     "\nError reading file in dialog_textbox().\n");
		    exit (-1);
		}
		buf[bytes_read] = '\0';
	    }
	    page = buf + bytes_read;
	    back_lines (height - 4);
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
	    wrefresh (dialog);
	    break;
	case 'K':		/* Previous line */
	case 'k':
	case KEY_UP:
	    if (!begin_reached) {
		back_lines (page_length + 1);
#ifdef HAVE_LIBNCURSES
		/* We don't call print_page() here but use scrolling to ensure
		   faster screen update. However, 'end_reached' and
		   'page_length' should still be updated, and 'page' should
		   point to start of next page. This is done by calling
		   get_line() in the following 'for' loop. */
		scrollok (text, TRUE);
		wscrl (text, -1);	/* Scroll text region down one line */
		scrollok (text, FALSE);
		page_length = 0;
		passed_end = 0;
		for (i = 0; i < height - 4; i++) {
		    if (!i) {
			/* print first line of page */
			print_line (text, 0, width - 2);
			wnoutrefresh (text);
		    } else
			/* Called to update 'end_reached' and 'page' */
			get_line ();
		    if (!passed_end)
			page_length++;
		    if (end_reached && !passed_end)
			passed_end = 1;
		}
#else
		print_page (text, height - 4, width - 2);
#endif
		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case 'B':		/* Previous page */
	case 'b':
	case KEY_PPAGE:
	    if (begin_reached)
		break;
	    back_lines (page_length + height - 4);
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case 'J':		/* Next line */
	case 'j':
	case KEY_DOWN:
	    if (!end_reached) {
		begin_reached = 0;
		scrollok (text, TRUE);
		scroll (text);	/* Scroll text region up one line */
		scrollok (text, FALSE);
		print_line (text, height - 5, width - 2);
#ifndef HAVE_LIBNCURSES
		wmove (text, height - 5, 0);
		waddch (text, ' ');
		wmove (text, height - 5, width - 3);
		waddch (text, ' ');
#endif
		wnoutrefresh (text);
		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case ' ':		/* Next page */
	case KEY_NPAGE:
	    if (end_reached)
		break;

	    begin_reached = 0;
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case '0':		/* Beginning of line */
	case 'H':		/* Scroll left */
	case 'h':
	case KEY_LEFT:
	    if (hscroll <= 0)
		break;

	    if (key == '0')
		hscroll = 0;
	    else
		hscroll--;
	    /* Reprint current page to scroll horizontally */
	    back_lines (page_length);
	    print_page (text, height - 4, width - 2);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case 'L':		/* Scroll right */
	case 'l':
	case KEY_RIGHT:
	    if (hscroll >= MAX_LEN)
		break;
	    hscroll++;
	    /* Reprint current page to scroll horizontally */
	    back_lines (page_length);
	    print_page (text, height - 4, width - 2);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case '/':		/* Forward search */
	case 'n':		/* Repeat forward search */
	case '?':		/* Backward search */
	case 'N':		/* Repeat backward search */
	    /* set search direction */
	    dir = (key == '/' || key == 'n') ? 1 : 0;
	    if (dir ? !end_reached : !begin_reached) {
		if (key == 'n' || key == 'N') {
		    if (search_term[0] == '\0') {	/* No search term yet */
			fprintf (stderr, "\a");		/* beep */
			break;
		    }
		} else
		    /* Get search term from user */
		    if (get_search_term (text, search_term, height - 4,
					 width - 2) == -1) {
		    /* ESC pressed in get_search_term().
		       Reprint page to clear box */
		    wattrset (text, dialog_attr);
		    back_lines (page_length);
		    print_page (text, height - 4, width - 2);
		    wmove (dialog, cur_y, cur_x);
		    wrefresh (dialog);
		    break;
		}
		/* Save variables for restoring in case search term
		   can't be found */
		tempptr = page;
		temp = begin_reached;
		temp1 = end_reached;
		if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1) {
		    endwin ();
		    fprintf (stderr, "\nError moving file pointer in "
			     "dialog_textbox().\n");
		    exit (-1);
		}
		fpos -= bytes_read;
		/* update 'page' to point to next (previous) line before
		   forward (backward) searching */
		back_lines (dir ? page_length - 1 : page_length + 1);
		found = NULL;
		if (dir)	/* Forward search */
		    while ((found = strstr (get_line (), search_term))
			   == NULL) {
			if (end_reached)
			    break;
		} else		/* Backward search */
		    while ((found = strstr (get_line (), search_term))
			   == NULL) {
			if (begin_reached)
			    break;
			back_lines (2);
		    }
		if (found == NULL) {	/* not found */
		    fprintf (stderr, "\a");	/* beep */
		    /* Restore program state to that before searching */
		    if (lseek (fd, fpos, SEEK_SET) == -1) {
			endwin ();
			fprintf (stderr, "\nError moving file pointer in "
				 "dialog_textbox().\n");
			exit (-1);
		    }
		    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
			endwin ();
			fprintf (stderr, "\nError reading file in "
				 "dialog_textbox().\n");
			exit (-1);
		    }
		    buf[bytes_read] = '\0';
		    page = tempptr;
		    begin_reached = temp;
		    end_reached = temp1;
		    /* move 'page' to point to start of current page in order to
		       re-print current page. Note that 'page' always points to
		       start of next page, so this is necessary */
		    back_lines (page_length);
		} else		/* Search term found */
		    back_lines (1);
		/* Reprint page */
		wattrset (text, dialog_attr);
		print_page (text, height - 4, width - 2);
		if (found != NULL)
		    print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    } else		/* no need to find */
		fprintf (stderr, "\a");		/* beep */
	    break;
	case ESC:
	    break;
	}
    }

    delwin (dialog);
    free (buf);
    close (fd);
    return -1;			/* ESC pressed */
}
Пример #19
0
void CreateMatrix(INT *Data, INT nb_rows, INT nb_cols, INT verbose_level)
{
	INT f_v = (verbose_level >= 1);
	INT a, b, i, j;

	nRow = nb_rows;
	nCol = nb_cols;
	dlx_nb_sol = 0;

	if (f_v) {
		cout << "dlx.C: CreateMatrix" << endl;
		cout << "The " << nb_rows << " x " << nb_cols << " matrix is:" << endl;
		for (i = 0; i < nb_rows; i++) {
			for (j = 0; j < nb_cols; j++) {
				cout << Data[i * nb_cols + j];
				}
			cout << endl;
			}
		//INT_matrix_print(Data, nb_rows, nb_cols);
		cout << endl;
		}

	Matrix = new dlx_node[nRow * nCol];
	Root = new dlx_node;
	//RowHeader = new pdlx_node[nRow];

	
	Result = NEW_INT(nRow);
	Nb_choices = NEW_INT(nRow);
	Cur_choice = NEW_INT(nRow);
	Nb_col_nodes = NEW_INT(nCol);

	for (j = 0; j < nCol; j++) {
		Nb_col_nodes[j] = 0;
		}

	
	// Build toroidal linklist matrix according to data bitmap
	for (a = 0; a < nRow; a++) {
		for (b = 0; b < nCol; b++) {
			Matrix[a * nCol + b].row = a;
			Matrix[a * nCol + b].col = b;
			}
		}
	
	// Connect the coefficients which are nonzero to their up and down and left and right neighbors:

	for (a = 0; a < nRow; a++) {
		for (b = 0; b < nCol; b++) {
			if (Data[a * nCol + b] != 0) {
				// Left pointer
				i = a; j = b; do { j = dataLeft(j); } while (Data[i * nCol + j] == 0);
				Matrix[a * nCol + b].Left = &Matrix[i * nCol + j]; 
				// Right pointer
				i = a; j = b; do { j = dataRight(j); } while (Data[i * nCol + j] == 0);
				Matrix[a * nCol + b].Right = &Matrix[i * nCol + j];
				// Up pointer
				i = a; j = b; do { i = dataUp(i); } while (Data[i * nCol + j] == 0);
				Matrix[a * nCol + b].Up = &Matrix[i * nCol + j];
				// Down pointer
				i = a; j = b; do { i = dataDown(i); } while (Data[i * nCol + j] == 0);
				Matrix[a * nCol + b].Down = &Matrix[i * nCol + j]; 

#if 0
				cout << "at " << a << "/" << b << ":";
				cout << " Left="; print_position(Matrix[a * nCol + b].Left);
				cout << " Right="; print_position(Matrix[a * nCol + b].Right);
				cout << " Up="; print_position(Matrix[a * nCol + b].Up);
				cout << " Down="; print_position(Matrix[a * nCol + b].Down);
				cout << endl;
#endif
				// Header pointer at the very bottom:
				Matrix[a * nCol + b].Header = &Matrix[(nRow - 1) * nCol + b];
				//Row Header
				//RowHeader[a] = &Matrix[a * nCol + b];
				}
			}
		}

	// Count the number of nodes in each column (i.e. the number of ones in the column of the matrix)
	for (j = 0; j < nCol; j++) {
		Nb_col_nodes[j] = 0;

		dlx_node *ColNode, *RowNode;

		// this is the RHS
		ColNode = &Matrix[(nRow - 1) * nCol + j];
		
		for (RowNode = ColNode->Down; RowNode != ColNode; RowNode = RowNode->Down) {
			Nb_col_nodes[j]++;
			}
		}
	
#if 0
	for (a = 0; a < nCol; a++) {
		Matrix[(nRow - 1) * nCol + a].row = nRow - 1;
		Matrix[(nRow - 1) * nCol + a].col = a;
		}
#endif
	//Insert root at the end of all RHS nodes:
	Root->Left = &Matrix[(nRow - 1) * nCol + (nCol - 1)];
	Root->Right = &Matrix[(nRow - 1) * nCol + 0];
	Matrix[(nRow - 1) * nCol + nCol - 1].Right = Root;
	Matrix[(nRow - 1) * nCol + 0].Left = Root;
	Root->row = -1;
	Root->col = -1;
}
Пример #20
0
/*
 * Display text from a file in a dialog box.
 */
int dialog_textbox(const char *title, const char *tbuf,
		   int initial_height, int initial_width)
{
	int i, x, y, cur_x, cur_y, key = 0;
	int height, width, boxh, boxw;
	int passed_end;
	WINDOW *dialog, *box;

	begin_reached = 1;
	end_reached = 0;
	page_length = 0;
	hscroll = 0;
	buf = tbuf;
	page = buf;	/* page is pointer to start of page to be displayed */

do_resize:
	getmaxyx(stdscr, height, width);
	if (height < 8 || width < 8)
		return -ERRDISPLAYTOOSMALL;
	if (initial_height != 0)
		height = initial_height;
	else
		if (height > 4)
			height -= 4;
		else
			height = 0;
	if (initial_width != 0)
		width = initial_width;
	else
		if (width > 5)
			width -= 5;
		else
			width = 0;

	/* center dialog box on screen */
	x = (COLS - width) / 2;
	y = (LINES - height) / 2;

	draw_shadow(stdscr, y, x, height, width);

	dialog = newwin(height, width, y, x);
	keypad(dialog, TRUE);

	/* Create window for box region, used for scrolling text */
	boxh = height - 4;
	boxw = width - 2;
	box = subwin(dialog, boxh, boxw, y + 1, x + 1);
	wattrset(box, dlg.dialog.atr);
	wbkgdset(box, dlg.dialog.atr & A_COLOR);

	keypad(box, TRUE);

	/* register the new window, along with its borders */
	draw_box(dialog, 0, 0, height, width,
		 dlg.dialog.atr, dlg.border.atr);

	wattrset(dialog, dlg.border.atr);
	mvwaddch(dialog, height - 3, 0, ACS_LTEE);
	for (i = 0; i < width - 2; i++)
		waddch(dialog, ACS_HLINE);
	wattrset(dialog, dlg.dialog.atr);
	wbkgdset(dialog, dlg.dialog.atr & A_COLOR);
	waddch(dialog, ACS_RTEE);

	print_title(dialog, title, width);

	print_button(dialog, gettext(" Exit "), height - 2, width / 2 - 4, TRUE);
	wnoutrefresh(dialog);
	getyx(dialog, cur_y, cur_x);	/* Save cursor position */

	/* Print first page of text */
	attr_clear(box, boxh, boxw, dlg.dialog.atr);
	refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x);

	while ((key != KEY_ESC) && (key != '\n')) {
		key = wgetch(dialog);
		switch (key) {
		case 'E':	/* Exit */
		case 'e':
		case 'X':
		case 'x':
		case 'q':
			delwin(box);
			delwin(dialog);
			return 0;
		case 'g':	/* First page */
		case KEY_HOME:
			if (!begin_reached) {
				begin_reached = 1;
				page = buf;
				refresh_text_box(dialog, box, boxh, boxw,
						 cur_y, cur_x);
			}
			break;
		case 'G':	/* Last page */
		case KEY_END:

			end_reached = 1;
			/* point to last char in buf */
			page = buf + strlen(buf);
			back_lines(boxh);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'K':	/* Previous line */
		case 'k':
		case KEY_UP:
			if (!begin_reached) {
				back_lines(page_length + 1);

				/* We don't call print_page() here but use
				 * scrolling to ensure faster screen update.
				 * However, 'end_reached' and 'page_length'
				 * should still be updated, and 'page' should
				 * point to start of next page. This is done
				 * by calling get_line() in the following
				 * 'for' loop. */
				scrollok(box, TRUE);
				wscrl(box, -1);	/* Scroll box region down one line */
				scrollok(box, FALSE);
				page_length = 0;
				passed_end = 0;
				for (i = 0; i < boxh; i++) {
					if (!i) {
						/* print first line of page */
						print_line(box, 0, boxw);
						wnoutrefresh(box);
					} else
						/* Called to update 'end_reached' and 'page' */
						get_line();
					if (!passed_end)
						page_length++;
					if (end_reached && !passed_end)
						passed_end = 1;
				}

				print_position(dialog);
				wmove(dialog, cur_y, cur_x);	/* Restore cursor position */
				wrefresh(dialog);
			}
			break;
		case 'B':	/* Previous page */
		case 'b':
		case 'u':
		case KEY_PPAGE:
			if (begin_reached)
				break;
			back_lines(page_length + boxh);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'J':	/* Next line */
		case 'j':
		case KEY_DOWN:
			if (!end_reached) {
				begin_reached = 0;
				scrollok(box, TRUE);
				scroll(box);	/* Scroll box region up one line */
				scrollok(box, FALSE);
				print_line(box, boxh - 1, boxw);
				wnoutrefresh(box);
				print_position(dialog);
				wmove(dialog, cur_y, cur_x);	/* Restore cursor position */
				wrefresh(dialog);
			}
			break;
		case KEY_NPAGE:	/* Next page */
		case ' ':
		case 'd':
			if (end_reached)
				break;

			begin_reached = 0;
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case '0':	/* Beginning of line */
		case 'H':	/* Scroll left */
		case 'h':
		case KEY_LEFT:
			if (hscroll <= 0)
				break;

			if (key == '0')
				hscroll = 0;
			else
				hscroll--;
			/* Reprint current page to scroll horizontally */
			back_lines(page_length);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'L':	/* Scroll right */
		case 'l':
		case KEY_RIGHT:
			if (hscroll >= MAX_LEN)
				break;
			hscroll++;
			/* Reprint current page to scroll horizontally */
			back_lines(page_length);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case KEY_ESC:
			key = on_key_esc(dialog);
			break;
		case KEY_RESIZE:
			back_lines(height);
			delwin(box);
			delwin(dialog);
			on_key_resize();
			goto do_resize;
		}
	}
	delwin(box);
	delwin(dialog);
	return key;		/* ESC pressed */
}
Пример #21
0
static void
write_waypt(const waypoint *wpt)
{
    unsigned char wpt_class;
    garmin_fs_p gmsd;
    char *wpt_type;
    char *dspl_mode;
    const char *country;
    double x;
    int i, icon, dynamic;
    char *icon_descr;

    gmsd = GMSD_FIND(wpt);

    i = GMSD_GET(display, 0);
    if (i > GT_DISPLAY_MODE_MAX) i = 0;
    dspl_mode = gt_display_mode_names[i];

    wpt_class = GMSD_GET(wpt_class, 0);
    if (wpt_class <= gt_waypt_class_map_line)
        wpt_type = gt_waypt_class_names[wpt_class];
    else
        wpt_type = gt_waypt_class_names[0];

    gbfprintf(fout, "Waypoint\t%s\t", (wpt->shortname) ? wpt->shortname : "");
    if (wpt_class <= gt_waypt_class_airport_ndb) {
        char *temp = wpt->notes;
        if (temp == NULL) {
            if (wpt->description && (strcmp(wpt->description, wpt->shortname) != 0))
                temp = wpt->description;
            else
                temp = "";
        }
        print_string("%s\t", temp);
    }
    else
        gbfprintf(fout, "\t");
    gbfprintf(fout, "%s\t", wpt_type);

    print_position(wpt);

    if IS_VALID_ALT(wpt->altitude)
        print_distance(wpt->altitude, 1, 0, 0);
    gbfprintf(fout, "\t");

    x = WAYPT_GET(wpt, depth, unknown_alt);
    if (x != unknown_alt)
        print_distance(x, 1, 0, 1);
    gbfprintf(fout, "\t");

    x = WAYPT_GET(wpt, proximity, unknown_alt);
    if (x != unknown_alt)
        print_distance(x, 0, 0, 0);
    gbfprintf(fout, "\t");

    x = WAYPT_GET(wpt, temperature, -999);
    if (x != -999)
        print_temperature(x);
    gbfprintf(fout, "\t%s\t", dspl_mode);

    gbfprintf(fout, "Unknown\t"); 				/* Color is fixed: Unknown */

    icon = GMSD_GET(icon, -1);
    if (icon == -1) {
        icon = gt_find_icon_number_from_desc(wpt->icon_descr, GDB);
    }
    icon_descr = gt_find_desc_from_icon_number(icon, GDB, &dynamic);
    print_string("%s\t", icon_descr);
    if (dynamic) xfree(icon_descr);

    print_string("%s\t", GMSD_GET(facility, ""));
    print_string("%s\t", GMSD_GET(city, ""));
    print_string("%s\t", GMSD_GET(state, ""));
    country = gt_get_icao_country(GMSD_GET(cc, ""));
    print_string("%s\t", (country != NULL) ? country : "");
    print_date_and_time(wpt->creation_time, 0);
    print_string("%s\t", wpt->url ? wpt->url : "");
    print_categories(GMSD_GET(category, 0));

    gbfprintf(fout, "\r\n");
}
Пример #22
0
void input_flight_info_from_file(int id, char file_name[], char server_host[], int server_port) {
   //int year, month, day, hour, minute, second;
   //double millisecond;
   double latitude, longitude, altitude;
   double roll = 0.0 , pitch= 0.0, yaw = 0.0;
   
   char buffer[BUFSIZE*sizeof(char)];
   
   FILE *fp = open_file(file_name, "r");
   
   int valid_buffer_start = 0;
   int valid_buffer_end = fread(buffer, sizeof(char), BUFSIZE, fp);
   
   while(valid_buffer_start < valid_buffer_end){
      bool has_line = false;
      int line_size = 0;
      
      while(!has_line){
	 if(valid_buffer_start == valid_buffer_end){
	    int count = fread(buffer + line_size, sizeof(char), BUFSIZE - line_size, fp);
	    
	    if(count > 0){
	       valid_buffer_start = line_size;
	       valid_buffer_end = line_size + count;
	    }else{
	       buffer[valid_buffer_start] = '\n';
	    }
	 }
	 if(line_size + 2 < BUFSIZE){
	    buffer[line_size] = buffer[valid_buffer_start++];
	    if (buffer[line_size] == '#'){
	       buffer[line_size] = '\0';
	    }else if (buffer[line_size] == '\n' || buffer[line_size] == '\r'){
	       buffer[line_size] = '\0';
	       has_line = true;
	    }
	 }else{
	    fprintf(stderr, "error: line overflow.\n");
	    exit(EXIT_FAILURE);
	 }
	 line_size++;
      }
      //while(count)
      int count = sscanf(buffer, "%lf,%lf,%lf ", &latitude, &longitude, &altitude);
      //if </coordinates>
      if (count == 3){
	 Time_stamp time_stamp = new_time_stamp(2008, 01, 01, 00, 01, 00, 00.0);
	 //Time_stamp time_stamp = new_time_stamp(year, month, day, hour, minute, second, millisecond);
	 Position position = new_position(longitude, latitude, feet_to_metres(altitude));
	 print_position(position);
	 Orientation orientation = new_orientation(roll, pitch, yaw);
	 
	 id = 1;
	 Flight_info flight_info = new_flight_info(id, time_stamp, position, orientation);
	 
	 if (!give_flight_info_to_server(flight_info, server_host, server_port)){
	    fprintf(stderr, "Give flight info to server failed\n");
	 }
	 
      }else if (count > 0){
	 fprintf(stderr, "Found a sad line in input, parsed %d elements\n", count);
      }
   }
}
Пример #23
0
/**
 * @brief	function designed to be the main of a thread
 *			Sends movement commands to the drone in order to follow the beacon
 */
void * track_position(void * arg){

	// check time interval
    struct timeval old_tv = {0};
    struct timeval tv = {0};
    long unsigned int elapsed_time = 0; // in microsecondss
    
    // moves
    char message [512];
	int tps = 1;
	int wait =1;

	//handle the ctrl -c to make the drone land
	struct sigaction act;
	memset(&act,0,sizeof(act));
	act.sa_handler = intHandlerThread3;
	sigaction(SIGINT, &act, NULL);

    gettimeofday(&old_tv, NULL); 

	if (init_socket() != 0)
    {
        printf("[FAILED] Socket initialization failed\n");
    }
    else
    {

    	//////////////////////////////////////////////////////////
    	//	TAKING OFF 
    	//////////////////////////////////////////////////////////
		sleep(1);
        printf("Drone starts flying...\n");
		set_trim(message, wait);
		
		printf("Taking off...\n");
		while(tps < 167)
		{
			take_off(message, wait);
			tps++;
		}
		
		//stop waiting 40 us after a command send
		wait = 0;

		// Go up to be at shoulder level
		printf("Going up...\n");
		gettimeofday(&old_tv, NULL);
		elapsed_time = 0;

		while(elapsed_time < 2)
		{
			set_simple_move(message, UP, 1, wait);
			gettimeofday(&tv, NULL);
			elapsed_time = (tv.tv_sec-old_tv.tv_sec);
		}

		set_simple_move(message, UP, 0.0, wait);
		elapsed_time = 35000;

		while(keepRunning){
		    while (elapsed_time < 35000)
			{
				gettimeofday(&tv, NULL);
				elapsed_time = (tv.tv_sec-old_tv.tv_sec)*1000000 + (tv.tv_usec-old_tv.tv_usec);
			}

			pthread_mutex_lock(&track_pos_mux);

			print_position();
			
			///////////////////////////////////////////////////////////////////////
			// MOVES TO HAVE THE RIGHT ANGLE AND RIGHT DISTANCE FROM THE EMIITER
			///////////////////////////////////////////////////////////////////////
			reset_com(message, wait);

			//If no signal has been detected
			if(!pos.signalDetected)
			{
				// stop moving
				set_simple_move(message, FRONT, 0, wait);
			}
			// If a signal has been detected, move !
			else
			{

				if(pos.angle >= -ANGLE_PRECISION/2 && pos.angle <= ANGLE_PRECISION/2)
				{
					// For now, always move forward when the source in front of the drone
					set_simple_move(message, FRONT, 0.05, wait);

					// And now manage distance
					// if(pos.distance > 200) // in cm
					// 	set_simple_move(message, FRONT, 0.05, wait);
					// else if(pos.distance < 180) // in cm
					// 	set_simple_move(message, BACK, 0.05, wait);
					// else
					// 	set_simple_move(message, FRONT, 0, wait);	
				}				
	      	 	else if (pos.angle > ANGLE_PRECISION/2)
					set_simple_move(message, CLKWISE, 0.5, wait);
				else
					set_simple_move(message, ANTI_CLKWISE, 0.5,wait);
				
			}
			pthread_mutex_unlock(&compute_pos_mux);

			gettimeofday(&old_tv, NULL);
			elapsed_time=0;
		}

		///////////////////////////////////////////
		// LANDING
		///////////////////////////////////////////
		landing(message, wait);
		sleep(1);

	}
	pthread_exit(NULL);
}
Пример #24
0
int
dialog_textyesno (const char *title, const char *file, int height, int width)
{
    int i, x, y, cur_x, cur_y, fpos, key = 0, button = 0;
    int passed_end;
    char search_term[MAX_LEN + 1];
    WINDOW *dialog, *text;

    search_term[0] = '\0';	/* no search term entered yet */

    /* Open input file for reading */
    if ((fd = open (file, O_RDONLY)) == -1) {
	endwin ();
	fprintf (stderr,
		 "\nCan't open input file in dialog_textbox().\n");
	exit (-1);
    }
    /* Get file size. Actually, 'file_size' is the real file size - 1,
       since it's only the last byte offset from the beginning */
    if ((file_size = lseek (fd, 0, SEEK_END)) == -1) {
	endwin ();
	fprintf (stderr, "\nError getting file size in dialog_textbox().\n");
	exit (-1);
    }
    /* Restore file pointer to beginning of file after getting file size */
    if (lseek (fd, 0, SEEK_SET) == -1) {
	endwin ();
	fprintf (stderr, "\nError moving file pointer in dialog_textbox().\n");
	exit (-1);
    }
    /* Allocate space for read buffer */
    if ((buf = malloc (BUF_SIZE + 1)) == NULL) {
	endwin ();
	fprintf (stderr, "\nCan't allocate memory in dialog_textbox().\n");
	exit (-1);
    }
    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
	endwin ();
	fprintf (stderr, "\nError reading file in dialog_textbox().\n");
	exit (-1);
    }
    buf[bytes_read] = '\0';	/* mark end of valid data */
    page = buf;			/* page is pointer to start of page to be displayed */

    /* center dialog box on screen */
    x = (COLS - width) / 2;
    y = (LINES - height) / 2;


    draw_shadow (stdscr, y, x, height, width);

    dialog = newwin (height, width, y, x);
    keypad (dialog, TRUE);

    /* Create window for text region, used for scrolling text */
    text = subwin (dialog, height - 4, width - 2, y + 1, x + 1);
    wattrset (text, dialog_attr);
    wbkgdset (text, dialog_attr & A_COLOR);

    keypad (text, TRUE);

    /* register the new window, along with its borders */
    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);

    wattrset (dialog, border_attr);
    mvwaddch (dialog, height-3, 0, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
	waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    wbkgdset (dialog, dialog_attr & A_COLOR);
    waddch (dialog, ACS_RTEE);

    if (title != NULL && strlen(title) >= width-2 ) {
	/* truncate long title -- mec */
	char * title2 = malloc(width-2+1);
	memcpy( title2, title, width-2 );
	title2[width-2] = '\0';
	title = title2;
    }

    if (title != NULL) {
	wattrset (dialog, title_attr);
	mvwaddch (dialog, 0, (width - strlen(title))/2 - 1, ' ');
	waddstr (dialog, (char *)title);
	waddch (dialog, ' ');
    }

    //Nenad instered this
    print_buttons(dialog, height, width, 0);
    wnoutrefresh (dialog);
    getyx (dialog, cur_y, cur_x);	/* Save cursor position */

    /* Print first page of text */
    attr_clear (text, height - 4, width - 2, dialog_attr);
    print_page (text, height - 4, width - 2);
    print_position (dialog, height, width);
    wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
    wrefresh (dialog);

    while ((key != ESC) && (key != '\n')) {
	key = wgetch (dialog);
	switch (key) {
	case 'Y':		/* Exit */
	case 'y':
	    delwin (dialog);
	    free (buf);
	    close (fd);
	    return 0;
	case 'N':
	case 'n':
	    delwin (dialog);
	    free (buf);
	    close (fd);
	    return 1;
	case 'g':		/* First page */
	case KEY_HOME:
	    if (!begin_reached) {
		begin_reached = 1;
		/* First page not in buffer? */
		if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1) {
		    endwin ();
		    fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		    exit (-1);
		}
		if (fpos > bytes_read) {	/* Yes, we have to read it in */
		    if (lseek (fd, 0, SEEK_SET) == -1) {
			endwin ();
			fprintf (stderr, "\nError moving file pointer in "
				 "dialog_textbox().\n");
			exit (-1);
		    }
		    if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
			endwin ();
			fprintf (stderr,
			     "\nError reading file in dialog_textbox().\n");
			exit (-1);
		    }
		    buf[bytes_read] = '\0';
		}
		page = buf;
		print_page (text, height - 4, width - 2);
		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case 'G':		/* Last page */
	case KEY_END:

	    end_reached = 1;
	    /* Last page not in buffer? */
	    if ((fpos = lseek (fd, 0, SEEK_CUR)) == -1) {
		endwin ();
		fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		exit (-1);
	    }
	    if (fpos < file_size) {	/* Yes, we have to read it in */
		if (lseek (fd, -BUF_SIZE, SEEK_END) == -1) {
		    endwin ();
		    fprintf (stderr,
		      "\nError moving file pointer in dialog_textbox().\n");
		    exit (-1);
		}
		if ((bytes_read = read (fd, buf, BUF_SIZE)) == -1) {
		    endwin ();
		    fprintf (stderr,
			     "\nError reading file in dialog_textbox().\n");
		    exit (-1);
		}
		buf[bytes_read] = '\0';
	    }
	    page = buf + bytes_read;
	    back_lines (height - 4);
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
	    wrefresh (dialog);
	    break;
	case 'K':		/* Previous line */
	case 'k':
	case KEY_UP:
	    if (!begin_reached) {
		back_lines (page_length + 1);

		/* We don't call print_page() here but use scrolling to ensure
		   faster screen update. However, 'end_reached' and
		   'page_length' should still be updated, and 'page' should
		   point to start of next page. This is done by calling
		   get_line() in the following 'for' loop. */
		scrollok (text, TRUE);
		wscrl (text, -1);	/* Scroll text region down one line */
		scrollok (text, FALSE);
		page_length = 0;
		passed_end = 0;
		for (i = 0; i < height - 4; i++) {
		    if (!i) {
			/* print first line of page */
			print_line (text, 0, width - 2);
			wnoutrefresh (text);
		    } else
			/* Called to update 'end_reached' and 'page' */
			get_line ();
		    if (!passed_end)
			page_length++;
		    if (end_reached && !passed_end)
			passed_end = 1;
		}

		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case 'B':		/* Previous page */
	case 'b':
	case KEY_PPAGE:
	    if (begin_reached)
		break;
	    back_lines (page_length + height - 4);
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case 'J':		/* Next line */
	case 'j':
	case KEY_DOWN:
	    if (!end_reached) {
		begin_reached = 0;
		scrollok (text, TRUE);
		scroll (text);	/* Scroll text region up one line */
		scrollok (text, FALSE);
		print_line (text, height - 5, width - 2);
		wnoutrefresh (text);
		print_position (dialog, height, width);
		wmove (dialog, cur_y, cur_x);	/* Restore cursor position */
		wrefresh (dialog);
	    }
	    break;
	case KEY_NPAGE:		/* Next page */
	    if (end_reached)
		break;

	    begin_reached = 0;
	    print_page (text, height - 4, width - 2);
	    print_position (dialog, height, width);
	    wmove (dialog, cur_y, cur_x);
	    wrefresh (dialog);
	    break;
	case TAB:
	case KEY_LEFT:
	case KEY_RIGHT:
	    button = ((key == KEY_LEFT ? --button : ++button) < 0)
			? 1 : (button > 1 ? 0 : button);

	    print_buttons(dialog, height, width, button);
	    wrefresh (dialog);
	    break;
        case ' ':
	case '\n':
	    delwin (dialog);
	    free (buf);
	    close (fd);
	    return button;
	case ESC:
	    break;
	}
    }

    delwin (dialog);
    free (buf);
    close (fd);
    return -1;			/* ESC pressed */
}
Пример #25
0
/*
 * Display text from a file in a dialog box.
 */
int
dialog_textbox(const char *title, const char *file, int height, int width)
{
    /* *INDENT-OFF* */
    static DLG_KEYS_BINDING binding[] = {
	HELPKEY_BINDINGS,
	ENTERKEY_BINDINGS,
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  'J' ),
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  'j' ),
	DLG_KEYS_DATA( DLGK_GRID_DOWN,  KEY_DOWN ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'H' ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'h' ),
	DLG_KEYS_DATA( DLGK_GRID_LEFT,  KEY_LEFT ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'L' ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'l' ),
	DLG_KEYS_DATA( DLGK_GRID_RIGHT, KEY_RIGHT ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    'K' ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    'k' ),
	DLG_KEYS_DATA( DLGK_GRID_UP,    KEY_UP ),
	DLG_KEYS_DATA( DLGK_PAGE_FIRST, 'g' ),
	DLG_KEYS_DATA( DLGK_PAGE_FIRST, KEY_HOME ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  'G' ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  KEY_END ),
	DLG_KEYS_DATA( DLGK_PAGE_LAST,  KEY_LL ),
	DLG_KEYS_DATA( DLGK_PAGE_NEXT,  ' ' ),
	DLG_KEYS_DATA( DLGK_PAGE_NEXT,  KEY_NPAGE ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  'B' ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  'b' ),
	DLG_KEYS_DATA( DLGK_PAGE_PREV,  KEY_PPAGE ),
	DLG_KEYS_DATA( DLGK_BEGIN,	'0' ),
	DLG_KEYS_DATA( DLGK_BEGIN,	KEY_BEG ),
	DLG_KEYS_DATA( DLGK_FIELD_NEXT, TAB ),
	DLG_KEYS_DATA( DLGK_FIELD_PREV, KEY_BTAB ),
	END_KEYS_BINDING
    };
    /* *INDENT-ON* */

#ifdef KEY_RESIZE
    int old_height = height;
    int old_width = width;
#endif
    long fpos;
    int x, y, cur_x, cur_y;
    int key = 0, fkey;
    int next = 0;
    int i, code, passed_end;
    char search_term[MAX_LEN + 1];
    MY_OBJ obj;
    WINDOW *dialog;
    bool moved;
    int result = DLG_EXIT_UNKNOWN;
    int button = dlg_default_button();
    int min_width = 12;

    search_term[0] = '\0';	/* no search term entered yet */

    memset(&obj, 0, sizeof(obj));

    obj.begin_reached = TRUE;
    obj.buffer_first = TRUE;
    obj.end_reached = FALSE;
    obj.buttons = dlg_exit_label();

    /* Open input file for reading */
    if ((obj.fd = open(file, O_RDONLY)) == -1)
	dlg_exiterr("Can't open input file %s", file);

    /* Get file size. Actually, 'file_size' is the real file size - 1,
       since it's only the last byte offset from the beginning */
    lseek_end(&obj, 0L);

    /* Restore file pointer to beginning of file after getting file size */
    lseek_set(&obj, 0L);

    read_high(&obj, BUF_SIZE);

    dlg_button_layout(obj.buttons, &min_width);

#ifdef KEY_RESIZE
  retry:
#endif
    moved = TRUE;

    dlg_auto_sizefile(title, file, &height, &width, 2, min_width);
    dlg_print_size(height, width);
    dlg_ctl_size(height, width);

    x = dlg_box_x_ordinate(width);
    y = dlg_box_y_ordinate(height);

    dialog = dlg_new_window(height, width, y, x);
    dlg_register_window(dialog, "textbox", binding);
    dlg_register_buttons(dialog, "textbox", obj.buttons);

    dlg_mouse_setbase(x, y);

    /* Create window for text region, used for scrolling text */
    obj.text = dlg_sub_window(dialog, PAGE_LENGTH, PAGE_WIDTH, y + 1, x + 1);

    /* register the new window, along with its borders */
    dlg_mouse_mkbigregion(0, 0, PAGE_LENGTH + 2, width, KEY_MAX, 1, 1, 1 /* lines */ );
    dlg_draw_box2(dialog, 0, 0, height, width, dialog_attr, border_attr, border2_attr);
    dlg_draw_bottom_box2(dialog, border_attr, border2_attr, dialog_attr);
    dlg_draw_title(dialog, title);

    dlg_draw_buttons(dialog, PAGE_LENGTH + 2, 0, obj.buttons, button, FALSE, width);
    (void) wnoutrefresh(dialog);
    getyx(dialog, cur_y, cur_x);	/* Save cursor position */

    dlg_attr_clear(obj.text, PAGE_LENGTH, PAGE_WIDTH, dialog_attr);

    while (result == DLG_EXIT_UNKNOWN) {

	/*
	 * Update the screen according to whether we shifted up/down by a line
	 * or not.
	 */
	if (moved) {
	    if (next < 0) {
		(void) scrollok(obj.text, TRUE);
		(void) scroll(obj.text);	/* Scroll text region up one line */
		(void) scrollok(obj.text, FALSE);
		print_line(&obj, PAGE_LENGTH - 1, PAGE_WIDTH);
		(void) wnoutrefresh(obj.text);
	    } else if (next > 0) {
		/*
		 * We don't call print_page() here but use scrolling to ensure
		 * faster screen update.  However, 'end_reached' and
		 * 'page_length' should still be updated, and 'in_buf' should
		 * point to start of next page.  This is done by calling
		 * get_line() in the following 'for' loop.
		 */
		(void) scrollok(obj.text, TRUE);
		(void) wscrl(obj.text, -1);	/* Scroll text region down one line */
		(void) scrollok(obj.text, FALSE);
		obj.page_length = 0;
		passed_end = 0;
		for (i = 0; i < PAGE_LENGTH; i++) {
		    if (!i) {
			print_line(&obj, 0, PAGE_WIDTH);	/* print first line of page */
			(void) wnoutrefresh(obj.text);
		    } else
			(void) get_line(&obj);	/* Called to update 'end_reached' and 'in_buf' */
		    if (!passed_end)
			obj.page_length++;
		    if (obj.end_reached && !passed_end)
			passed_end = 1;
		}
	    } else {
		print_page(&obj, PAGE_LENGTH, PAGE_WIDTH);
	    }
	    print_position(&obj, dialog, height, width);
	    (void) wmove(dialog, cur_y, cur_x);		/* Restore cursor position */
	    wrefresh(dialog);
	}
	moved = FALSE;		/* assume we'll not move */
	next = 0;		/* ...but not scroll by a line */

	key = dlg_mouse_wgetch(dialog, &fkey);
	if (dlg_result_key(key, fkey, &result))
	    break;

	if (!fkey && (code = dlg_char_to_button(key, obj.buttons)) >= 0) {
	    result = dlg_ok_buttoncode(code);
	    break;
	}

	if (fkey) {
	    switch (key) {
	    default:
		if (is_DLGK_MOUSE(key)) {
		    result = dlg_exit_buttoncode(key - M_EVENT);
		    if (result < 0)
			result = DLG_EXIT_OK;
		} else {
		    beep();
		}
		break;
	    case DLGK_FIELD_NEXT:
		button = dlg_next_button(obj.buttons, button);
		if (button < 0)
		    button = 0;
		dlg_draw_buttons(dialog,
				 height - 2, 0,
				 obj.buttons, button,
				 FALSE, width);
		break;
	    case DLGK_FIELD_PREV:
		button = dlg_prev_button(obj.buttons, button);
		if (button < 0)
		    button = 0;
		dlg_draw_buttons(dialog,
				 height - 2, 0,
				 obj.buttons, button,
				 FALSE, width);
		break;
	    case DLGK_ENTER:
		if (dialog_vars.nook)
		    result = DLG_EXIT_OK;
		else
		    result = dlg_exit_buttoncode(button);
		break;
	    case DLGK_PAGE_FIRST:
		if (!obj.begin_reached) {
		    obj.begin_reached = 1;
		    /* First page not in buffer? */
		    fpos = ftell_obj(&obj);

		    if (fpos > obj.fd_bytes_read) {
			/* Yes, we have to read it in */
			lseek_set(&obj, 0L);

			read_high(&obj, BUF_SIZE);
		    }
		    obj.in_buf = 0;
		    moved = TRUE;
		}
		break;
	    case DLGK_PAGE_LAST:
		obj.end_reached = TRUE;
		/* Last page not in buffer? */
		fpos = ftell_obj(&obj);

		if (fpos < obj.file_size) {
		    /* Yes, we have to read it in */
		    lseek_end(&obj, -BUF_SIZE);

		    read_high(&obj, BUF_SIZE);
		}
		obj.in_buf = obj.bytes_read;
		back_lines(&obj, (long) PAGE_LENGTH);
		moved = TRUE;
		break;
	    case DLGK_GRID_UP:	/* Previous line */
		if (!obj.begin_reached) {
		    back_lines(&obj, obj.page_length + 1);
		    next = 1;
		    moved = TRUE;
		}
		break;
	    case DLGK_PAGE_PREV:	/* Previous page */
	    case DLGK_MOUSE(KEY_PPAGE):
		if (!obj.begin_reached) {
		    back_lines(&obj, obj.page_length + PAGE_LENGTH);
		    moved = TRUE;
		}
		break;
	    case DLGK_GRID_DOWN:	/* Next line */
		if (!obj.end_reached) {
		    obj.begin_reached = 0;
		    next = -1;
		    moved = TRUE;
		}
		break;
	    case DLGK_PAGE_NEXT:	/* Next page */
	    case DLGK_MOUSE(KEY_NPAGE):
		if (!obj.end_reached) {
		    obj.begin_reached = 0;
		    moved = TRUE;
		}
		break;
	    case DLGK_BEGIN:	/* Beginning of line */
		if (obj.hscroll > 0) {
		    obj.hscroll = 0;
		    /* Reprint current page to scroll horizontally */
		    back_lines(&obj, obj.page_length);
		    moved = TRUE;
		}
		break;
	    case DLGK_GRID_LEFT:	/* Scroll left */
		if (obj.hscroll > 0) {
		    obj.hscroll--;
		    /* Reprint current page to scroll horizontally */
		    back_lines(&obj, obj.page_length);
		    moved = TRUE;
		}
		break;
	    case DLGK_GRID_RIGHT:	/* Scroll right */
		if (obj.hscroll < MAX_LEN) {
		    obj.hscroll++;
		    /* Reprint current page to scroll horizontally */
		    back_lines(&obj, obj.page_length);
		    moved = TRUE;
		}
		break;
#ifdef KEY_RESIZE
	    case KEY_RESIZE:
		/* reset data */
		height = old_height;
		width = old_width;
		back_lines(&obj, obj.page_length);
		/* repaint */
		dlg_clear();
		dlg_del_window(dialog);
		refresh();
		dlg_mouse_free_regions();
		goto retry;
#endif
	    }
	} else {
	    switch (key) {
	    case '/':		/* Forward search */
	    case 'n':		/* Repeat forward search */
	    case '?':		/* Backward search */
	    case 'N':		/* Repeat backward search */
		moved = perform_search(&obj, height, width, key, search_term);
		fkey = FALSE;
		break;
	    default:
		beep();
		break;
	    }
	}
    }

    dlg_del_window(dialog);
    free(obj.buf);
    (void) close(obj.fd);
    dlg_mouse_free_regions();
    return result;
}
Пример #26
0
int main(int argc, char **argv)
{
    setbuf(stdout, NULL);
    signal(SIGINT, INThandler);

    unsigned char ply = 6;

    int opt;
    while ((opt = getopt(argc, argv, "p:")) != -1) {
        switch (opt) {
        case 'p':
            ply = atoi(optarg);
            break;
        default:
            fprintf(stderr, "Usage: %s [-p ply]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    struct position pos;
    init_position(&pos);
    assert(consistency(&pos));

    struct timespec realt_old, realt_new;

    tt = new_trans_tables();

#ifdef _USE_HISTORY
    hist = init_history();
#endif

#ifdef _DEBUG
    testing();
#endif

#ifndef _XBOARD
    print_position(&pos);
#endif

    while (1) {
        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        user_input(&pos);
#ifndef _XBOARD
        print_position(&pos);
#endif
        assert(consistency(&pos));

        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        current_utc_time(&realt_old);
        computer_move(&pos, ply);
        assert(consistency(&pos));
        current_utc_time(&realt_new);

#ifndef _XBOARD
        fprintf(stderr, "One second: %12llu ns\n",
            (long long unsigned)BILLION);
        fprintf(stderr, "Real  time: %12llu ns\n",
            (long long unsigned)minus_time(&realt_new, &realt_old));

        print_position(&pos);
#endif
    }

    return (0);
}