Beispiel #1
0
/*
 * Display a dialog box with a list of options that can be turned on or off
 * The `flag' parameter is used to select between radiolist and checklist.
 */
int
dialog_checklist (const char *title, const char *prompt, int height, int width,
	int list_height, int item_no, const char * const * items, int flag)
	
{
    int i, x, y, box_x, box_y;
    int key = 0, button = 0, choice = 0, scroll = 0, max_choice, *status;
    WINDOW *dialog, *list;

    checkflag = flag;

    /* Allocate space for storing item on/off status */
    if ((status = malloc (sizeof (int) * item_no)) == NULL) {
	endwin ();
	fprintf (stderr,
		 "\nCan't allocate memory in dialog_checklist().\n");
	exit (-1);
    }

    /* Initializes status */
    for (i = 0; i < item_no; i++) {
	status[i] = !strcasecmp (items[i * 3 + 2], "on");
	if (!choice && status[i])
            choice = i;
    }

    max_choice = MIN (list_height, item_no);

    /* 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);

    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);
    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, ' ');
    }

    wattrset (dialog, dialog_attr);
    print_autowrap (dialog, prompt, width - 2, 1, 3);

    list_width = width - 6;
    box_y = height - list_height - 5;
    box_x = (width - list_width) / 2 - 1;

    /* create new window for the list */
    list = subwin (dialog, list_height, list_width, y+box_y+1, x+box_x+1);

    keypad (list, TRUE);

    /* draw a box around the list items */
    draw_box (dialog, box_y, box_x, list_height + 2, list_width + 2,
	      menubox_border_attr, menubox_attr);

    /* Find length of longest item in order to center checklist */
    check_x = 0;
    for (i = 0; i < item_no; i++) 
	check_x = MAX (check_x, + strlen (items[i * 3 + 1]) + 4);

    check_x = (list_width - check_x) / 2;
    item_x = check_x + 4;

    if (choice >= list_height) {
	scroll = choice - list_height + 1;
	choice -= scroll;
    }

    /* Print the list */
    for (i = 0; i < max_choice; i++) {
	print_item (list, items[(scroll+i) * 3 + 1],
		    status[i+scroll], i, i == choice);
    }

    print_arrows(dialog, choice, item_no, scroll,
			box_y, box_x + check_x + 5, list_height);

    print_buttons(dialog, height, width, 0);

    wnoutrefresh (list);
    wnoutrefresh (dialog);
    doupdate ();

    while (key != ESC) {
	key = wgetch (dialog);

    	for (i = 0; i < max_choice; i++)
            if (toupper(key) == toupper(items[(scroll+i)*3+1][0]))
                break;


	if ( i < max_choice || key == KEY_UP || key == KEY_DOWN || 
	    key == '+' || key == '-' ) {
	    if (key == KEY_UP || key == '-') {
		if (!choice) {
		    if (!scroll)
			continue;
		    /* Scroll list down */
		    if (list_height > 1) {
			/* De-highlight current first item */
			print_item (list, items[scroll * 3 + 1],
					status[scroll], 0, FALSE);
			scrollok (list, TRUE);
			wscrl (list, -1);
			scrollok (list, FALSE);
		    }
		    scroll--;
		    print_item (list, items[scroll * 3 + 1],
				status[scroll], 0, TRUE);
		    wnoutrefresh (list);

    		    print_arrows(dialog, choice, item_no, scroll,
				box_y, box_x + check_x + 5, list_height);

		    wrefresh (dialog);

		    continue;	/* wait for another key press */
		} else
		    i = choice - 1;
	    } else if (key == KEY_DOWN || key == '+') {
		if (choice == max_choice - 1) {
		    if (scroll + choice >= item_no - 1)
			continue;
		    /* Scroll list up */
		    if (list_height > 1) {
			/* De-highlight current last item before scrolling up */
			print_item (list, items[(scroll + max_choice - 1) * 3 + 1],
				    status[scroll + max_choice - 1],
				    max_choice - 1, FALSE);
			scrollok (list, TRUE);
			scroll (list);
			scrollok (list, FALSE);
		    }
		    scroll++;
		    print_item (list, items[(scroll + max_choice - 1) * 3 + 1],
				status[scroll + max_choice - 1],
				max_choice - 1, TRUE);
		    wnoutrefresh (list);

    		    print_arrows(dialog, choice, item_no, scroll,
				box_y, box_x + check_x + 5, list_height);

		    wrefresh (dialog);

		    continue;	/* wait for another key press */
		} else
		    i = choice + 1;
	    }
	    if (i != choice) {
		/* De-highlight current item */
		print_item (list, items[(scroll + choice) * 3 + 1],
			    status[scroll + choice], choice, FALSE);
		/* Highlight new item */
		choice = i;
		print_item (list, items[(scroll + choice) * 3 + 1],
			    status[scroll + choice], choice, TRUE);
		wnoutrefresh (list);
		wrefresh (dialog);
	    }
	    continue;		/* wait for another key press */
	}
	switch (key) {
	case 'H':
	case 'h':
	case '?':
	    delwin (dialog);
	    free (status);
	    return 1;
	case 'S':
	case 's':
	case ' ':
	case '\n':
	    if (!button) {
		if (flag == FLAG_CHECK) {
		    status[scroll + choice] = !status[scroll + choice];
		    wmove (list, choice, check_x);
		    wattrset (list, check_selected_attr);
		    wprintw (list, "[%c]", status[scroll + choice] ? 'X' : ' ');
		} else {
		    if (!status[scroll + choice]) {
			for (i = 0; i < item_no; i++)
			    status[i] = 0;
			status[scroll + choice] = 1;
			for (i = 0; i < max_choice; i++)
			    print_item (list, items[(scroll + i) * 3 + 1],
					status[scroll + i], i, i == choice);
		    }
		}
		wnoutrefresh (list);
		wrefresh (dialog);
            
		for (i = 0; i < item_no; i++) {
		    if (status[i]) {
			if (flag == FLAG_CHECK) {
			    fprintf (stderr, "\"%s\" ", items[i * 3]);
			} else {
			    fprintf (stderr, "%s", items[i * 3]);
			}

		    }
		}
            }
	    delwin (dialog);
	    free (status);
	    return button;
	case 'X':
	case 'x':
	    key = ESC;
	case ESC:
	    break;
	}

	/* Now, update everything... */
	doupdate ();
    }
    

    delwin (dialog);
    free (status);
    return -1;			/* ESC pressed */
}
Beispiel #2
0
/* 
 * called to redraw the menu
 */
static int wdg_input_redraw(struct wdg_object *wo)
{
   WDG_WO_EXT(struct wdg_input_handle, ww);
   size_t c, l, x, y;
   
   WDG_DEBUG_MSG("wdg_input_redraw");
   
   /* center the window on the screen */
   wo->x1 = (current_screen.cols - (ww->x + 2)) / 2;
   wo->y1 = (current_screen.lines - (ww->y + 2)) / 2;
   wo->x2 = -wo->x1;
   wo->y2 = -wo->y1;
   
   c = wdg_get_ncols(wo);
   l = wdg_get_nlines(wo);
   x = wdg_get_begin_x(wo);
   y = wdg_get_begin_y(wo);
   
   /* deal with rouding */
   if (l != ww->y + 2) l = ww->y + 2;
   if (c != ww->x + 2) c = ww->x + 2;
 
   /* the window already exist */
   if (ww->win) {
      /* erase the border */
      wbkgd(ww->win, COLOR_PAIR(wo->screen_color));
      werase(ww->win);
      /* destroy the internal form */
      wdg_input_form_destroy(wo);
      
      touchwin(ww->win);
      wnoutrefresh(ww->win);

      /* set the form color */
      wbkgd(ww->win, COLOR_PAIR(wo->window_color));
     
      /* resize the window */
      mvwin(ww->win, y, x);
      wresize(ww->win, l, c);
      
      /* redraw the window */
      wdg_input_borders(wo);
      
      /* create the internal form */
      wdg_input_form_create(wo);
      
      touchwin(ww->win);

   /* the first time we have to allocate the window */
   } else {

      /* create the menu window (fixed dimensions) */
      if ((ww->win = newwin(l, c, y, x)) == NULL)
         return -WDG_E_FATAL;

      /* set the window color */
      wbkgd(ww->win, COLOR_PAIR(wo->window_color));
      redrawwin(ww->win);
      
      /* draw the titles */
      wdg_input_borders(wo);

      /* create the internal form */
      wdg_input_form_create(wo);

      /* no scrolling for menu */
      scrollok(ww->win, FALSE);

   }
   
   /* refresh the window */
   touchwin(ww->win);
   wnoutrefresh(ww->win);
   
   touchwin(ww->fwin);
   wnoutrefresh(ww->fwin);

   wo->flags |= WDG_OBJ_VISIBLE;

   return WDG_E_SUCCESS;
}
Beispiel #3
0
int processInput(char *command, int terminalIndex, int screenHeight, int screenWidth) {
    int *vtCoordinates, *vtCoordPointer;
    int numberTerminals;
    int i, j, k;
    int targets[10], targetCounter;
    struct virtualTerminal *vt;
    char *pRest, *pRest2, *pToken;


    if(isdigit(*command)) { // command starts with digit
        // build up array of target terminals
        /*
        for(i = 0; i < 10; i++)
        	targets[i] = -1;
        */
        targetCounter = 0;

        i = -1;
        j = strtol(command, &pRest, 10); // get target terminal
        while(*pRest == '-' || *pRest == ',') {
            j--; // terminals are numbered starting at 1 on the screen
            if(i != -1) { // i contains start of a range
                i++; // we already added the first in the range so skip it
                for(; i < j; i++)
                    targets[targetCounter++] = i;
                i = -1;
            }

            if(*pRest == '-') { // range
                i = j; // copy start of range into i
            } else {
            }
            targets[targetCounter++] = j;
            pRest++;
            j = strtol(pRest, &pRest, 10); // get target terminal
        }
        j--; // terminals are numbered starting at 1 on the screen
        if(i != -1) { // i contains start of a range
            i++; // we already added the first in the range so skip it
            for(; i < j; i++)
                targets[targetCounter++] = i;
            i = -1;
        } else
            targets[targetCounter++] = j;

        if(*pRest == 0) {
            j = targets[0];
            if(vtGet(j)) {
                vtHighlight(j);
                return j;
            }
        }

        // move the following three to functions
        if(*pRest == ' ') { // terminal # followed by space then commands to send to it ... send with newline
            strcat(pRest, "\n"); // send newline? ... this needs to be optional
        }
        if(*pRest == ':') { // terminal # followed by colon then commands to send to it ... send without newline
        }
        pRest++;

        for(j = 0; j < targetCounter; j++) {
            i = targets[j];
            //fprintf(stderr, "#%d\n", i);
            //continue;
            if(i < 0 || i > 10) // make sure we have a valid number
                continue;
            // rest of command should be a terminal-specific command
            vtSend(i, pRest); // move past space

            /*
            if(*pRest == '.') {
            	pRest++;
            	if(strcmp(pRest, "close") == 0 || strcmp(pRest, "destroy") == 0) { // destroy terminal
            	}
            	if(strcmp(pRest, "hide") == 0) {
            	}
            }
            */

            /*
            if(*pRest == '-') { // range of terminal numbers
            	pRest++;
            	j = strtol(pRest, &pRest, 10); // get last target terminal
            	if(*pRest == ' ') { // terminal # followed by space then commands to send to it ... send with newline
            		pRest++; // move past space
            		strcat(pRest, "\n"); // send newline? ... this needs to be optional
            		for(i; i <= j; i++) {
            			vtSend(i-1, pRest);
            		}
            	}
            	if(*pRest == ':') { // terminal # followed by colon then commands to send to it ... send without newline
            		pRest++; // move past colon
            		vtSend(i, pRest);
            		for(; i <= j; i++) {
            			vtSend(i-1, pRest);
            		}
            	}
            }
            if(*pRest == ',') { // list of terminal numbers
            }
            */
        }

    } else { // command doesn't start with digit

        pToken = strtok(command, " ");
        if(pToken) {
            if(strcmp(pToken, "quit") == 0) {
                keepRunning = 0;
            }
            if(strcmp(pToken, "create") == 0) {
                pToken = strtok(NULL, " ");
                if(pToken && isdigit(*pToken)) { // probably have a number
                    numberTerminals = strtol(pToken, NULL, 10); // get target terminal
                } else
                    numberTerminals = 1;
                for(i = 0; i < 10; i++) {
                    if(vtGet(i) != NULL)
                        numberTerminals++;
                }

#ifdef DEBUG
                fprintf(stderr, "%d existing terminals, creating 1\n", numberTerminals - 1);
#endif

                // we're about to resize terminals, clear the background
                wclear(ncursesScreen);
                wnoutrefresh(ncursesScreen);
                // move terms around if not all positions are filled but last one is
                // array of terminals needs to reflect the order they are on the screen
                vtCoordPointer = vtCoordinates = divideRectangle_favorHeight(screenWidth, screenHeight - 2, numberTerminals, 1);
                for(i = 0; i < 10; i++) {
                    vt = vtGet(i);
                    if(vt) {
                        vtMove(i, *vtCoordPointer, *(vtCoordPointer + 1), *(vtCoordPointer + 2), *(vtCoordPointer + 3));
                    } else // found a spot to put our new terminal(s)
                        break;

                    vtCoordPointer += 4;
                }
                for(; i < numberTerminals; i++) {
                    vtCreate(*(vtCoordPointer + 2), *(vtCoordPointer + 3), *vtCoordPointer, *(vtCoordPointer + 1), i);
                    vtCoordPointer += 4;
                }
                free(vtCoordinates);
                // draw separation lines
            }
        }
    }
    return terminalIndex;
}
Beispiel #4
0
/* Get a string of input at the statusbar prompt.  This should only be
 * called from do_prompt(). */
const sc *get_prompt_string(int *actual, bool allow_tabs,
#ifndef DISABLE_TABCOMP
	bool allow_files,
#endif
	const char *curranswer,
	bool *meta_key, bool *func_key,
#ifndef NANO_TINY
	filestruct **history_list,
#endif
	void (*refresh_func)(void), int menu
#ifndef DISABLE_TABCOMP
	, bool *list
#endif
	)
{
    int kbinput = ERR;
    bool have_shortcut, ran_func, finished;
    size_t curranswer_len;
    const sc *s;
#ifndef DISABLE_TABCOMP
    bool tabbed = FALSE;
	/* Whether we've pressed Tab. */
#endif
#ifndef NANO_TINY
    char *history = NULL;
	/* The current history string. */
    char *magichistory = NULL;
	/* The temporary string typed at the bottom of the history, if
	 * any. */
#ifndef DISABLE_TABCOMP
    int last_kbinput = ERR;
	/* The key we pressed before the current key. */
    size_t complete_len = 0;
	/* The length of the original string that we're trying to
	 * tab complete, if any. */
#endif
#endif /* !NANO_TINY */

    answer = mallocstrcpy(answer, curranswer);
    curranswer_len = strlen(answer);

    /* If reset_statusbar_x is TRUE, restore statusbar_x and
     * statusbar_pww to what they were before this prompt.  Then, if
     * statusbar_x is uninitialized or past the end of curranswer, put
     * statusbar_x at the end of the string and update statusbar_pww
     * based on it.  We do these things so that the cursor position
     * stays at the right place if a prompt-changing toggle is pressed,
     * or if this prompt was started from another prompt and we cancel
     * out of it. */
    if (reset_statusbar_x) {
	statusbar_x = old_statusbar_x;
	statusbar_pww = old_pww;
    }

    if (statusbar_x == (size_t)-1 || statusbar_x > curranswer_len) {
	statusbar_x = curranswer_len;
	statusbar_pww = statusbar_xplustabs();
    }

    currmenu = menu;

#ifdef DEBUG
fprintf(stderr, "get_prompt_string: answer = \"%s\", statusbar_x = %lu\n", answer, (unsigned long) statusbar_x);
#endif

    update_statusbar_line(answer, statusbar_x);

    /* Refresh the edit window and the statusbar before getting
     * input. */
    wnoutrefresh(edit);
    wnoutrefresh(bottomwin);

    /* If we're using restricted mode, we aren't allowed to change the
     * name of the current file once it has one, because that would
     * allow writing to files not specified on the command line.  In
     * this case, disable all keys that would change the text if the
     * filename isn't blank and we're at the "Write File" prompt. */
    while (1) {
	kbinput = do_statusbar_input(meta_key, func_key, &have_shortcut,
	    &ran_func, &finished, TRUE, refresh_func);
	assert(statusbar_x <= strlen(answer));

	s = get_shortcut(currmenu, &kbinput, meta_key, func_key);

	if (s)
	    if (s->scfunc == do_cancel || s->scfunc == do_enter_void)
		break;

#ifndef DISABLE_TABCOMP
	if (s && s->scfunc != do_tab)
	    tabbed = FALSE;
#endif

#ifndef DISABLE_TABCOMP
#ifndef NANO_TINY
	if (s && s->scfunc == do_tab) {
		if (history_list != NULL) {
		    if (last_kbinput != sc_seq_or(do_tab, NANO_CONTROL_I))
			complete_len = strlen(answer);

		    if (complete_len > 0) {
			answer = mallocstrcpy(answer,
				get_history_completion(history_list,
				answer, complete_len));
			statusbar_x = strlen(answer);
		    }
		} else
#endif /* !NANO_TINY */
		if (allow_tabs)
		    answer = input_tab(answer, allow_files,
			&statusbar_x, &tabbed, refresh_func, list);

		update_statusbar_line(answer, statusbar_x);
	} else
#endif /* !DISABLE_TABCOMP */
#ifndef NANO_TINY
	if (s && s->scfunc == get_history_older_void) {
		if (history_list != NULL) {
		    /* If we're scrolling up at the bottom of the
		     * history list and answer isn't blank, save answer
		     * in magichistory. */
		    if ((*history_list)->next == NULL &&
			answer[0] != '\0')
			magichistory = mallocstrcpy(magichistory,
				answer);

		    /* Get the older search from the history list and
		     * save it in answer.  If there is no older search,
		     * don't do anything. */
		    if ((history =
			get_history_older(history_list)) != NULL) {
			answer = mallocstrcpy(answer, history);
			statusbar_x = strlen(answer);
		    }

		    update_statusbar_line(answer, statusbar_x);

		    /* This key has a shortcut list entry when it's used
		     * to move to an older search, which means that
		     * finished has been set to TRUE.  Set it back to
		     * FALSE here, so that we aren't kicked out of the
		     * statusbar prompt. */
		    finished = FALSE;
		}
	} else if (s && s->scfunc == get_history_newer_void) {
		if (history_list != NULL) {
		    /* Get the newer search from the history list and
		     * save it in answer.  If there is no newer search,
		     * don't do anything. */
		    if ((history =
			get_history_newer(history_list)) != NULL) {
			answer = mallocstrcpy(answer, history);
			statusbar_x = strlen(answer);
		    }

		    /* If, after scrolling down, we're at the bottom of
		     * the history list, answer is blank, and
		     * magichistory is set, save magichistory in
		     * answer. */
		    if ((*history_list)->next == NULL &&
			*answer == '\0' && magichistory != NULL) {
			answer = mallocstrcpy(answer, magichistory);
			statusbar_x = strlen(answer);
		    }

		    update_statusbar_line(answer, statusbar_x);

		    /* This key has a shortcut list entry when it's used
		     * to move to a newer search, which means that
		     * finished has been set to TRUE.  Set it back to
		     * FALSE here, so that we aren't kicked out of the
		     * statusbar prompt. */
		    finished = FALSE;
		}
	} else
#endif /* !NANO_TINY */
	if (s && s->scfunc == do_help_void) {
		update_statusbar_line(answer, statusbar_x);

		/* This key has a shortcut list entry when it's used to
		 * go to the help browser or display a message
		 * indicating that help is disabled, which means that
		 * finished has been set to TRUE.  Set it back to FALSE
		 * here, so that we aren't kicked out of the statusbar
		 * prompt. */
		finished = FALSE;
	}

	/* If we have a shortcut with an associated function, break out
	 * if we're finished after running or trying to run the
	 * function. */
	if (finished)
	    break;

#if !defined(NANO_TINY) && !defined(DISABLE_TABCOMP)
	last_kbinput = kbinput;
#endif

	reset_statusbar_cursor();
	wnoutrefresh(bottomwin);
    }


#ifndef NANO_TINY
    /* Set the current position in the history list to the bottom and
     * free magichistory, if we need to. */
    if (history_list != NULL) {
	history_reset(*history_list);

	if (magichistory != NULL)
	    free(magichistory);
    }
#endif


    /* We've finished putting in an answer or run a normal shortcut's
     * associated function, so reset statusbar_x and statusbar_pww.  If
     * we've finished putting in an answer, reset the statusbar cursor
     * position too. */
    if (s) {
	if (s->scfunc ==  do_cancel || s->scfunc == do_enter_void ||
	ran_func) {
	    statusbar_x = old_statusbar_x;
	    statusbar_pww = old_pww;

	    if (!ran_func)
		reset_statusbar_x = TRUE;
    /* Otherwise, we're still putting in an answer or a shortcut with
     * an associated function, so leave the statusbar cursor position
     * alone. */
	} else
	    reset_statusbar_x = FALSE;
    }

    *actual = kbinput;
    return s;
}
Beispiel #5
0
static void blocklist_onDraw(ToxWindow *self, Tox *m, int y2, int x2)
{
    wattron(self->window, A_BOLD);
    wprintw(self->window, " Blocked: ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "%d\n\n", Blocked.num_blocked);

    if ((y2 - FLIST_OFST) <= 0) {
        return;
    }

    uint32_t selected_num = 0;

    /* Determine which portion of friendlist to draw based on current position */
    int page = Blocked.num_selected / (y2 - FLIST_OFST);
    int start = (y2 - FLIST_OFST) * page;
    int end = y2 - FLIST_OFST + start;

    int i;

    for (i = start; i < Blocked.num_blocked && i < end; ++i) {
        uint32_t f = Blocked.index[i];
        bool f_selected = false;

        if (i == Blocked.num_selected) {
            wattron(self->window, A_BOLD);
            wprintw(self->window, " > ");
            wattroff(self->window, A_BOLD);
            selected_num = f;
            f_selected = true;
        } else {
            wprintw(self->window, "   ");
        }

        wattron(self->window, COLOR_PAIR(RED));
        wprintw(self->window, "x");
        wattroff(self->window, COLOR_PAIR(RED));

        if (f_selected) {
            wattron(self->window, COLOR_PAIR(BLUE));
        }

        wattron(self->window, A_BOLD);
        wprintw(self->window, " %s\n", Blocked.list[f].name);
        wattroff(self->window, A_BOLD);

        if (f_selected) {
            wattroff(self->window, COLOR_PAIR(BLUE));
        }
    }

    wprintw(self->window, "\n");
    self->x = x2;

    if (Blocked.num_blocked) {
        wmove(self->window, y2 - 1, 1);

        wattron(self->window, A_BOLD);
        wprintw(self->window, "Key: ");
        wattroff(self->window, A_BOLD);

        int i;

        for (i = 0; i < TOX_PUBLIC_KEY_SIZE; ++i) {
            wprintw(self->window, "%02X", Blocked.list[selected_num].pub_key[i] & 0xff);
        }
    }

    wnoutrefresh(self->window);
    draw_del_popup();

    if (self->help->active) {
        help_onDraw(self);
    }
}
Beispiel #6
0
/*
 * Display a dialog box with a list of options that can be turned on or off
 */
int dialog_checklist(char *title, char *prompt, int height, int width, int list_height, int item_no, char **items)
{
  int i, x, y, cur_x, cur_y, box_x, box_y, key = 0, button = 0, choice = 0,
      scrolli = 0, max_choice, *status;
  WINDOW *dialog, *list;

  /* Allocate space for storing item on/off status */
  if ((status = malloc(sizeof(int)*item_no)) == NULL) {
    endwin();
    fprintf(stderr, "\nCan't allocate memory in dialog_checklist().\n");
    exit(-1);
  }
  /* Initializes status */
  for (i = 0; i < item_no; i++)
    status[i] = !strcasecmp(items[i*3 + 2], "on");

  max_choice = MIN(list_height, item_no);

  /* center dialog box on screen */
  x = (COLS - width)/2;
  y = (LINES - height)/2;
  
#ifdef HAVE_NCURSES
  if (use_shadow)
    draw_shadow(stdscr, y, x, height, width);
#endif
  dialog = newwin(height, width, y, x);
  keypad(dialog, TRUE);

  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, ' ');
  }
  wattrset(dialog, dialog_attr);
  print_autowrap(dialog, prompt, width, 1, 3);

  list_width = width-6;
  getyx(dialog, cur_y, cur_x);
  box_y = cur_y + 1;
  box_x = (width - list_width)/2 - 1;

  /* create new window for the list */
  list = subwin(dialog, list_height, list_width, y + box_y + 1, x + box_x + 1);
  keypad(list, TRUE);

  /* draw a box around the list items */
  draw_box(dialog, box_y, box_x, list_height+2, list_width+2, menubox_border_attr, menubox_attr);

  check_x = 0;
  item_x = 0;
  /* Find length of longest item in order to center checklist */
  for (i = 0; i < item_no; i++) {
    check_x = MAX(check_x, strlen(items[i*3]) + strlen(items[i*3 + 1]) + 6);
    item_x = MAX(item_x, strlen(items[i*3]));
  }
  check_x = (list_width - check_x) / 2;
  item_x = check_x + item_x + 6;

  /* Print the list */
  for (i = 0; i < max_choice; i++)
    print_item(list, items[i*3], items[i*3 + 1], status[i], i, i == choice);
  wnoutrefresh(list);

  if (list_height < item_no) {
    wattrset(dialog, darrow_attr);
    wmove(dialog, box_y + list_height + 1, box_x + check_x + 5);
    waddch(dialog, ACS_DARROW);
    wmove(dialog, box_y + list_height + 1, box_x + check_x + 6);
    waddstr(dialog, "(+)");
  }

  x = width/2-11;
  y = height-2;
  print_button(dialog, "Cancel", y, x+14, FALSE);
  print_button(dialog, "  OK  ", y, x, TRUE);
  wrefresh(dialog);

  while (key != ESC) {
    key = wgetch(dialog);
    /* Check if key pressed matches first character of any item tag in list */
    for (i = 0; i < max_choice; i++)
      if (toupper(key) == toupper(items[(scrolli+i)*3][0]))
        break;

    if (i < max_choice || (key >= '1' && key <= MIN('9', '0'+max_choice)) || 
        key == KEY_UP || key == KEY_DOWN || key == ' ' ||
        key == '+' || key == '-' ) {
      if (key >= '1' && key <= MIN('9', '0'+max_choice))
        i = key - '1';
      else if (key == KEY_UP || key == '-') {
        if (!choice) {
          if (scrolli) {
#ifdef BROKEN_WSCRL
    /* wscrl() in ncurses 1.8.1 seems to be broken, causing a segmentation
       violation when scrolling windows of height = 4, so scrolling is not
       used for now */
            scrolli--;
            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
            /* Reprint list to scroll down */
            for (i = 0; i < max_choice; i++)
              print_item(list, items[(scrolli+i)*3], items[(scrolli+i)*3 + 1], status[scrolli+i], i, i == choice);

#else

            /* Scroll list down */
            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
            if (list_height > 1) {
              /* De-highlight current first item before scrolling down */
              print_item(list, items[scrolli*3], items[scrolli*3 + 1], status[scrolli], 0, FALSE);
              scrollok(list, TRUE);
              wscrl(list, -1);
              scrollok(list, FALSE);
            }
            scrolli--;
            print_item(list, items[scrolli*3], items[scrolli*3 + 1], status[scrolli], 0, TRUE);
#endif
            wnoutrefresh(list);

            /* print the up/down arrows */
            wmove(dialog, box_y, box_x + check_x + 5);
            wattrset(dialog, scrolli ? uarrow_attr : menubox_attr);
            waddch(dialog, scrolli ? ACS_UARROW : ACS_HLINE);
            wmove(dialog, box_y, box_x + check_x + 6);
            waddch(dialog, scrolli ? '(' : ACS_HLINE);
            wmove(dialog, box_y, box_x + check_x + 7);
            waddch(dialog, scrolli ? '-' : ACS_HLINE);
            wmove(dialog, box_y, box_x + check_x + 8);
            waddch(dialog, scrolli ? ')' : ACS_HLINE);
            wattrset(dialog, darrow_attr);
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 5);
            waddch(dialog, ACS_DARROW);
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 6);
            waddch(dialog, '(');
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 7);
            waddch(dialog, '+');
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 8);
            waddch(dialog, ')');
            wmove(dialog, cur_y, cur_x);  /* Restore cursor position */
            wrefresh(dialog);
          }
          continue;    /* wait for another key press */
        }
        else
          i = choice - 1;
      }
      else if (key == KEY_DOWN || key == '+') {
        if (choice == max_choice - 1) {
          if (scrolli+choice < item_no-1) {
#ifdef BROKEN_WSCRL
    /* wscrl() in ncurses 1.8.1 seems to be broken, causing a segmentation
       violation when scrolling windows of height = 4, so scrolling is not
       used for now */
            scrolli++;
            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
            /* Reprint list to scroll up */
            for (i = 0; i < max_choice; i++)
              print_item(list, items[(scrolli+i)*3], items[(scrolli+i)*3 + 1], status[scrolli+i], i, i == choice);

#else

            /* Scroll list up */
            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
            if (list_height > 1) {
              /* De-highlight current last item before scrolling up */
              print_item(list, items[(scrolli+max_choice-1)*3], items[(scrolli+max_choice-1)*3 + 1], status[scrolli+max_choice-1], max_choice-1, FALSE);
              scrollok(list, TRUE);
              scroll(list);
              scrollok(list, FALSE);
            }
            scrolli++;
            print_item(list, items[(scrolli+max_choice-1)*3], items[(scrolli+max_choice-1)*3 + 1], status[scrolli+max_choice-1], max_choice-1, TRUE);
#endif
            wnoutrefresh(list);

            /* print the up/down arrows */
            wattrset(dialog, uarrow_attr);
            wmove(dialog, box_y, box_x + check_x + 5);
            waddch(dialog, ACS_UARROW);
            wmove(dialog, box_y, box_x + check_x + 6);
            waddstr(dialog, "(-)");
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 5);
            wattrset(dialog, scrolli+choice < item_no-1 ? darrow_attr : menubox_border_attr);
            waddch(dialog, scrolli+choice < item_no-1 ? ACS_DARROW : ACS_HLINE);
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 6);
            waddch(dialog, scrolli+choice < item_no-1 ? '(' : ACS_HLINE);
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 7);
            waddch(dialog, scrolli+choice < item_no-1 ? '+' : ACS_HLINE);
            wmove(dialog, box_y + list_height + 1, box_x + check_x + 8);
            waddch(dialog, scrolli+choice < item_no-1 ? ')' : ACS_HLINE);
            wmove(dialog, cur_y, cur_x);  /* Restore cursor position */
            wrefresh(dialog);
          }
          continue;    /* wait for another key press */
        }
        else
          i = choice + 1;
      }
      else if (key == ' ') {    /* Toggle item status */
        status[scrolli+choice] = !status[scrolli+choice];
        getyx(dialog, cur_y, cur_x);    /* Save cursor position */
        wmove(list, choice, check_x);
        wattrset(list, check_selected_attr);
        wprintw(list, "[%c]", status[scrolli+choice] ? 'X' : ' ');
        wnoutrefresh(list);
        wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */
        wrefresh(dialog);
        continue;    /* wait for another key press */
      }

      if (i != choice) {
        /* De-highlight current item */
        getyx(dialog, cur_y, cur_x);    /* Save cursor position */
        print_item(list, items[(scrolli+choice)*3], items[(scrolli+choice)*3 + 1], status[scrolli+choice], choice, FALSE);

        /* Highlight new item */
        choice = i;
        print_item(list, items[(scrolli+choice)*3], items[(scrolli+choice)*3 + 1], status[scrolli+choice], choice, TRUE);
        wnoutrefresh(list);
        wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */
        wrefresh(dialog);
      }
      continue;    /* wait for another key press */
    }

    switch (key) {
      case 'O':
      case 'o':
        delwin(dialog);
        for (i = 0; i < item_no; i++)
	    if (status[i]) {
		if (separate_output) {
		    fprintf(stderr, "%s\n", items[i*3]);
		} else {
		    fprintf(stderr, "\"%s\" ", items[i*3]);
		}
	    }
        free(status);
        return 0;
      case 'C':
      case 'c':
        delwin(dialog);
        free(status);
        return 1;
      case TAB:
      case KEY_LEFT:
      case KEY_RIGHT:
        if (!button) {
          button = 1;    /* Indicates "Cancel" button is selected */
          print_button(dialog, "  OK  ", y, x, FALSE);
          print_button(dialog, "Cancel", y, x+14, TRUE);
        }
        else {
          button = 0;    /* Indicates "OK" button is selected */
          print_button(dialog, "Cancel", y, x+14, FALSE);
          print_button(dialog, "  OK  ", y, x, TRUE);
        }
        wrefresh(dialog);
        break;
      case ' ':
      case '\n':
        delwin(dialog);
        if (!button)
          for (i = 0; i < item_no; i++)
	      if (status[i]) {
		  if (separate_output) {
		      fprintf(stderr, "%s\n", items[i*3]);
		  } else {
		      fprintf(stderr, "\"%s\" ", items[i*3]);
		  }
	      }
        free(status);
        return button;
      case ESC:
        break;
    }
  }

  delwin(dialog);
  free(status);
  return -1;    /* ESC pressed */
}
Beispiel #7
0
/* Ask a question on the statusbar.  The prompt will be stored in the
 * static prompt, which should be NULL initially, and the answer will be
 * stored in the answer global.  Returns -1 on aborted enter, -2 on a
 * blank string, and 0 otherwise, the valid shortcut key caught.
 * curranswer is any editable text that we want to put up by default,
 * and refresh_func is the function we want to call to refresh the edit
 * window.
 *
 * The allow_tabs parameter indicates whether we should allow tabs to be
 * interpreted.  The allow_files parameter indicates whether we should
 * allow all files (as opposed to just directories) to be tab
 * completed. */
int do_prompt(bool allow_tabs,
#ifndef DISABLE_TABCOMP
	bool allow_files,
#endif
	int menu, const char *curranswer,
	bool *meta_key, bool *func_key,
#ifndef NANO_TINY
	filestruct **history_list,
#endif
	void (*refresh_func)(void), const char *msg, ...)
{
    va_list ap;
    int retval;
    const sc *s;
#ifndef DISABLE_TABCOMP
    bool list = FALSE;
#endif

    /* prompt has been freed and set to NULL unless the user resized
     * while at the statusbar prompt. */
    if (prompt != NULL)
	free(prompt);

    prompt = charalloc(((COLS - 4) * mb_cur_max()) + 1);

    bottombars(menu);

    va_start(ap, msg);
    vsnprintf(prompt, (COLS - 4) * mb_cur_max(), msg, ap);
    va_end(ap);
    null_at(&prompt, actual_x(prompt, COLS - 4));

    s = get_prompt_string(&retval, allow_tabs,
#ifndef DISABLE_TABCOMP
	allow_files,
#endif
	curranswer,
	meta_key, func_key,
#ifndef NANO_TINY
	history_list,
#endif
	refresh_func, menu
#ifndef DISABLE_TABCOMP
	, &list
#endif
	);

    free(prompt);
    prompt = NULL;

    /* We're done with the prompt, so save the statusbar cursor
     * position. */
    old_statusbar_x = statusbar_x;
    old_pww = statusbar_pww;

    /* If we left the prompt via Cancel or Enter, set the return value
     * properly. */
    if (s && s->scfunc ==  do_cancel)
	retval = -1;
    else if (s && s->scfunc == do_enter_void)
	retval = (*answer == '\0') ? -2 : 0;

    blank_statusbar();
    wnoutrefresh(bottomwin);

#ifdef DEBUG
    fprintf(stderr, "answer = \"%s\"\n", answer);
#endif

#ifndef DISABLE_TABCOMP
    /* If we've done tab completion, there might be a list of filename
     * matches on the edit window at this point.  Make sure that they're
     * cleared off. */
    if (list)
	refresh_func();
#endif

    return retval;
}
Beispiel #8
0
int main(int argc, char **argv)
{
	struct timeval tv;
#ifndef RETURN_TV_IN_SELECT
  	struct timeval before;
  	struct timeval after;
#endif
	fd_set rfds;
	int retval;
#ifdef HAVE_LIBKVM
	if (kvm_init()) can_use_kvm = 1;
#endif
	
#ifdef DEBUG
	if (!(debug_file = fopen("debug", "w"))){
		printf("file debug open error\n");
		exit(0);
	}
#endif
	get_boot_time();
	get_rows_cols(&screen_rows, &screen_cols);
	buf_size = screen_cols + screen_cols/2;
	line_buf = malloc(buf_size);
	if (!line_buf)
		errx(1, "Cannot allocate memory for buffer.");

	curses_init();
	current = &users_list;
	users_init();
        procwin_init();
	subwin_init();
	menu_init();
	signal(SIGINT, int_handler);
	signal(SIGWINCH, winch_handler);  
//	signal(SIGSEGV, segv_handler);

	print_help();
	update_load();
	current->redraw();
	wnoutrefresh(main_win);
	wnoutrefresh(info_win.wd);
	wnoutrefresh(help_win.wd);
	doupdate();
		
	tv.tv_sec = TIMEOUT;
	tv.tv_usec = 0;
	for(;;) {				/* main loop */
		int key;
		FD_ZERO(&rfds);
		FD_SET(0,&rfds);
#ifdef RETURN_TV_IN_SELECT
		retval = select(1, &rfds, 0, 0, &tv);
		if(retval > 0) {
			key = getkey();
			if(key == KBD_MORE) {
				usleep(10000);
				key = getkey();
			}
			key_action(key);
		}
		if (!tv.tv_sec && !tv.tv_usec){
			ticks++;
			periodic();
			tv.tv_sec = TIMEOUT;
		}
#else
		gettimeofday(&before, 0);
		retval = select(1, &rfds, 0, 0, &tv);
		gettimeofday(&after, 0);
		tv.tv_sec -= (after.tv_sec - before.tv_sec);
		if(retval > 0) {
			int key = read_key();
			key_action(key);
		}
		if(tv.tv_sec <= 0) {
			ticks++;
			periodic();
			tv.tv_sec = TIMEOUT;

		}
#endif
		if(size_changed) resize();

	}
}
Beispiel #9
0
Datei: smap.c Projekt: VURM/slurm
static void *_resize_handler(int sig)
{
	int startx = 0, starty = 0;
	int height = 40, width = 100;
	int check_width = min_screen_width;
	main_ycord = 1;

	/* clear existing data and update to avoid ghost during resize */
	clear_window(text_win);
	clear_window(grid_win);
	doupdate();
	delwin(grid_win);
	delwin(text_win);

	endwin();
	COLS = 0;
	LINES = 0;
	initscr();
	doupdate();	/* update now to make sure we get the new size */
	getmaxyx(stdscr, LINES, COLS);

	if (params.cluster_dims == 4) {
		height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
		width = (dim_size[1] + dim_size[3] + 1) * dim_size[0];
		check_width += width;
	} else if (params.cluster_dims == 3) {
		height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
		width = dim_size[0] + dim_size[2] + 3;
		check_width += width;
	} else {
		height = 10;
		width = COLS;
	}

	if (COLS < check_width || LINES < height) {
		endwin();
		error("Screen is too small make sure "
		      "the screen is at least %dx%d\n"
		      "Right now it is %dx%d\n", width, height, COLS, LINES);
		_smap_exit(0);	/* Calls exit(), no return */
	}

	grid_win = newwin(height, width, starty, startx);
	max_display = grid_win->_maxy * grid_win->_maxx;

	if (params.cluster_dims == 4) {
		startx = width;
		COLS -= 2;
		width = COLS - width;
		height = LINES;
	} else if (params.cluster_dims == 3) {
		startx = width;
		COLS -= 2;
		width = COLS - width;
		height = LINES;
	} else {
		startx = 0;
		starty = height;
		height = LINES - height;
	}

	text_win = newwin(height, width, starty, startx);

	print_date();
	switch (params.display) {
	case JOBS:
		get_job();
		break;
	case RESERVATIONS:
		get_reservation();
		break;
	case SLURMPART:
		get_slurm_part();
		break;
	case COMMANDS:
		if (params.cluster_flags & CLUSTER_FLAG_BG)
			get_command();
		break;
	case BGPART:
		if (params.cluster_flags & CLUSTER_FLAG_BG)
			get_bg_part();
		break;
	}

	print_grid();
	box(text_win, 0, 0);
	box(grid_win, 0, 0);
	wnoutrefresh(text_win);
	wnoutrefresh(grid_win);
	doupdate();
	resize_screen = 1;
	return NULL;
}
Beispiel #10
0
void display_calibration()
{
  char line[COLS];
  s_mouse_cal* mcal = cal_get_mouse(current_mouse, current_conf);

  if(current_cal == NONE)
  {
    mvaddstr(CAL_Y_P, CAL_X_P + 1, _("Mouse calibration (Ctrl+F1 to edit)"));
  }
  else
  {
    mvaddstr(CAL_Y_P, CAL_X_P + 1, _("Mouse calibration (Ctrl+F1 to save)(mouse wheel to change values)"));
  }
  clrtoeol();
  wmove(wcal, 1, 1);
  if(GE_GetMKMode() == GE_MK_MODE_MULTIPLE_INPUTS)
  {
    waddstr(wcal, "Mouse:");
    if(current_cal == MC)
    {
      wattron(wcal, COLOR_PAIR(4));
    }
    snprintf(line, COLS, " %s (%d) (F1) ", GE_MouseName(current_mouse), GE_MouseVirtualId(current_mouse));
    waddstr(wcal, line);
    if(current_cal == MC)
    {
      wattron(wcal, COLOR_PAIR(1));
    }
  }
  waddstr(wcal, _("Profile:"));
  if(current_cal == CC)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  snprintf(line, COLS, " %d (F2)", current_conf + 1);
  waddstr(wcal, line);
  if(current_cal == CC)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  wclrtoeol(wcal);
  mvwaddstr(wcal, 2, 1, _("Dead zone:"));
  if(current_cal == DZX)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, " x=");
  if(mcal->dzx)
  {
    snprintf(line, COLS, "%d", *mcal->dzx);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _("N/A"));
  }
  waddstr(wcal, " (F3)");
  if(current_cal == DZX)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  if(current_cal == DZY)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, " y=");
  if(mcal->dzy)
  {
    snprintf(line, COLS, "%d", *mcal->dzy);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _("N/A"));
  }
  waddstr(wcal, " (F4)");
  if(current_cal == DZY)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  if(current_cal == DZS)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, _(" shape="));
  if(mcal->dzs)
  {
    if (*mcal->dzs == E_SHAPE_CIRCLE)
    {
      waddstr(wcal, _("circle"));
    }
    else
    {
      waddstr(wcal, _("rectangle"));
    }
  }
  else
  {
    waddstr(wcal, _(" N/A"));
  }
  waddstr(wcal, " (F5)");
  if(current_cal == DZS)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  wclrtoeol(wcal);
  mvwaddstr(wcal, 3, 1, _("Acceleration:"));
  if(current_cal == TEST)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, _(" test (F6)"));
  if(current_cal == TEST)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  if(current_cal == EX)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, " x=");
  if(mcal->ex)
  {
    snprintf(line, COLS, "%.2f", *mcal->ex);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _("N/A"));
  }
  waddstr(wcal, " (F7)");
  if(current_cal == EX)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  if(current_cal == EY)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, " y=");
  if(mcal->ey)
  {
    snprintf(line, COLS, "%.2f", *mcal->ey);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _("N/A"));
  }
  waddstr(wcal, " (F8)");
  if(current_cal == EY)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  wclrtoeol(wcal);
  mvwaddstr(wcal, 4, 1, _("Sensitivity:"));
  if(current_cal == MX)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  if(mcal->mx)
  {
    snprintf(line, COLS, " %.2f", *mcal->mx);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _(" N/A"));
  }
  waddstr(wcal, " (F9)");
  if(current_cal == MX)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  wclrtoeol(wcal);
  mvwaddstr(wcal, 5, 1, "X/Y:");
  if(current_cal == RD || current_cal == VEL)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, _(" circle test"));
  if(current_cal == RD || current_cal == VEL)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  waddstr(wcal, ", ");
  if(current_cal == RD)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  snprintf(line, COLS, _("radius=%d (F10)"), mcal->rd);
  waddstr(wcal, line);
  if(current_cal == RD)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  waddstr(wcal, ", ");
  if(current_cal == VEL)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  snprintf(line, COLS, _("velocity=%d (F11)"), mcal->vel);
  waddstr(wcal, line);
  if(current_cal == VEL)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  if(current_cal == MY)
  {
    wattron(wcal, COLOR_PAIR(4));
  }
  waddstr(wcal, _(" ratio="));
  if(mcal->mx && mcal->my)
  {
    snprintf(line, COLS, "%.2f", *mcal->my / *mcal->mx);
    waddstr(wcal, line);
  }
  else
  {
    waddstr(wcal, _("N/A"));
  }
  waddstr(wcal, " (F12)");
  if(current_cal == MY)
  {
    wattron(wcal, COLOR_PAIR(1));
  }
  wclrtoeol(wcal);
  box(wcal, 0 , 0);
  wnoutrefresh(wcal);
  doupdate();
}
Beispiel #11
0
/*
 * Display a menu for choosing among a number of options
 */
int
dialog_menu (const char *title, const char *prompt, int height, int width,
		int menu_height, const char *current, int item_no,
		const char * const * items)

{
    int i, j, x, y, box_x, box_y;
    int key = 0, button = 0, scroll = 0, choice = 0, first_item = 0, max_choice;
    WINDOW *dialog, *menu;
    FILE *f;

    max_choice = MIN (menu_height, item_no);

    /* 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);

    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, ' ');
    }

    wattrset (dialog, dialog_attr);
    print_autowrap (dialog, prompt, width - 2, 1, 3);

    menu_width = width - 6;
    box_y = height - menu_height - 5;
    box_x = (width - menu_width) / 2 - 1;

    /* create new window for the menu */
    menu = subwin (dialog, menu_height, menu_width,
		y + box_y + 1, x + box_x + 1);
    keypad (menu, TRUE);

    /* draw a box around the menu items */
    draw_box (dialog, box_y, box_x, menu_height + 2, menu_width + 2,
	      menubox_border_attr, menubox_attr);

    /*
     * Find length of longest item in order to center menu.
     * Set 'choice' to default item. 
     */
    item_x = 0;
    for (i = 0; i < item_no; i++) {
	item_x = MAX (item_x, MIN(menu_width, strlen (items[i * 2 + 1]) + 2));
	if (strcmp(current, items[i*2]) == 0) choice = i;
    }

    item_x = (menu_width - item_x) / 2;

    /* get the scroll info from the temp file */
    if ( (f=fopen("lxdialog.scrltmp","r")) != NULL ) {
	if ( (fscanf(f,"%d\n",&scroll) == 1) && (scroll <= choice) &&
	     (scroll+max_choice > choice) && (scroll >= 0) &&
	     (scroll+max_choice <= item_no) ) {
	    first_item = scroll;
	    choice = choice - scroll;
	    fclose(f);
	} else {
	    scroll=0;
	    remove("lxdialog.scrltmp");
	    fclose(f);
	    f=NULL;
	}
    }
    if ( (choice >= max_choice) || (f==NULL && choice >= max_choice/2) ) {
	if (choice >= item_no-max_choice/2)
	    scroll = first_item = item_no-max_choice;
	else
	    scroll = first_item = choice - max_choice/2;
	choice = choice - scroll;
    }

    /* Print the menu */
    for (i=0; i < max_choice; i++) {
	print_item (menu, items[(first_item + i) * 2 + 1], i, i == choice,
                    (items[(first_item + i)*2][0] != ':'));
    }

    wnoutrefresh (menu);

    print_arrows(dialog, item_no, scroll,
		 box_y, box_x+item_x+1, menu_height);

    print_buttons (dialog, height, width, 0);

    while (key != ESC) {
	key = wgetch(dialog);

	if (key < 256 && isalpha(key)) key = tolower(key);

	if (strchr("ynm", key))
		i = max_choice;
	else {
        for (i = choice+1; i < max_choice; i++) {
		j = first_alpha(items[(scroll+i)*2+1], "YyNnMm");
		if (key == tolower(items[(scroll+i)*2+1][j]))
                	break;
	}
	if (i == max_choice)
       		for (i = 0; i < max_choice; i++) {
			j = first_alpha(items[(scroll+i)*2+1], "YyNnMm");
			if (key == tolower(items[(scroll+i)*2+1][j]))
                		break;
		}
	}

	if (i < max_choice || 
            key == KEY_UP || key == KEY_DOWN ||
            key == '-' || key == '+' ||
            key == KEY_PPAGE || key == KEY_NPAGE) {

            print_item (menu, items[(scroll+choice)*2+1], choice, FALSE,
                       (items[(scroll+choice)*2][0] != ':'));

	    if (key == KEY_UP || key == '-') {
                if (choice < 2 && scroll) {
	            /* Scroll menu down */
                    scrollok (menu, TRUE);
                    wscrl (menu, -1);
                    scrollok (menu, FALSE);

                    scroll--;

                    print_item (menu, items[scroll * 2 + 1], 0, FALSE,
                               (items[scroll*2][0] != ':'));
		} else
		    choice = MAX(choice - 1, 0);

	    } else if (key == KEY_DOWN || key == '+')  {

		print_item (menu, items[(scroll+choice)*2+1], choice, FALSE,
                                (items[(scroll+choice)*2][0] != ':'));

                if ((choice > max_choice-3) &&
                    (scroll + max_choice < item_no)
                   ) {
		    /* Scroll menu up */
		    scrollok (menu, TRUE);
                    scroll (menu);
                    scrollok (menu, FALSE);

                    scroll++;

                    print_item (menu, items[(scroll+max_choice-1)*2+1],
                               max_choice-1, FALSE,
                               (items[(scroll+max_choice-1)*2][0] != ':'));
                } else
                    choice = MIN(choice+1, max_choice-1);

	    } else if (key == KEY_PPAGE) {
	        scrollok (menu, TRUE);
                for (i=0; (i < max_choice); i++) {
                    if (scroll > 0) {
                	wscrl (menu, -1);
                	scroll--;
                	print_item (menu, items[scroll * 2 + 1], 0, FALSE,
                	(items[scroll*2][0] != ':'));
                    } else {
                        if (choice > 0)
                            choice--;
                    }
                }
                scrollok (menu, FALSE);

            } else if (key == KEY_NPAGE) {
                for (i=0; (i < max_choice); i++) {
                    if (scroll+max_choice < item_no) {
			scrollok (menu, TRUE);
			scroll(menu);
			scrollok (menu, FALSE);
                	scroll++;
                	print_item (menu, items[(scroll+max_choice-1)*2+1],
			            max_choice-1, FALSE,
			            (items[(scroll+max_choice-1)*2][0] != ':'));
		    } else {
			if (choice+1 < max_choice)
			    choice++;
		    }
                }

            } else
                choice = i;

            print_item (menu, items[(scroll+choice)*2+1], choice, TRUE,
                       (items[(scroll+choice)*2][0] != ':'));

            print_arrows(dialog, item_no, scroll,
                         box_y, box_x+item_x+1, menu_height);

            wnoutrefresh (menu);
            wrefresh (dialog);

	    continue;		/* wait for another key press */
        }

	switch (key) {
	case KEY_LEFT:
	case TAB:
	case KEY_RIGHT:
	    button = ((key == KEY_LEFT ? --button : ++button) < 0)
			? 2 : (button > 2 ? 0 : button);

	    print_buttons(dialog, height, width, button);
	    wrefresh (dialog);
	    break;
	case ' ':
	case 's':
	case 'y':
	case 'n':
	case 'm':
	    /* save scroll info */
	    if ( (f=fopen("lxdialog.scrltmp","w")) != NULL ) {
		fprintf(f,"%d\n",scroll);
		fclose(f);
	    }
	    delwin (dialog);
            fprintf(stderr, "%s\n", items[(scroll + choice) * 2]);
            switch (key) {
            case 's': return 3;
            case 'y': return 3;
            case 'n': return 4;
            case 'm': return 5;
            case ' ': return 6;
            }
	    return 0;
	case 'h':
	case '?':
	    button = 2;
	case '\n':
	    delwin (dialog);
	    if (button == 2) 
            	fprintf(stderr, "%s \"%s\"\n", 
			items[(scroll + choice) * 2],
			items[(scroll + choice) * 2 + 1] +
			first_alpha(items[(scroll + choice) * 2 + 1],""));
	    else
            	fprintf(stderr, "%s\n", items[(scroll + choice) * 2]);

	    remove("lxdialog.scrltmp");
	    return button;
	case 'e':
	case 'x':
	    key = ESC;
	case ESC:
	    break;
	}
    }

    delwin (dialog);
    remove("lxdialog.scrltmp");
    return -1;			/* ESC pressed */
}
Beispiel #12
0
void display_run(e_controller_type type, int axis[])
{
  int i;
  int d;
  char label[BUTTON_LENGTH];
  char rate[COLS];

  int freq = stats_get_frequency(0);

  if(freq >= 0)
  {
    sprintf(rate, _("Refresh rate: %4dHz  "), freq);
    mvaddstr(LINES-1, 1, rate);
  }

  d = 0;

  for(i=rel_axis_rstick_y+1; i<AXIS_MAX; ++i)
  {
    if(axis[i])
    {
      snprintf(label, sizeof(label), "%8s: %4d", controller_get_axis_name(type, i), axis[i]);
      mvwaddstr(wbuttons, 1 + d, 1, label);
      d++;
      if(d == BUTTON_Y_L - 3)
      {
        break;
      }
    }
  }
  memset(label, ' ', sizeof(label));
  label[sizeof(label)-1] = '\0';
  for(i=d; i<last_button_nb; ++i)
  {
    mvwaddstr(wbuttons, 1 + i, 1, label);
  }
  last_button_nb = d;
  wnoutrefresh(wbuttons);

  mvwaddch(lstick, cross[0][1], cross[0][0], ' ');
  cross[0][0] = STICK_X_L / 2 + (double)axis[rel_axis_lstick_x] / controller_get_max_signed(adapter_get(0)->ctype, rel_axis_lstick_x) * (STICK_X_L / 2 - 1);
  cross[0][1] = STICK_Y_L / 2 + (double)axis[rel_axis_lstick_y] / controller_get_max_signed(adapter_get(0)->ctype, rel_axis_lstick_y) * (STICK_Y_L / 2 - 1);
  if(cross[0][0] <= 0 || cross[0][0] >= STICK_X_L-1 || cross[0][1] <= 0 || cross[0][1] >= STICK_Y_L-1)
  {
    mvwaddch(lstick, cross[0][1], cross[0][0], CROSS_CHAR | COLOR_PAIR(3));
  }
  else
  {
    mvwaddch(lstick, cross[0][1], cross[0][0], CROSS_CHAR);
  }
  wnoutrefresh(lstick);

  mvwaddch(rstick, cross[1][1], cross[1][0], ' ');
  cross[1][0] = STICK_X_L / 2 + (double)axis[rel_axis_rstick_x] / controller_get_max_signed(adapter_get(0)->ctype, rel_axis_rstick_x) * (STICK_X_L / 2 - 1);
  cross[1][1] = STICK_Y_L / 2 + (double)axis[rel_axis_rstick_y] / controller_get_max_signed(adapter_get(0)->ctype, rel_axis_rstick_y) * (STICK_Y_L / 2 - 1);
  if(cross[1][0] <= 0 || cross[1][0] >= STICK_X_L-1 || cross[1][1] <= 0 || cross[1][1] >= STICK_Y_L-1)
  {
    mvwaddch(rstick, cross[1][1], cross[1][0], CROSS_CHAR | COLOR_PAIR(3));
  }
  else
  {
    mvwaddch(rstick, cross[1][1], cross[1][0], CROSS_CHAR);
  }
  wnoutrefresh(rstick);

  move(LINES-1, COLS-1);
  wnoutrefresh(stdscr);
  doupdate();
}
/*
25x80

                                                             <--LEGEND_WIDTH=20->
+--------------------------------------------------------------------------------+
|                   LBA:       xxx,xxx / xxx,xxx,xxx         ETA           xx:xx |
|ZZZZZZZZZZZZZZZxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx SPEED    xxxxx kb/s |
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     |
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x unread space      |^
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x copied space,     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   no read errors    ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x read errors       ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   occured           || LEGEND_HEIGHT=9
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Display block is XXX||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx XXX blocks by 256 se||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ctors               |v
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x NNNNNNNNNN        |^
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x NNNNNNNNNN        || W_STATS_HEIGHT=3
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x NNNNNNNNNN        |v
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     |
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Device copying /dev/|^
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx XXX                 ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Ctrl+C to abort     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     || SUMMARY
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                     ||
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                               |v
| WHDD rev. X.X-X-gXXXXXXX                                                       |
+--------------------------------------------------------------------------------+
*/
static int Open(DC_RendererCtx *ctx) {
    WholeSpace *priv = ctx->priv;
    DC_ProcedureCtx *actctx = ctx->procedure_ctx;

    // TODO Raise error message
    if (LINES < 25 || COLS < 80)
        return -1;

    priv->nb_blocks = actctx->dev->capacity / actctx->blk_size;
    if (actctx->dev->capacity % actctx->blk_size)
        priv->nb_blocks++;
    priv->unread_count = actctx->progress.den;
    priv->sectors_per_block = actctx->blk_size / 512;
    priv->blocks_map = calloc(priv->nb_blocks, sizeof(uint8_t));
    assert(priv->blocks_map);
    int journal_fd = ((CopyPriv*)actctx->priv)->journal_fd;
    lseek(journal_fd, 0, SEEK_SET);
    if (((CopyPriv*)actctx->priv)->use_journal) {
        priv->unread_count = 0;
        uint8_t journal_chunk[1*1024*1024];
        int64_t chunklen;
        int64_t end_lba = ((CopyPriv*)actctx->priv)->end_lba;
        for (int64_t i = 0; i < priv->nb_blocks; i++) {
            int64_t lba = i * priv->sectors_per_block;
            if (lba % sizeof(journal_chunk) == 0) {
                chunklen = (end_lba - lba) < (int64_t)sizeof(journal_chunk) ? (end_lba - lba) : (int64_t)sizeof(journal_chunk);
                int ret = read(journal_fd, journal_chunk, chunklen);
                if (ret != chunklen)
                    return 1;
            }
            char sector_status = journal_chunk[lba % sizeof(journal_chunk)];
            priv->blocks_map[i] = sector_status;
            int sectors_in_block = priv->sectors_per_block;
            if (i == priv->nb_blocks - 1)  // Last block may be smaller
                sectors_in_block = (actctx->dev->capacity % actctx->blk_size) / 512;
            switch ((enum SectorStatus)sector_status) {
                case SectorStatus_eUnread:
                    priv->unread_count += sectors_in_block;
                    break;
                case SectorStatus_eReadOk:
                    priv->read_ok_count += sectors_in_block;
                    break;
                case SectorStatus_eBlockReadError:
                case SectorStatus_eSectorReadError:
                    priv->errors_count += sectors_in_block;
                    break;
            }
        }
    }

#define LBA_WIDTH 20
#define LEGEND_WIDTH 20
#define LEGEND_HEIGHT 9
#define LEGEND_VERT_OFFSET 3 /* ETA & SPEED are above, 1 for spacing */

    priv->w_cur_lba = derwin(stdscr, 1, LBA_WIDTH, 0 /* at the top */, COLS - LEGEND_WIDTH - 1 - (LBA_WIDTH * 2) );
    assert(priv->w_cur_lba);
    wbkgd(priv->w_cur_lba, COLOR_PAIR(MY_COLOR_GRAY));

    priv->w_end_lba = derwin(stdscr, 1, LBA_WIDTH, 0 /* at the top */, COLS - LEGEND_WIDTH - 1 - LBA_WIDTH);
    assert(priv->w_end_lba);
    wbkgd(priv->w_end_lba, COLOR_PAIR(MY_COLOR_GRAY));

    priv->eta = derwin(stdscr, 1, LEGEND_WIDTH, 0 /* at the top */, COLS-LEGEND_WIDTH);
    assert(priv->eta);
    wbkgd(priv->eta, COLOR_PAIR(MY_COLOR_GRAY));

    priv->avg_speed = derwin(stdscr, 1, LEGEND_WIDTH, 1 /* ETA is above */, COLS-LEGEND_WIDTH);
    assert(priv->avg_speed);
    wbkgd(priv->avg_speed, COLOR_PAIR(MY_COLOR_GRAY));

    priv->legend = derwin(stdscr, LEGEND_HEIGHT, LEGEND_WIDTH, LEGEND_VERT_OFFSET, COLS-LEGEND_WIDTH);
    assert(priv->legend);
    wbkgd(priv->legend, COLOR_PAIR(MY_COLOR_GRAY));

#define W_STATS_HEIGHT 3
#define W_STATS_VERT_OFFSET ( LEGEND_VERT_OFFSET + LEGEND_HEIGHT + 1 /* spacing */ )
    priv->w_stats = derwin(stdscr, W_STATS_HEIGHT, LEGEND_WIDTH, W_STATS_VERT_OFFSET, COLS-LEGEND_WIDTH);
    assert(priv->w_stats);

#define SUMMARY_VERT_OFFSET ( W_STATS_VERT_OFFSET + W_STATS_HEIGHT + 1 /* spacing */ )
#define SUMMARY_HEIGHT ( LINES - SUMMARY_VERT_OFFSET - 1 /* don't touch bottom line */ )
    priv->summary = derwin(stdscr, SUMMARY_HEIGHT, LEGEND_WIDTH, SUMMARY_VERT_OFFSET, COLS-LEGEND_WIDTH);
    assert(priv->summary);
    wbkgd(priv->summary, COLOR_PAIR(MY_COLOR_GRAY));

    priv->vis_height = LINES - 2; /* LBA is above, version is below */
    priv->vis_width = COLS - LEGEND_WIDTH - 1;
    int vis_cells_avail = priv->vis_height * priv->vis_width;
    priv->blocks_per_vis = priv->nb_blocks / vis_cells_avail;
    if (priv->nb_blocks % vis_cells_avail)
        priv->blocks_per_vis++;
    priv->vis = derwin(stdscr, priv->vis_height, priv->vis_width, 1 /* LBA is above */, 0);
    assert(priv->vis);
    wrefresh(priv->vis);

    whole_space_show_legend(priv);

    priv->reports[0].seqno = 1; // anything but zero

    char comma_lba_buf[30], *comma_lba_p;
    comma_lba_p = commaprint(actctx->dev->capacity / 512, comma_lba_buf, sizeof(comma_lba_buf));
    wprintw(priv->w_end_lba, "/ %s", comma_lba_p);
    wnoutrefresh(priv->w_end_lba);
    wprintw(priv->summary,
            "%s %s\n"
            "Ctrl+C to abort\n",
            actctx->procedure->display_name, actctx->dev->dev_path);
    wrefresh(priv->summary);
    int r = pthread_create(&priv->render_thread, NULL, render_thread_proc, priv);
    if (r)
        return r; // FIXME leak
    return 0;
}
Beispiel #14
0
// inits and draws the actual game screen
void init_ui()
{

	/* initialization of windows */
	/* naming reference:
	   mainbw = outer area, "box"
	   gamebw  = main game "box"
	   gamew = main game area
	   commandw = command listing window
	   skillsw = skills listing window
   */
	background_win = newwin(y_size, x_size, 0, 0);
	draw_background(x_size, y_size);
	wnoutrefresh(background_win);

	// calculate widths
	int remaining_width = x_size;
	remaining_width -= 2; // outer borders
	int cmdw_width = 17;
	remaining_width -= cmdw_width;
	remaining_width -= 2; // margins for cmdw
	remaining_width -= 1; // vertical line between cmdw and gamew
	int skillsw_width = cmdw_width;
	skillsw_width -= 2; // margin for index numbers
	int gamew_width = remaining_width / 2;
	remaining_width -= gamew_width;
	remaining_width -= 1; // vertical line between gamew and logw
	int logw_width = remaining_width;
	int inputw_width = logw_width;
	inputw_width -= 2; // margin for prompt

	// calculate heights
	int skillsw_height = 5;
	int cmdw_height = y_size;
	cmdw_height -= 2; // outer borders
	cmdw_height -= 1; // horiz line between cmdw and skillsw
	cmdw_height -= 1; // one line margin at top
	cmdw_height -= skillsw_height;
	int inputw_height = 1;
	int logw_height = y_size;
	logw_height -= 2; // outer borders
	logw_height -= 1; // horiz line between logw and inputw
	logw_height -= inputw_height;
	int gamew_height = y_size;
	gamew_height -= 2; // outer borders

	command_win = newwin(cmdw_height, cmdw_width, 2, 2);
	skills_win = newwin(skillsw_height, skillsw_width, y_size-(skillsw_height+1), 4);
	game_win = newwin(gamew_height, gamew_width, 1, cmdw_width+4);
	log_win = newwin(logw_height, logw_width, 1, (x_size-logw_width)-1);
	input_win = newwin(inputw_height, inputw_width, y_size-2, (x_size-inputw_width)-1);

	fight_statw_width = (gamew_width/2)-1; // lets leave few characters in the middle

	for (int i = 0; i < 3; i++)
	{
		fight_stat_win[i] = newwin(7, fight_statw_width, 1+(i*7), cmdw_width+4);
		fight_stat_win[i+3] = newwin(7, fight_statw_width, y_size - (1+((i+1)*7)), x_size-(logw_width+fight_statw_width+2));
		/* debugging: Show windows 
		wbkgd(fight_stat_win[i], '0' + i);
		wbkgd(fight_stat_win[i+3], '3' + i);
		box(fight_stat_win[i], 0, 0);
		box(fight_stat_win[i+3], 0, 0);
		wnoutrefresh(fight_stat_win[i]);
		wnoutrefresh(fight_stat_win[i+3]);
		*/
	}

	/* debugging: Show windows 
	wbkgd(command_win, 'C');
	wbkgd(skills_win, 'S');
	wbkgd(game_win, 'G');
	wbkgd(log_win, 'L');
	wbkgd(input_win, 'I');
	wnoutrefresh(command_win);
	wnoutrefresh(skills_win);
	wnoutrefresh(game_win);
	wnoutrefresh(log_win);
	wnoutrefresh(input_win);
	*/
	ncurs_skills(); /* for the lack of a better place updated here */
	doupdate();
}
Beispiel #15
0
/*
 * create the internal menu for the files 
 */
static void wdg_file_menu_create(struct wdg_object *wo)
{
   WDG_WO_EXT(struct wdg_file_handle, ww);
   int mrows, mcols;
   int i;
   size_t c = wdg_get_ncols(wo);
   size_t x = wdg_get_begin_x(wo);
   size_t y = wdg_get_begin_y(wo);
   struct stat buf;

   /* the menu is already posted */
   if (ww->nitems)
      return;
 
   WDG_DEBUG_MSG("wdg_file_menu_create");
   
   /* get the working directory */
   getcwd(ww->curpath, PATH_MAX);
         
   /* scan the directory */
   ww->nlist = scandir(".", &ww->namelist, 0, alphasort);

   /* on error display the message in the box */
   if (ww->nlist <= 0) {
      ww->nitems = 2;
      WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *));
      ww->items[ww->nitems - 2] = new_item("/", "root");
      ww->items[ww->nitems - 1] = new_item("Cannot open the directory", "");
      item_opts_off(ww->items[ww->nitems - 1], O_SELECTABLE);
   } else {

      /* for each directory in the directory */
      for (i = 0; i < ww->nlist; i++) {
        
         /* 
          * transform the current dir into the root.
          * useful to exit from a path whose parent is not readable 
          */
         if (!strcmp(ww->namelist[i]->d_name, ".")) {
            strncpy(ww->namelist[i]->d_name, "/", 1);
            ww->nitems++;
            WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *));
            ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, "root");
            continue;
         }
         
         /* get the file properties */
         stat(ww->namelist[i]->d_name, &buf);
         
         if (S_ISDIR(buf.st_mode)) {
            ww->nitems++;
            WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *));
            ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, "[...]");
         }
         // if not readable
         //item_opts_off(ww->items[ww->nitems - 1], O_SELECTABLE);
      }
      
      /* and now add the files */
      for (i = 0; i < ww->nlist; i++) {
         
         /* get the file properties */
         stat(ww->namelist[i]->d_name, &buf);
         
         if (!S_ISDIR(buf.st_mode)) {
            ww->nitems++;
            WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *));
            ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, "");
         }
      }
   }

   /* null terminate the array */
   WDG_SAFE_REALLOC(ww->items, (ww->nitems + 1) * sizeof(ITEM *));
   ww->items[ww->nitems] = NULL;
     
   /* create the menu */
   ww->m = new_menu(ww->items);

   /* set the dimensions */
   set_menu_format(ww->m, ww->y - 2, 1);
   set_menu_spacing(ww->m, 2, 0, 0);

   /* get the geometry to make a window */
   scale_menu(ww->m, &mrows, &mcols);

   /* 
    * if the menu is larger than the main window
    * adapt to the new dimensions
    */
   if (mcols > (int)c - 4) {
      ww->x = mcols + 4;
      wdg_file_redraw(wo);
      return;
   }
   /* create the window for the menu */
   ww->mwin = newwin(mrows, MAX(mcols, (int)c - 4), y + 1, x + 2);
   /* set the color */
   wbkgd(ww->mwin, COLOR_PAIR(wo->window_color));
   keypad(ww->mwin, TRUE);
  
   /* associate with the menu */
   set_menu_win(ww->m, ww->mwin);
   
   /* the subwin for the menu */
   set_menu_sub(ww->m, derwin(ww->mwin, mrows + 1, mcols, 1, 1));

   /* menu attributes */
   set_menu_mark(ww->m, "");
   set_menu_grey(ww->m, COLOR_PAIR(wo->window_color));
   set_menu_back(ww->m, COLOR_PAIR(wo->window_color));
   set_menu_fore(ww->m, COLOR_PAIR(wo->window_color) | A_REVERSE | A_BOLD);
   
   /* display the menu */
   post_menu(ww->m);

   wnoutrefresh(ww->mwin);
   
}
Beispiel #16
0
Datei: smap.c Projekt: VURM/slurm
int main(int argc, char *argv[])
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	node_info_msg_t *node_info_ptr = NULL;
	node_info_msg_t *new_node_ptr = NULL;
	int error_code;
	int height = 40;
	int width = 100;
	int startx = 0;
	int starty = 0;
	int end = 0;
	int i;
	int rc;
	int mapset = 0;

	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_DAEMON, NULL);
	parse_command_line(argc, argv);
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	if (params.cluster_dims == 4) {
		min_screen_width = 92;
	} else if (params.cluster_dims == 3)
		min_screen_width = 92;

	while (slurm_load_node((time_t) NULL, &new_node_ptr, SHOW_ALL)) {
		error_code = slurm_get_errno();
		printf("slurm_load_node: %s\n", slurm_strerror(error_code));
		if (params.display == COMMANDS) {
			new_node_ptr = NULL;
			break;		/* just continue */
		}
		if (params.iterate == 0)
			_smap_exit(1);	/* Calls exit(), no return */
		sleep(10);	/* keep trying to reconnect */
	}

	_init_colors();
	select_g_ba_init(new_node_ptr, 0);
	init_grid(new_node_ptr);

	if (params.resolve) {
#if defined HAVE_BG_FILES && defined HAVE_BG_L_P
#if 1
		error("this doesn't work in the current 2.3 code. FIXME");
#else
		if (!have_db2) {
			printf("Required libraries can not be found "
			       "to access the Bluegene system.\nPlease "
			       "set your LD_LIBRARY_PATH correctly to "
			       "point to them.\n");
			goto part_fini;
		}

		if (!mapset)
			mapset = 1;
		if (params.resolve[0] != 'R') {
			i = strlen(params.resolve);
			i -= 3;
			if (i < 0) {
				printf("No real block was entered\n");
				goto part_fini;
			}
			char *rack_mid = find_bp_rack_mid(params.resolve+i);
			if (rack_mid) {
				printf("X=%c Y=%c Z=%c resolves to %s\n",
				       params.resolve[0+i],
				       params.resolve[1+i],
				       params.resolve[2+i],
				       rack_mid);
			} else {
				printf("X=%c Y=%c Z=%c has no resolve\n",
				       params.resolve[0+i],
				       params.resolve[1+i],
				       params.resolve[2+i]);
			}
		} else {
			uint16_t *coord = find_bp_loc(params.resolve);
			if (coord) {
				printf("%s resolves to X=%d Y=%d Z=%d\n",
				       params.resolve,
				       coord[0], coord[1], coord[2]);
			} else {
				printf("%s has no resolve.\n",
				       params.resolve);
			}
		}
part_fini:
#endif
#else
		printf("Must be physically on a BlueGene system for support "
		       "of resolve option.\n");
#endif
		_smap_exit(0);	/* Calls exit(), no return */
	}
	if (!params.commandline) {
		int check_width = min_screen_width;
		signal(SIGWINCH, (void (*)(int))_resize_handler);
		initscr();

		if (params.cluster_dims == 4) {
			height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
			width = (dim_size[1] + dim_size[3] + 1) * dim_size[0]
				 + 2;
			check_width += width;
		} else if (params.cluster_dims == 3) {
			height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
			width = dim_size[0] + dim_size[2] + 3;
			check_width += width;
		} else {
			height = 10;
			width = COLS;
		}

	        if ((COLS < check_width) || (LINES < height)) {
			endwin();
			error("Screen is too small make sure the screen "
			      "is at least %dx%d\n"
			      "Right now it is %dx%d\n",
			      check_width,
			      height,
			      COLS,
			      LINES);
			_smap_exit(1);	/* Calls exit(), no return */
		}

		raw();
		keypad(stdscr, TRUE);
		noecho();
		cbreak();
		curs_set(0);
		nodelay(stdscr, TRUE);
		start_color();
		_set_pairs();

		grid_win = newwin(height, width, starty, startx);
		max_display = grid_win->_maxy * grid_win->_maxx;

		if (params.cluster_dims == 4) {
			startx = width;
			COLS -= 2;
			width = COLS - width;
			height = LINES;
		} else if (params.cluster_dims == 3) {
			startx = width;
			COLS -= 2;
			width = COLS - width;
			height = LINES;
		} else {
			startx = 0;
			starty = height;
			height = LINES - height;
		}

		text_win = newwin(height, width, starty, startx);
        }
	while (!end) {
		if (!params.commandline) {
			_get_option();
redraw:
			clear_window(text_win);
			clear_window(grid_win);
			move(0, 0);

			main_xcord = 1;
			main_ycord = 1;
		}

		if (!params.no_header)
			print_date();

		clear_grid();
		switch (params.display) {
		case JOBS:
			get_job();
			break;
		case RESERVATIONS:
			get_reservation();
			break;
		case SLURMPART:
			get_slurm_part();
			break;
		case COMMANDS:
			if (params.cluster_flags & CLUSTER_FLAG_BG) {
				if (!mapset) {
					mapset = 1;
					wclear(text_win);
				}
				get_command();
			} else {
				error("Must be on a BG SYSTEM to "
				      "run this command");
				if (!params.commandline)
					endwin();
				_smap_exit(1);	/* Calls exit(), no return */
			}
			break;
		case BGPART:
			if (params.cluster_flags & CLUSTER_FLAG_BG)
				get_bg_part();
			else {
				error("Must be on a BG SYSTEM to "
				      "run this command");
				if (!params.commandline)
					endwin();
				_smap_exit(1);	/* Calls exit(), no return */
			}
			break;
		}

		if (!params.commandline) {
			box(text_win, 0, 0);
			wnoutrefresh(text_win);

			print_grid();
			box(grid_win, 0, 0);
			wnoutrefresh(grid_win);

			doupdate();

			node_info_ptr = new_node_ptr;
			if (node_info_ptr) {
				error_code = slurm_load_node(
					node_info_ptr->last_update,
					&new_node_ptr, SHOW_ALL);
				if (error_code == SLURM_SUCCESS)
					slurm_free_node_info_msg(
						node_info_ptr);
				else if (slurm_get_errno()
					 == SLURM_NO_CHANGE_IN_DATA) {
					error_code = SLURM_SUCCESS;
					new_node_ptr = node_info_ptr;
				}
			} else {
				error_code = slurm_load_node(
					(time_t) NULL,
					&new_node_ptr, SHOW_ALL);
			}
			if (error_code && (quiet_flag != 1)) {
				if (!params.commandline) {
					mvwprintw(
						text_win,
						main_ycord,
						1,
						"slurm_load_node: %s",
						slurm_strerror(
							slurm_get_errno()));
					main_ycord++;
				} else {
					printf("slurm_load_node: %s",
					       slurm_strerror(
						       slurm_get_errno()));
				}
			}
		}

		if (params.iterate) {
			for (i = 0; i < params.iterate; i++) {
				sleep(1);
				if (!params.commandline) {
					if ((rc = _get_option()) == 1)
						goto redraw;
					else if (resize_screen) {
						resize_screen = 0;
						goto redraw;
					}
				}
			}
		} else
			break;

	}

	if (!params.commandline) {
		nodelay(stdscr, FALSE);
		getch();
		endwin();
	}

	_smap_exit(0);	/* Calls exit(), no return */
	exit(0);	/* Redundant, but eliminates compiler warning */
}
Beispiel #17
0
int dialog_menu(const char *title, const char *prompt,
                const void *selected, int *s_scroll)
{
	int i, j, x, y, box_x, box_y;
	int height, width, menu_height;
	int key = 0, button = 0, scroll = 0, choice = 0;
	int first_item =  0, max_choice;
	WINDOW *dialog, *menu;

do_resize:
	height = getmaxy(stdscr);
	width = getmaxx(stdscr);
	if (height < 15 || width < 65)
		return -ERRDISPLAYTOOSMALL;

	height -= 4;
	width  -= 5;
	menu_height = height - 10;

	max_choice = MIN(menu_height, item_count());

	
	x = (COLS - width) / 2;
	y = (LINES - height) / 2;

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

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

	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);

	wattrset(dialog, dlg.dialog.atr);
	print_autowrap(dialog, prompt, width - 2, 1, 3);

	menu_width = width - 6;
	box_y = height - menu_height - 5;
	box_x = (width - menu_width) / 2 - 1;

	
	menu = subwin(dialog, menu_height, menu_width,
		      y + box_y + 1, x + box_x + 1);
	keypad(menu, TRUE);

	
	draw_box(dialog, box_y, box_x, menu_height + 2, menu_width + 2,
		 dlg.menubox_border.atr, dlg.menubox.atr);

	if (menu_width >= 80)
		item_x = (menu_width - 70) / 2;
	else
		item_x = 4;

	
	item_foreach()
		if (selected && (selected == item_data()))
			choice = item_n();
	
	scroll = *s_scroll;
	if ((scroll <= choice) && (scroll + max_choice > choice) &&
	   (scroll >= 0) && (scroll + max_choice <= item_count())) {
		first_item = scroll;
		choice = choice - scroll;
	} else {
		scroll = 0;
	}
	if ((choice >= max_choice)) {
		if (choice >= item_count() - max_choice / 2)
			scroll = first_item = item_count() - max_choice;
		else
			scroll = first_item = choice - max_choice / 2;
		choice = choice - scroll;
	}

	
	for (i = 0; i < max_choice; i++) {
		print_item(first_item + i, i, i == choice);
	}

	wnoutrefresh(menu);

	print_arrows(dialog, item_count(), scroll,
		     box_y, box_x + item_x + 1, menu_height);

	print_buttons(dialog, height, width, 0);
	wmove(menu, choice, item_x + 1);
	wrefresh(menu);

	while (key != KEY_ESC) {
		key = wgetch(menu);

		if (key < 256 && isalpha(key))
			key = tolower(key);

		if (strchr("ynmh", key))
			i = max_choice;
		else {
			for (i = choice + 1; i < max_choice; i++) {
				item_set(scroll + i);
				j = first_alpha(item_str(), "YyNnMmHh");
				if (key == tolower(item_str()[j]))
					break;
			}
			if (i == max_choice)
				for (i = 0; i < max_choice; i++) {
					item_set(scroll + i);
					j = first_alpha(item_str(), "YyNnMmHh");
					if (key == tolower(item_str()[j]))
						break;
				}
		}

		if (i < max_choice ||
		    key == KEY_UP || key == KEY_DOWN ||
		    key == '-' || key == '+' ||
		    key == KEY_PPAGE || key == KEY_NPAGE) {
			
			print_item(scroll + choice, choice, FALSE);

			if (key == KEY_UP || key == '-') {
				if (choice < 2 && scroll) {
					
					do_scroll(menu, &scroll, -1);

					print_item(scroll, 0, FALSE);
				} else
					choice = MAX(choice - 1, 0);

			} else if (key == KEY_DOWN || key == '+') {
				print_item(scroll+choice, choice, FALSE);

				if ((choice > max_choice - 3) &&
				    (scroll + max_choice < item_count())) {
					
					do_scroll(menu, &scroll, 1);

					print_item(scroll+max_choice - 1,
						   max_choice - 1, FALSE);
				} else
					choice = MIN(choice + 1, max_choice - 1);

			} else if (key == KEY_PPAGE) {
				scrollok(menu, TRUE);
				for (i = 0; (i < max_choice); i++) {
					if (scroll > 0) {
						do_scroll(menu, &scroll, -1);
						print_item(scroll, 0, FALSE);
					} else {
						if (choice > 0)
							choice--;
					}
				}

			} else if (key == KEY_NPAGE) {
				for (i = 0; (i < max_choice); i++) {
					if (scroll + max_choice < item_count()) {
						do_scroll(menu, &scroll, 1);
						print_item(scroll+max_choice-1,
							   max_choice - 1, FALSE);
					} else {
						if (choice + 1 < max_choice)
							choice++;
					}
				}
			} else
				choice = i;

			print_item(scroll + choice, choice, TRUE);

			print_arrows(dialog, item_count(), scroll,
				     box_y, box_x + item_x + 1, menu_height);

			wnoutrefresh(dialog);
			wrefresh(menu);

			continue;	
		}

		switch (key) {
		case KEY_LEFT:
		case TAB:
		case KEY_RIGHT:
			button = ((key == KEY_LEFT ? --button : ++button) < 0)
			    ? 2 : (button > 2 ? 0 : button);

			print_buttons(dialog, height, width, button);
			wrefresh(menu);
			break;
		case ' ':
		case 's':
		case 'y':
		case 'n':
		case 'm':
		case '/':
			
			*s_scroll = scroll;
			delwin(menu);
			delwin(dialog);
			item_set(scroll + choice);
			item_set_selected(1);
			switch (key) {
			case 's':
				return 3;
			case 'y':
				return 3;
			case 'n':
				return 4;
			case 'm':
				return 5;
			case ' ':
				return 6;
			case '/':
				return 7;
			}
			return 0;
		case 'h':
		case '?':
			button = 2;
		case '\n':
			*s_scroll = scroll;
			delwin(menu);
			delwin(dialog);
			item_set(scroll + choice);
			item_set_selected(1);
			return button;
		case 'e':
		case 'x':
			key = KEY_ESC;
			break;
		case KEY_ESC:
			key = on_key_esc(menu);
			break;
		case KEY_RESIZE:
			on_key_resize();
			delwin(menu);
			delwin(dialog);
			goto do_resize;
		}
	}
	delwin(menu);
	delwin(dialog);
	return key;		
}
Beispiel #18
0
void get_command(void)
{
	char com[255];

	int text_width, text_startx;
	allocated_block_t *allocated_block = NULL;
	int i = 0;
	int count = 0;

	WINDOW *command_win = NULL;
        List allocated_blocks = NULL;
	ListIterator results_i;

	if (params.commandline && !params.command) {
		printf("Configure won't work with commandline mode.\n");
		printf("Please remove the -c from the commandline.\n");
		bg_configure_ba_fini();
		exit(0);
	}

	if (working_cluster_rec) {
		char *cluster_name = slurm_get_cluster_name();
		if (strcmp(working_cluster_rec->name, cluster_name)) {
			xfree(cluster_name);
			endwin();
			printf("To use the configure option you must be on the "
			       "cluster the configure is for.\nCross cluster "
			       "support doesn't exist today.\nSorry for the "
			       "inconvenince.\n");
			bg_configure_ba_fini();
			exit(0);
		}
		xfree(cluster_name);
	}

	/* make sure we don't get any noisy debug */
	ba_configure_set_ba_debug_flags(0);

	bg_configure_ba_setup_wires();

	color_count = 0;

	allocated_blocks = list_create(_destroy_allocated_block);

	if (params.commandline) {
		snprintf(com, sizeof(com), "%s", params.command);
		goto run_command;
	} else {
		text_width = text_win->_maxx;
		text_startx = text_win->_begx;
		command_win = newwin(3, text_width - 1, LINES - 4,
				     text_startx + 1);
		curs_set(1);
		echo();
	}

	while (strcmp(com, "quit")) {
		clear_window(grid_win);
		print_grid();
		clear_window(text_win);
		box(text_win, 0, 0);
		box(grid_win, 0, 0);

		if (!params.no_header)
			_print_header_command();

		if (error_string != NULL) {
			i = 0;
			while (error_string[i] != '\0') {
				if (error_string[i] == '\n') {
					main_ycord++;
					main_xcord=1;
					i++;
				}
				mvwprintw(text_win,
					  main_ycord,
					  main_xcord,
					  "%c",
					  error_string[i++]);
				main_xcord++;
			}
			main_ycord++;
			main_xcord = 1;
			memset(error_string, 0, 255);
		}
		results_i = list_iterator_create(allocated_blocks);

		count = list_count(allocated_blocks)
			- (LINES-(main_ycord+5));

		if (count<0)
			count=0;
		i=0;
		while ((allocated_block = list_next(results_i)) != NULL) {
			if (i >= count)
				_print_text_command(allocated_block);
			i++;
		}
		list_iterator_destroy(results_i);

		wnoutrefresh(text_win);
		wnoutrefresh(grid_win);
		doupdate();
		clear_window(command_win);

		box(command_win, 0, 0);
		mvwprintw(command_win, 0, 3,
			  "Input Command: (type quit to change view, "
			  "exit to exit)");
		wmove(command_win, 1, 1);
		wgetstr(command_win, com);

		if (!strcmp(com, "exit")) {
			endwin();
			if (allocated_blocks)
				list_destroy(allocated_blocks);
			bg_configure_ba_fini();
			exit(0);
		}
	run_command:

		if (!strcmp(com, "quit") || !strcmp(com, "\\q")) {
			break;
		} else if (!strncasecmp(com, "layout", 6)) {
			_set_layout(com);
		} else if (!strncasecmp(com, "basepartition", 13)) {
			_set_base_part_cnt(com);
		} else if (!strncasecmp(com, "nodecard", 8)) {
			_set_nodecard_cnt(com);
		} else if (!strncasecmp(com, "resolve", 7) ||
			   !strncasecmp(com, "r ", 2)) {
			_resolve(com);
		} else if (!strncasecmp(com, "resume", 6)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "drain", 5)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "alldown", 7)) {
			_change_state_all_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "down", 4)) {
			_change_state_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "allup", 5)) {
			_change_state_all_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "up", 2)) {
			_change_state_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "remove", 6)
			|| !strncasecmp(com, "delete", 6)
			|| !strncasecmp(com, "drop", 4)) {
			_remove_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "create", 6)) {
			_create_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "copy", 4)
			|| !strncasecmp(com, "c ", 2)
			|| !strncasecmp(com, "c\0", 2)) {
			_copy_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "save", 4)) {
			_save_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "load", 4)) {
			_load_configuration(com, allocated_blocks);
		} else if (!strncasecmp(com, "clear all", 9)
			|| !strncasecmp(com, "clear", 5)) {
			list_flush(allocated_blocks);
		} else {
			memset(error_string, 0, 255);
			sprintf(error_string, "Unknown command '%s'",com);
		}

		if (params.commandline) {
			bg_configure_ba_fini();
			exit(1);
		}
	}
	if (allocated_blocks)
		list_destroy(allocated_blocks);
	params.display = 0;
	noecho();

	clear_window(text_win);
	main_xcord = 1;
	main_ycord = 1;
	curs_set(0);
	print_date();
	get_job();
	return;
}
Beispiel #19
0
static int
test_opaque(int level, char **argv, WINDOW *stswin)
{
    WINDOW *txtbox = 0;
    WINDOW *txtwin = 0;
    FILE *fp;
    int ch;
    int txt_x = 0, txt_y = 0;
    int base_y;
    bool in_status = FALSE;
    int active = 0;

    if (argv[level] == 0) {
	beep();
	return FALSE;
    }

    if (level > 1) {
	txtbox = newwin(LINES - BASE_Y, COLS - level, BASE_Y, level);
	box(txtbox, 0, 0);
	wnoutrefresh(txtbox);

	txtwin = derwin(txtbox,
			getmaxy(txtbox) - 2,
			getmaxx(txtbox) - 2,
			1, 1);
	base_y = 0;
    } else {
	txtwin = stdscr;
	base_y = BASE_Y;
    }

    keypad(txtwin, TRUE);	/* enable keyboard mapping */
    (void) cbreak();		/* take input chars one at a time, no wait for \n */
    (void) noecho();		/* don't echo input */

    txt_y = base_y;
    txt_x = 0;
    wmove(txtwin, txt_y, txt_x);

    if ((fp = fopen(argv[level], "r")) != 0) {
	while ((ch = fgetc(fp)) != EOF) {
	    if (waddch(txtwin, UChar(ch)) != OK) {
		break;
	    }
	}
	fclose(fp);
    } else {
	wprintw(txtwin, "Cannot open:\n%s", argv[1]);
    }

    for (;;) {
	if (in_status) {
	    to_keyword(stswin, active);

	    ch = wgetch(stswin);
	    show_opaque(stswin, txtwin, TRUE, active);
	    if (Quit(ch))
		break;

	    switch (ch) {
	    case '\t':
		in_status = FALSE;
		break;
	    case KEY_DOWN:
	    case 'j':
		if (active < (int) SIZEOF(bool_funcs) - 1)
		    active++;
		else
		    beep();
		break;
	    case KEY_UP:
	    case 'k':
		if (active > 0)
		    active--;
		else
		    beep();
		break;
	    case ' ':
		bool_funcs[active].func(txtwin,
					!bool_funcs[active].func(txtwin, -1));
		break;
	    default:
		beep();
		break;
	    }
	    show_opaque(stswin, txtwin, FALSE, in_status ? active : -1);
	} else {
	    ch = mvwgetch(txtwin, txt_y, txt_x);
	    show_opaque(stswin, txtwin, TRUE, -1);
	    if (Quit(ch))
		break;

	    switch (ch) {
	    case '\t':
		in_status = TRUE;
		break;
	    case KEY_DOWN:
	    case 'j':
		if (txt_y < getmaxy(txtwin) - 1)
		    txt_y++;
		else
		    beep();
		break;
	    case KEY_UP:
	    case 'k':
		if (txt_y > base_y)
		    txt_y--;
		else
		    beep();
		break;
	    case KEY_LEFT:
	    case 'h':
		if (txt_x > 0)
		    txt_x--;
		else
		    beep();
		break;
	    case KEY_RIGHT:
	    case 'l':
		if (txt_x < getmaxx(txtwin) - 1)
		    txt_x++;
		else
		    beep();
		break;
	    case 'w':
		test_opaque(level + 1, argv, stswin);
		if (txtbox != 0) {
		    touchwin(txtbox);
		    wnoutrefresh(txtbox);
		} else {
		    touchwin(txtwin);
		    wnoutrefresh(txtwin);
		}
		break;
	    default:
		beep();
		napms(100);
		break;
	    }

	    show_opaque(stswin, txtwin, FALSE, -1);
	}
    }
    if (level > 1) {
	delwin(txtwin);
	delwin(txtbox);
    }
    return TRUE;
}
Beispiel #20
0
/******************************************************\
 * Description:	Determines the screen size of the the *
 *		terminal and prompts for the user to  *
 *		change the screen.		      *
\******************************************************/
RETSIGTYPE checkScreenSize(int sig)
{   
    int count;
    
    /* Avoid unused variable warning */
    UNUSED(sig);

    clearScreen(windows);
    endwin();
    init_screen();                                      /* init visuals       */

    slk_clear();                                        /* init menu bar      */
    slk_restore();                                      /* restore bottom menu*/
    slk_noutrefresh();
    doupdate();
							/* recacl these values*/
    BASE                =   (COLS - 6 - MIN_ADDR_LENGTH) / 4;            /*base for the number */
    hex_outline_width   =   (BASE * 3) + 3 + MIN_ADDR_LENGTH;
    MAXY                =   LINES - 3;
    hex_win_width       =   BASE * 3;
    ascii_outline_width =   BASE + 2;
    ascii_win_width     =   BASE;
    maxlines		=   maxLines((fpIN != NULL) ? maxLoc(fpIN) : 0);
    currentLine		=   0;
    SIZE_CH		=   TRUE;
                                                        /* check for term size*/
    if ((COLS < MIN_COLS) || (LINES < MIN_LINES))	
    {    
	/*
        endwin();
        printf("\n\n\n\nscreen size too small\n");
        exit(0);
	*/

	init_fkeys();                                   /* define menu bar    */
	init_menu(windows);                             /* init windows       */
	clearScreen(windows);
	slk_clear();
	mvwprintw(windows->hex, 0, 0, "Your screen is too small");
	/*mvwprintw(windows->hex, 1, 2, "Resize it to continue");*/
	refreshall(windows);
	doupdate();
    }
    else
    {
	init_fkeys();                                   /* define menu bar    */
	init_menu(windows);                             /* init windows       */
	wmove(windows->hex,0,0);
	if (fpIN)					/* if a file is open  */
	{
	    for (count = 0; count <= MAXY && count <= maxLines(maxLoc(fpIN)); 
		 count++)
		outline(fpIN, count);

	    mvwprintw(windows->cur_address, 0, 0, "%0*d", MIN_ADDR_LENGTH, 0);
	    wmove(windows->hex,0,0);
	}

	refreshall(windows);
        wnoutrefresh(windows->cur_address);
	/* this next refresh is to put the cursor in the correct window */
        wnoutrefresh(windows->hex);
	doupdate();
    }
}
Beispiel #21
0
/* Ask a simple Yes/No (and optionally All) question, specified in msg,
 * on the statusbar.  Return 1 for Yes, 0 for No, 2 for All (if all is
 * TRUE when passed in), and -1 for Cancel. */
int do_yesno_prompt(bool all, const char *msg)
{
    int ok = -2, width = 16;
    const char *yesstr;		/* String of Yes characters accepted. */
    const char *nostr;		/* Same for No. */
    const char *allstr;		/* And All, surprise! */
    const sc *s;
    int oldmenu = currmenu;

    assert(msg != NULL);

    /* yesstr, nostr, and allstr are strings of any length.  Each string
     * consists of all single-byte characters accepted as valid
     * characters for that value.  The first value will be the one
     * displayed in the shortcuts. */
    /* TRANSLATORS: For the next three strings, if possible, specify
     * the single-byte shortcuts for both your language and English.
     * For example, in French: "OoYy" for "Oui". */
    yesstr = _("Yy");
    nostr = _("Nn");
    allstr = _("Aa");

    if (!ISSET(NO_HELP)) {
	char shortstr[3];
		/* Temp string for Yes, No, All. */

	if (COLS < 32)
	    width = COLS / 2;

	/* Clear the shortcut list from the bottom of the screen. */
	blank_bottombars();

	sprintf(shortstr, " %c", yesstr[0]);
	wmove(bottomwin, 1, 0);
	onekey(shortstr, _("Yes"), width);

	if (all) {
	    wmove(bottomwin, 1, width);
	    shortstr[1] = allstr[0];
	    onekey(shortstr, _("All"), width);
	}

	wmove(bottomwin, 2, 0);
	shortstr[1] = nostr[0];
	onekey(shortstr, _("No"), width);

	wmove(bottomwin, 2, 16);
	onekey("^C", _("Cancel"), width);
    }

    wattron(bottomwin, reverse_attr);

    blank_statusbar();
    mvwaddnstr(bottomwin, 0, 0, msg, actual_x(msg, COLS - 1));

     wattroff(bottomwin, reverse_attr);

    /* Refresh the edit window and the statusbar before getting
     * input. */
    wnoutrefresh(edit);
    wnoutrefresh(bottomwin);

    do {
	int kbinput;
	bool meta_key, func_key;
#ifndef DISABLE_MOUSE
	int mouse_x, mouse_y;
#endif

	currmenu = MYESNO;
	kbinput = get_kbinput(bottomwin, &meta_key, &func_key);
	s = get_shortcut(currmenu, &kbinput, &meta_key, &func_key);

	if (s && s->scfunc ==  do_cancel)
	    ok = -1;
#ifndef DISABLE_MOUSE
	else if (kbinput == KEY_MOUSE) {
		/* We can click on the Yes/No/All shortcut list to
		 * select an answer. */
		if (get_mouseinput(&mouse_x, &mouse_y, FALSE) == 0 &&
			wmouse_trafo(bottomwin, &mouse_y, &mouse_x,
			FALSE) && mouse_x < (width * 2) &&
			mouse_y > 0) {
		    int x = mouse_x / width;
			/* Calculate the x-coordinate relative to the
			 * two columns of the Yes/No/All shortcuts in
			 * bottomwin. */
		    int y = mouse_y - 1;
			/* Calculate the y-coordinate relative to the
			 * beginning of the Yes/No/All shortcuts in
			 * bottomwin, i.e. with the sizes of topwin,
			 * edit, and the first line of bottomwin
			 * subtracted out. */

		    assert(0 <= x && x <= 1 && 0 <= y && y <= 1);

		    /* x == 0 means they clicked Yes or No.  y == 0
		     * means Yes or All. */
		    ok = -2 * x * y + x - y + 1;

		    if (ok == 2 && !all)
			ok = -2;
		}
	}
#endif /* !DISABLE_MOUSE */
	else if  (s && s->scfunc == total_refresh) {
	    total_redraw();
	    continue;
	} else {
		/* Look for the kbinput in the Yes, No and (optionally)
		 * All strings. */
		if (strchr(yesstr, kbinput) != NULL)
		    ok = 1;
		else if (strchr(nostr, kbinput) != NULL)
		    ok = 0;
		else if (all && strchr(allstr, kbinput) != NULL)
		    ok = 2;
	}
    } while (ok == -2);

    currmenu = oldmenu;
    return ok;
}
Beispiel #22
0
/********************************************************\
 * Description: outputs key command help                *
 * Returns:     none                                    *
\********************************************************/
void printHelp(WINS *win)
{
    WINDOW *ctrl, *help, *small;

    ctrl = newwin(LINES - 2, 9, 1, 1),
    help = newwin(LINES - 2, hex_win_width, 1, 10),
    small = newwin(LINES - 2, ascii_win_width, 1, hex_outline_width + 2);
    
    if ((LINES < 18) || (COLS < 78))			/* min size to display*/
    {
	mvwprintw(help, 0, 0, "Screen too small to display help");
	wmove(help,0,0);
    }
    else
    {
	wmove(ctrl,0,0);
	mvwprintw(ctrl, 0, 1, "Ctrl Key");		/* print in address   */
	mvwprintw(ctrl, 2, 1, "CTRL+?");
	mvwprintw(ctrl, 3, 1, "CTRL+S");
	mvwprintw(ctrl, 4, 1, "CTRL+O");
	mvwprintw(ctrl, 5, 1, "CTRL+G");
	mvwprintw(ctrl, 6, 1, "CTRL+F");
	mvwprintw(ctrl, 7, 1, "CTRL+A");
	mvwprintw(ctrl, 8, 1, "TAB");
	mvwprintw(ctrl, 9, 1, "CTRL+Q");
	mvwprintw(ctrl, 11, 1, "CTRL+U");
	mvwprintw(ctrl, 12, 1, "CTRL+D");
	mvwprintw(ctrl, 13, 1, "CTRL+Z");
	mvwprintw(ctrl, 14, 1, "CTRL+T");
	mvwprintw(ctrl, 15, 1, "CTRL+B");

	mvwprintw(small, 0, 1, "Function Keys");	/* print in ascii     */
	mvwprintw(small, 2, 1, "Help     = F1");
	mvwprintw(small, 3, 1, "Save     = F2");
	mvwprintw(small, 4, 1, "Open     = F3");
	mvwprintw(small, 5, 1, "Goto     = F4");
	mvwprintw(small, 6, 1, "Find     = F5");
	mvwprintw(small, 7, 1, "HexAdres = F6");
	mvwprintw(small, 8, 1, "Hex Edit = F7");
	mvwprintw(small, 9, 1, "Quit     = F8");
	mvwprintw(small, 11, 1, "Page up  = PGUP");
	mvwprintw(small, 12, 1, "Page down= PGDN");

	mvwprintw(help, 0, 10, "HexCurse Keyboard Commands");
	mvwprintw(help, 2, 2, "Help     - you are reading it now");
	mvwprintw(help, 3, 2, "Save     - saves the current file open");
	mvwprintw(help, 4, 2, "Open     - opens a new file");
	mvwprintw(help, 5, 2, "Goto     - goto a specified address");
	mvwprintw(help, 6, 2, "Find     - search for a hex/ascii value");
	mvwprintw(help, 7, 2, "HexAdres - toggle between hex/decimal address");
	mvwprintw(help, 8, 2, "Hex Edit - toggle between hex/ASCII windows");
	mvwprintw(help, 9, 2, "Quit     - exit out of the program");
	mvwprintw(help, 11, 2, "Page up  - scrolls one screen up");
	mvwprintw(help, 12, 2, "Page down- scrolls one screen down");
	mvwprintw(help, 13, 2, "Undo     - reverts last modification");
	mvwprintw(help, 14, 2, "Home     - returns to the top of the file");
	mvwprintw(help, 15, 2, "End      - jumps to the bottom of the file");
	mvwprintw(help, 17, 12, "Press enter to continue");
    }

    wnoutrefresh(ctrl);					/* refresh new wins   */
    wnoutrefresh(help);
    wnoutrefresh(small);
    doupdate();						/* update screen      */

    wgetch(ctrl);					/* wait for a char    */

    delwin(ctrl);					/* delete help wins   */
    delwin(help);
    delwin(small);

    redrawwin(win->hex);				/* redraw previous    */
    redrawwin(win->ascii);
    redrawwin(win->address);

    wnoutrefresh(win->hex);				/* refresh            */
    wnoutrefresh(win->ascii);
    wnoutrefresh(win->address);
    doupdate();						/* update screen      */

}
Beispiel #23
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':
			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 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 ' ':
			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 */
}
Beispiel #24
0
int
draw_message_pos(WINDOW *win, sip_msg_t *msg, int starting)
{
    int height, width, line, column, i;
    const char *cur_line, *payload;
    int syntax = setting_enabled(SETTING_SYNTAX);

    // Default text format
    int attrs = A_NORMAL | COLOR_PAIR(CP_DEFAULT);
    if (syntax)
        wattrset(win, attrs);

    // Get window of main panel
    getmaxyx(win, height, width);

    // Get packet payload
    cur_line = payload = (const char *) msg_get_payload(msg);

    // Print msg payload
    line = starting;
    column = 0;
    for (i = 0; i < strlen(payload); i++) {
        // If syntax highlighting is enabled
        if (syntax) {
            // First line highlight
            if (line == starting) {
                // Request syntax
                if (i == 0 && strncmp(cur_line, "SIP/2.0", 7))
                    attrs = A_BOLD | COLOR_PAIR(CP_YELLOW_ON_DEF);

                // Response syntax
                if (i == 8 && !strncmp(cur_line, "SIP/2.0", 7))
                    attrs = A_BOLD | COLOR_PAIR(CP_RED_ON_DEF);

                // SIP URI syntax
                if (!strncasecmp(payload + i, "sip:", 4)) {
                    attrs = A_BOLD | COLOR_PAIR(CP_CYAN_ON_DEF);
                }
            } else {

                // Header syntax
                if (strchr(cur_line, ':') && payload + i < strchr(cur_line, ':'))
                    attrs = A_NORMAL | COLOR_PAIR(CP_GREEN_ON_DEF);

                // Call-ID Header syntax
                if (!strncasecmp(cur_line, "Call-ID:", 8) && column > 8)
                    attrs = A_BOLD | COLOR_PAIR(CP_MAGENTA_ON_DEF);

                // CSeq Heaedr syntax
                if (!strncasecmp(cur_line, "CSeq:", 5) && column > 5 && !isdigit(payload[i]))
                    attrs = A_NORMAL | COLOR_PAIR(CP_YELLOW_ON_DEF);

                // tag and branch syntax
                if (i > 0 && payload[i - 1] == ';') {
                    // Highlight branch if requested
                    if (setting_enabled(SETTING_SYNTAX_BRANCH)) {
                        if (!strncasecmp(payload + i, "branch", 6)) {
                            attrs = A_BOLD | COLOR_PAIR(CP_CYAN_ON_DEF);
                        }
                    }
                    // Highlight tag if requested
                    if (setting_enabled(SETTING_SYNTAX_TAG)) {
                        if (!strncasecmp(payload + i, "tag", 3)) {
                            if (!strncasecmp(cur_line, "From:", 5)) {
                                attrs = A_BOLD | COLOR_PAIR(CP_DEFAULT);
                            } else {
                                attrs = A_BOLD | COLOR_PAIR(CP_GREEN_ON_DEF);
                            }
                        }
                    }
                }

                // SDP syntax
                if (strcspn(cur_line, "=") == 1)
                    attrs = A_NORMAL | COLOR_PAIR(CP_DEFAULT);
            }

            // Remove previous syntax
            if (strcspn(payload + i, " \n;<>") == 0) {
                wattroff(win, attrs);
                attrs = A_NORMAL | COLOR_PAIR(CP_DEFAULT);
            }

            // Syntax hightlight text!
            wattron(win, attrs);
        }

        // Dont print this characters
        if (payload[i] == '\r')
            continue;

        // Store where the line begins
        if (payload[i] == '\n')
            cur_line =payload + i + 1;

        // Move to the next line if line is filled or a we reach a line break
        if (column > width || payload[i] == '\n') {
            line++;
            column = 0;
            continue;
        }

        // Put next character in position
        mvwaddch(win, line, column++, payload[i]);

        // Stop if we've reached the bottom of the window
        if (line == height)
            break;
    }

    // Disable syntax when leaving
    if (syntax)
        wattroff(win, attrs);

    // Redraw raw win
    wnoutrefresh(win);

    return line - starting;
}
Beispiel #25
0
static void friendlist_onDraw(ToxWindow *self, Tox *m)
{
    curs_set(0);
    werase(self->window);
    int x2, y2;
    getmaxyx(self->window, y2, x2);

    bool fix_statuses = x2 != self->x;    /* true if window max x value has changed */

    wattron(self->window, COLOR_PAIR(CYAN));
    wprintw(self->window, " Press the");
    wattron(self->window, A_BOLD);
    wprintw(self->window, " h ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "key for help\n\n");
    wattroff(self->window, COLOR_PAIR(CYAN));

    if (blocklist_view == 1) {
        blocklist_onDraw(self, m, y2, x2);
        return;
    }

    time_t cur_time = get_unix_time();
    struct tm cur_loc_tm = *localtime((const time_t *) &cur_time);

    wattron(self->window, A_BOLD);
    wprintw(self->window, " Online: ");
    wattroff(self->window, A_BOLD);

    wprintw(self->window, "%d/%d \n\n", Friends.num_online, Friends.num_friends);

    if ((y2 - FLIST_OFST) <= 0) {
        return;
    }

    uint32_t selected_num = 0;

    /* Determine which portion of friendlist to draw based on current position */
    pthread_mutex_lock(&Winthread.lock);
    int page = Friends.num_selected / (y2 - FLIST_OFST);
    pthread_mutex_unlock(&Winthread.lock);

    int start = (y2 - FLIST_OFST) * page;
    int end = y2 - FLIST_OFST + start;

    pthread_mutex_lock(&Winthread.lock);
    size_t num_friends = Friends.num_friends;
    pthread_mutex_unlock(&Winthread.lock);

    int i;

    for (i = start; i < num_friends && i < end; ++i) {
        pthread_mutex_lock(&Winthread.lock);
        uint32_t f = Friends.index[i];
        bool is_active = Friends.list[f].active;
        int num_selected = Friends.num_selected;
        pthread_mutex_unlock(&Winthread.lock);

        bool f_selected = false;

        if (is_active) {
            if (i == num_selected) {
                wattron(self->window, A_BOLD);
                wprintw(self->window, " > ");
                wattroff(self->window, A_BOLD);
                selected_num = f;
                f_selected = true;
            } else {
                wprintw(self->window, "   ");
            }

            pthread_mutex_lock(&Winthread.lock);
            Tox_Connection connection_status = Friends.list[f].connection_status;
            Tox_User_Status status = Friends.list[f].status;
            pthread_mutex_unlock(&Winthread.lock);

            if (connection_status != TOX_CONNECTION_NONE) {
                int colour = MAGENTA;

                switch (status) {
                    case TOX_USER_STATUS_NONE:
                        colour = GREEN;
                        break;

                    case TOX_USER_STATUS_AWAY:
                        colour = YELLOW;
                        break;

                    case TOX_USER_STATUS_BUSY:
                        colour = RED;
                        break;
                }

                wattron(self->window, COLOR_PAIR(colour) | A_BOLD);
                wprintw(self->window, "%s ", ONLINE_CHAR);
                wattroff(self->window, COLOR_PAIR(colour) | A_BOLD);

                if (f_selected) {
                    wattron(self->window, COLOR_PAIR(BLUE));
                }

                wattron(self->window, A_BOLD);
                pthread_mutex_lock(&Winthread.lock);
                wprintw(self->window, "%s", Friends.list[f].name);
                pthread_mutex_unlock(&Winthread.lock);
                wattroff(self->window, A_BOLD);

                if (f_selected) {
                    wattroff(self->window, COLOR_PAIR(BLUE));
                }

                /* Reset Friends.list[f].statusmsg on window resize */
                if (fix_statuses) {
                    char statusmsg[TOX_MAX_STATUS_MESSAGE_LENGTH];

                    pthread_mutex_lock(&Winthread.lock);
                    tox_friend_get_status_message(m, Friends.list[f].num, (uint8_t *) statusmsg, NULL);
                    size_t s_len = tox_friend_get_status_message_size(m, Friends.list[f].num, NULL);
                    pthread_mutex_unlock(&Winthread.lock);

                    statusmsg[s_len] = '\0';

                    filter_str(statusmsg, s_len);

                    pthread_mutex_lock(&Winthread.lock);
                    snprintf(Friends.list[f].statusmsg, sizeof(Friends.list[f].statusmsg), "%s", statusmsg);
                    Friends.list[f].statusmsg_len = strlen(Friends.list[f].statusmsg);
                    pthread_mutex_unlock(&Winthread.lock);
                }

                /* Truncate note if it doesn't fit on one line */
                size_t maxlen = x2 - getcurx(self->window) - 2;

                pthread_mutex_lock(&Winthread.lock);

                if (Friends.list[f].statusmsg_len > maxlen) {
                    Friends.list[f].statusmsg[maxlen - 3] = '\0';
                    strcat(Friends.list[f].statusmsg, "...");
                    Friends.list[f].statusmsg[maxlen] = '\0';
                    Friends.list[f].statusmsg_len = maxlen;
                }

                if (Friends.list[f].statusmsg_len > 0) {
                    wprintw(self->window, " %s", Friends.list[f].statusmsg);
                }

                pthread_mutex_unlock(&Winthread.lock);

                wprintw(self->window, "\n");
            } else {
                wprintw(self->window, "%s ", OFFLINE_CHAR);

                if (f_selected) {
                    wattron(self->window, COLOR_PAIR(BLUE));
                }

                wattron(self->window, A_BOLD);
                pthread_mutex_lock(&Winthread.lock);
                wprintw(self->window, "%s", Friends.list[f].name);
                pthread_mutex_unlock(&Winthread.lock);
                wattroff(self->window, A_BOLD);

                if (f_selected) {
                    wattroff(self->window, COLOR_PAIR(BLUE));
                }

                pthread_mutex_lock(&Winthread.lock);
                time_t last_seen = Friends.list[f].last_online.last_on;
                pthread_mutex_unlock(&Winthread.lock);

                if (last_seen != 0) {
                    pthread_mutex_lock(&Winthread.lock);

                    int day_dist = (
                                       cur_loc_tm.tm_yday - Friends.list[f].last_online.tm.tm_yday
                                       + ((cur_loc_tm.tm_year - Friends.list[f].last_online.tm.tm_year) * 365)
                                   );
                    const char *hourmin = Friends.list[f].last_online.hour_min_str;

                    pthread_mutex_unlock(&Winthread.lock);

                    switch (day_dist) {
                        case 0:
                            wprintw(self->window, " Last seen: Today %s\n", hourmin);
                            break;

                        case 1:
                            wprintw(self->window, " Last seen: Yesterday %s\n", hourmin);
                            break;

                        default:
                            wprintw(self->window, " Last seen: %d days ago\n", day_dist);
                            break;
                    }
                } else {
                    wprintw(self->window, " Last seen: Never\n");
                }
            }
        }
    }

    self->x = x2;

    if (num_friends) {
        wmove(self->window, y2 - 1, 1);

        wattron(self->window, A_BOLD);
        wprintw(self->window, "Key: ");
        wattroff(self->window, A_BOLD);

        int i;

        for (i = 0; i < TOX_PUBLIC_KEY_SIZE; ++i) {
            wprintw(self->window, "%02X", Friends.list[selected_num].pub_key[i] & 0xff);
        }
    }

    wnoutrefresh(self->window);
    draw_del_popup();

    if (self->help->active) {
        help_onDraw(self);
    }
}
/*
 * 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;
	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);

	print_title(dialog, title, width);

	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 = wgetch(dialog);
		switch (key) {
		case 'E':	/* Exit */
		case 'e':
		case 'X':
		case 'x':
			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 */
		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 */
		case ' ':
			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 ESC:
			break;
		}
	}

	delwin(dialog);
	free(buf);
	close(fd);
	return -1;		/* ESC pressed */
}
Beispiel #27
0
int main() {
    int i, j, k, screenHeight, screenWidth;
    int input;
    unsigned int ch;
    char *boundString;
    int ch2;
    char inputBuffer[40];
    int terminalIndex, fdMax;
    fd_set fileDescriptors;
    struct timespec timeout;
    //struct tesiObject *to;
    struct virtualTerminal *vt;

    for(i = 0; i < 10; i++)
        virtualTerminals[i] = NULL;

    fdMax = 0;
    timeout.tv_sec = 0;
    timeout.tv_nsec = 50000000; // 10E-9

#ifdef USE_NCURSES
    ncursesScreen = initscr();
    if(ncursesScreen == NULL) {
        perror("Error initializing nCurses\n");
        exit(1);
    }

    if(has_colors()) {
        start_color();
#ifdef DEBUG
        fprintf(stderr, "max colors: %d\n", COLORS);
        fprintf(stderr, "max color pairs: %d\n", COLOR_PAIRS);
#endif
        k = 1;
        for(i = 0; i < COLORS; i++) {
            for(j = 0; j < COLORS; j++) {
                vt_colors[i][j] = k;
                init_pair(k, i, j);
                k++;
            }
        }
        //init all color pairs
        /*
         * black red green yellow blue magenta cyan white
         * attributes 30-37
         * in iterm, black starts at 1
         * */
    }

    keypad(ncursesScreen, true); // cause nCurses to package key combos into special, single values
    nodelay(ncursesScreen, TRUE); // return immediately if no input is waiting
    raw();
    noecho(); // don't echo input
    refresh(); // clear the main window

    // Get main window dimensions. This will be used when creating additional virtual terminals
    getmaxyx(ncursesScreen, screenHeight, screenWidth);
#endif

    inputBuffer[0] = 0;
    mvwaddstr(ncursesScreen, screenHeight - 1, 0, ":");

    mvwaddstr(ncursesScreen, 1, 0, "USING KNOX\n\nCommands\n\t\"create\" - creates a new Virtual Terminal\n\t\"create #\" - create # number of new Virtual Terminals\n\t\"NUMBER\" - sets focus to so numbered terminal\n\t\"NUMBER COMMAND\" - sends COMMAND to numbered terminal followed by newline");
    wmove(ncursesScreen, screenHeight - 1, 1);

    terminalIndex = -1;
    keepRunning = 1;
    k = 0;
    while(keepRunning) {
        FD_ZERO(&fileDescriptors);
        for(i = 0; i < 10; i++) {
            //if(vtGet(i) != NULL && tesi_handleInput(vtGet(i))) {
            vt = vtGet(i);
            if(vt && vt->fd != -1) {
                if(vt->fd > fdMax)
                    fdMax = vt->fd;
                FD_SET(vt->fd, &fileDescriptors);
            }
        }

        pselect(fdMax + 1, &fileDescriptors, NULL, NULL, &timeout, NULL);
        j = 0;
        for(i = 0; i < 10; i++) {
            //if(vtGet(i) != NULL && tesi_handleInput(vtGet(i))) {
            vt = vtGet(i);
            if(vt != NULL && vt->fd != -1 && FD_ISSET(vt->fd, &fileDescriptors)) {
                VTCore_dispatch(vt->core);
#ifdef USE_NCURSES
                //vt = (struct virtualTerminal*) vtGet(i)->pointer;
                wnoutrefresh(vt->window);
#endif
                j++; // keep track of the terminals that need updating
            }
        }
        if(j || k) { // if a VT or command window needs updating
#ifdef USE_NCURSES
            // re-move cursor to correct location after updating screens
            if(terminalIndex > -1) {
                //to = (struct tesiObject*) vtGet(terminalIndex);
                //vt = (struct virtualTerminal*) to->pointer;
                vt = vtGet(terminalIndex);
                //wmove(vt->window, to->y, to->x);
            } else {
                wmove(ncursesScreen, screenHeight - 1, 1 + strlen(inputBuffer));
            }

            doupdate();
        }
        k = 0;
        ch = wgetch(ncursesScreen); // ?
#endif
#ifdef USE_SLANG
        SLsmg_refresh();
        if(!SLang_input_pending(1)) // wait 1/10 of a second
            continue;
        ch = SLang_getkey();
#endif

#ifdef USE_NCURSES
#endif

        switch(ch) {
        case '`': // tilde pressed, cycle through terms?
            //case KEY_RIGHT: // tilde pressed, cycle through terms?
            terminalIndex++;
            if(terminalIndex == 10 || vtGet(terminalIndex) == NULL)
                terminalIndex = -1;
            vtHighlight(terminalIndex);
            k = 1; // update cursor position
            break;
        case ERR: // no input
            break;
        default:
            if(terminalIndex > -1) { // send input to terminal
                //to = vtGet(terminalIndex);
                vt = vtGet(terminalIndex);
                if(vt) { // this should never be null, but check anyway
                    boundString = keybound(ch, 0);
                    if(boundString) {
#ifdef DEBUG
                        fprintf(stderr, "key string: %s\n", boundString);
#endif
                        write(vt->fd, boundString, strlen(boundString));
                        free(boundString);
                    } else
                        write(vt->fd, &ch, 1);

                }

            } else { // build input buffer
#ifdef DEBUG
                fprintf(stderr, "Keypress: %d\n", ch);
#endif
                if(ch == 10) { // parse buffer when Enter is pressed, returns active terminal index
                    //wclear(ncursesScreen);
                    terminalIndex = processInput(inputBuffer, terminalIndex, screenHeight, screenWidth);
                    vtHighlight(terminalIndex);

                    FD_ZERO(&fileDescriptors);
                    FD_SET(0, &fileDescriptors);
#ifdef USE_NCURSES
                    // clear command window
                    mvwaddch(ncursesScreen, screenHeight - 1, 0, ':');
                    wmove(ncursesScreen, screenHeight - 1, 1);
                    wclrtoeol(ncursesScreen);
                    wmove(ncursesScreen, screenHeight - 1, 1);
                    wnoutrefresh(ncursesScreen);
                    k = 1;
#endif
                    inputBuffer[0] = 0;

                } else {
                    i = strlen(inputBuffer);
                    inputBuffer[ i ] = ch;
                    inputBuffer[ i + 1 ] = 0;
#ifdef USE_NCURSES
                    mvwaddstr(ncursesScreen, screenHeight - 1, 1, inputBuffer);
#endif
#ifdef USE_SLANG
                    SLsmg_gotorc(SLtt_Screen_Rows - 1, 0);
                    SLsmg_write_string(inputBuffer);
                    SLsmg_refresh();
#endif
                }
            }
            break;
        }
    }

    for(i = 0; i < 10; i++) {
        if(virtualTerminals[i] != NULL) {
            vtDestroy(i);
        }
    }

#ifdef USE_NCURSES
    endwin();
#endif
#ifdef USE_SLANG
    SLsmg_reset_smg();
    SLang_reset_tty();
#endif
    return 0;
}
Beispiel #28
0
int slk_noutrefresh(void)
{
    PDC_LOG(("slk_noutrefresh() - called\n"));

    return wnoutrefresh(SP->slk_winptr);
}
Beispiel #29
0
static void
test_adds(int level)
{
    static bool first = TRUE;

    int ch;
    int limit;
    int row = 1;
    int col;
    int row2, col2;
    int length;
    char buffer[BUFSIZ];
    WINDOW *look = 0;
    WINDOW *work = 0;
    WINDOW *show = 0;
    int margin = (2 * MY_TABSIZE) - 1;
    Options option = (Options) ((unsigned) (m_opt
					    ? oMove
					    : oDefault)
				| (unsigned) ((w_opt || (level > 0))
					      ? oWindow
					      : oDefault));

    if (first) {
	static char cmd[80];
	setlocale(LC_ALL, "");

	putenv(strcpy(cmd, "TABSIZE=8"));

	initscr();
	(void) cbreak();	/* take input chars one at a time, no wait for \n */
	(void) noecho();	/* don't echo input */
	keypad(stdscr, TRUE);
    }

    limit = LINES - 5;
    if (level > 0) {
	look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1);
	work = newwin(limit - 2, COLS - (2 * level), 1, level);
	show = newwin(4, COLS, limit + 1, 0);
	box(look, 0, 0);
	wnoutrefresh(look);
	limit -= 2;
    } else {
	work = stdscr;
	show = derwin(stdscr, 4, COLS, limit + 1, 0);
    }
    keypad(work, TRUE);

    for (col = margin + 1; col < COLS; col += MY_TABSIZE)
	MvWVLine(work, row, col, '.', limit - 2);

    MvWVLine(work, row, margin, ACS_VLINE, limit - 2);
    MvWVLine(work, row, margin + 1, ACS_VLINE, limit - 2);
    limit /= 2;

    MvWAddChStr(work, 1, 2, ChStr("String"));
    MvWAddChStr(work, limit + 1, 2, ChStr("Chars"));
    wnoutrefresh(work);

    buffer[length = 0] = '\0';
    legend(show, level, option, buffer, length);
    wnoutrefresh(show);

    doupdate();

    /*
     * Show the characters added in color, to distinguish from those that
     * are shifted.
     */
    if (has_colors()) {
	start_color();
	init_pair(1, COLOR_WHITE, COLOR_BLUE);
	show_attr = COLOR_PAIR(1);
	wbkgdset(work, show_attr | ' ');
    } else {
	show_attr = A_STANDOUT;
    }

    while ((ch = read_linedata(work)) != ERR && !isQUIT(ch)) {
	wmove(work, row, margin + 1);
	switch (ch) {
	case key_RECUR:
	    test_adds(level + 1);

	    touchwin(look);
	    touchwin(work);
	    touchwin(show);

	    wnoutrefresh(look);
	    wnoutrefresh(work);
	    wnoutrefresh(show);

	    doupdate();
	    break;
	case key_NEWLINE:
	    if (row < limit) {
		++row;
		/* put the whole string in, all at once */
		col2 = margin + 1;
		switch (option) {
		case oDefault:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    if (move(row, col2) != ERR) {
				AddNStr(ChStr2(buffer + col), LEN(col));
			    }
			}
		    } else {
			if (move(row, col2) != ERR) {
			    AddStr(ChStr2(buffer));
			}
		    }
		    break;
		case oMove:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvAddNStr(row, col2, ChStr2(buffer + col), LEN(col));
			}
		    } else {
			MvAddStr(row, col2, ChStr2(buffer));
		    }
		    break;
		case oWindow:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    if (wmove(work, row, col2) != ERR) {
				WAddNStr(work, ChStr2(buffer + col), LEN(col));
			    }
			}
		    } else {
			if (wmove(work, row, col2) != ERR) {
			    WAddStr(work, ChStr2(buffer));
			}
		    }
		    break;
		case oMoveWindow:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvWAddNStr(work, row, col2, ChStr2(buffer + col),
				       LEN(col));
			}
		    } else {
			MvWAddStr(work, row, col2, ChStr2(buffer));
		    }
		    break;
		}

		/* do the corresponding single-character add */
		row2 = limit + row;
		for (col = 0; col < length; ++col) {
		    col2 = ColOf(buffer, col, margin);
		    switch (option) {
		    case oDefault:
			if (move(row2, col2) != ERR) {
			    AddCh(UChar(buffer[col]));
			}
			break;
		    case oMove:
			MvAddCh(row2, col2, UChar(buffer[col]));
			break;
		    case oWindow:
			if (wmove(work, row2, col2) != ERR) {
			    WAddCh(work, UChar(buffer[col]));
			}
			break;
		    case oMoveWindow:
			MvWAddCh(work, row2, col2, UChar(buffer[col]));
			break;
		    }
		}
	    } else {
		beep();
	    }
	    break;
	case KEY_BACKSPACE:
	    ch = '\b';
	    /* FALLTHRU */
	default:
	    if (ch <= 0 || ch > 255) {
		beep();
		break;
	    }
	    buffer[length++] = (char) ch;
	    buffer[length] = '\0';

	    /* put the string in, one character at a time */
	    col = ColOf(buffer, length - 1, margin);
	    switch (option) {
	    case oDefault:
		if (move(row, col) != ERR) {
		    AddStr(ChStr2(buffer + length - 1));
		}
		break;
	    case oMove:
		MvAddStr(row, col, ChStr2(buffer + length - 1));
		break;
	    case oWindow:
		if (wmove(work, row, col) != ERR) {
		    WAddStr(work, ChStr2(buffer + length - 1));
		}
		break;
	    case oMoveWindow:
		MvWAddStr(work, row, col, ChStr2(buffer + length - 1));
		break;
	    }

	    /* do the corresponding single-character add */
	    switch (option) {
	    case oDefault:
		if (move(limit + row, col) != ERR) {
		    AddCh(UChar(ch));
		}
		break;
	    case oMove:
		MvAddCh(limit + row, col, UChar(ch));
		break;
	    case oWindow:
		if (wmove(work, limit + row, col) != ERR) {
		    WAddCh(work, UChar(ch));
		}
		break;
	    case oMoveWindow:
		MvWAddCh(work, limit + row, col, UChar(ch));
		break;
	    }

	    wnoutrefresh(work);

	    legend(show, level, option, buffer, length);
	    wnoutrefresh(show);

	    doupdate();
	    break;
	}
    }
    if (level > 0) {
	delwin(show);
	delwin(work);
	delwin(look);
    }
}
Beispiel #30
0
void
call_list_draw_list(PANEL *panel)
{
    WINDOW *win;
    int height, width, cline = 0;
    struct sip_call *call;
    int i, collen;
    char coltext[256];
    int colid;
    int colpos;
    int color;

    // Get panel info
    call_list_info_t *info = call_list_info(panel);

    // Get window of call list panel
    win = info->list_win;
    getmaxyx(win, height, width);

    // If autoscroll is enabled, select the last dialog
    if (info->autoscroll) {
        call_list_handle_key(panel, key_action_key(ACTION_END));
    }

    // If no active call, use the fist one (if exists)
    if (info->first_call == -1 && vector_iterator_count(&info->calls)) {
        vector_iterator_reset(&info->calls);
        call = vector_iterator_next(&info->calls);
        info->cur_call = info->first_call = vector_index(vector_iterator_vector(&info->calls), call);
        info->cur_line = info->first_line = 1;
    }

    // Clear call list before redrawing
    werase(win);

    // Set the iterator position to the first call
    vector_iterator_set_current(&info->calls, info->first_call - 1 );

    // Fill the call list
    while ((call = vector_iterator_next(&info->calls))) {
        // Stop if we have reached the bottom of the list
        if (cline == height)
            break;

        // We only print calls with messages (In fact, all call should have msgs)
        if (!call_msg_count(call))
            continue;

        // Show bold selected rows
        if (call_group_exists(info->group, call))
            wattron(win, A_BOLD | COLOR_PAIR(CP_DEFAULT));

        // Highlight active call
        if (call->index == info->cur_call + 1) {
            wattron(win, COLOR_PAIR(CP_WHITE_ON_BLUE));
            // Reverse colors on monochrome terminals
            if (!has_colors())
                wattron(win, A_REVERSE);
        }
        // Set current line background
        clear_line(win, cline);
        // Set current line selection box
        mvwprintw(win, cline, 2, call_group_exists(info->group, call) ? "[*]" : "[ ]");

        // Print requested columns
        colpos = 6;
        for (i = 0; i < info->columncnt; i++) {
            // Get current column id
            colid = info->columns[i].id;
            // Get current column width
            collen = info->columns[i].width;
            // Check if next column fits on window width
            if (colpos + collen >= width)
                break;

            // Initialize column text
            memset(coltext, 0, sizeof(coltext));

            // Get call attribute for current column
            if (!call_get_attribute(call, colid, coltext)) {
                colpos += collen + 1;
                continue;
            }

            // Enable attribute color (if not current one)
            color = 0;
            if (call->index != info->cur_call + 1 && (color = sip_attr_get_color(colid, coltext)) > 0)
                wattron(win, color);

            // Add the column text to the existing columns
            mvwprintw(win, cline, colpos, "%.*s", collen, coltext);
            colpos += collen + 1;

            // Disable attribute color
            if (color > 0)
                wattroff(win, color);
        }
        cline++;

        wattroff(win, COLOR_PAIR(CP_DEFAULT));
        wattroff(win, COLOR_PAIR(CP_DEF_ON_BLUE));
        wattroff(win, A_BOLD | A_REVERSE);
    }

    // Draw scrollbar to the right
    draw_vscrollbar(win, info->first_line, info->dispcallcnt, 1);
    wnoutrefresh(info->list_win);

}