Exemplo n.º 1
0
int init(){
	//Initialize all subsystems
	if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ){
		return false;
	}
	
	//Set up the screen
	set_window_size(SCREEN_WIDTH, SCREEN_HEIGHT);
	
	//If there was an error setting up the screen
	if(screen == NULL ){
		return false;
	}
	
	//Set the window caption
	SDL_WM_SetCaption( "CoSwarm 0.1", NULL );
	
	//Initialize SDL_ttf
    if( TTF_Init() == -1 )
    {
        MessageBox(NULL, "TTF library was not initialized correctly.", "Warning!", MB_OK);
        return false;
    }
	
	//If everything initialized fine
	return true;
}
Exemplo n.º 2
0
Arquivo: main.c Projeto: cout/sx3
int main(int argc, char *argv[]) {
    // Check for command-line arguments
    if(argc < 3) {
        fprintf(stderr, "Usage: %s: [options] model weapon skin\n",
            argv[0]);
        exit(1);
    }

    // Intialize SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Unable to initialize SDL\n");
        exit(1);
    }

    // Set our quit function so that we clean up properly
    atexit(SDL_Quit);

    // Set our desired GL attributes.  I'm not sure if this is necessary,
    // and I'm not sure what happens if the desired attributes cannot be
    // negotiated.
/*
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
*/
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    if(SDL_SetVideoMode(640, 480, 16, SDL_OPENGL) == NULL) {
        fprintf(stderr, "Unable set set GL mode\n");
        exit(1);
    }

    // Set the title of the Window, and use the default icon.  We could
    // specify an icon for the window, if we had one.
    SDL_WM_SetCaption("Model Viewer", NULL);

    // Initialize the viewer
    init(argv[1], argv[2], argv[3]);

    // Display the model for the first time
    set_window_size(640, 480);
    display();

    // Go into the event loop.  Unlike with GTK or GLUT, this function *will*
    // return.
    main_loop();

    return 0;
}
Exemplo n.º 3
0
Arquivo: main.c Projeto: cout/sx3
// SDL doesn't use callbacks, so we must check the events ourselves
void main_loop() {
    SDL_Event event;
    SDL_Event prev_event;
    int retval;

    for(;;) {
        // We can wait on an event (as we are doing here), or we can poll for
        // events and, if there are no events waiting to be processed, we can
        // call our idle function.  This allows for a slightly more versatile
        // event handler than with a callback-based approach, as with GLUT.
        if(!SDL_WaitEvent(&event)) continue;
event_switch:
        switch(event.type) {
            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
                mouse_button(event.button.button, event.button.state,
                    event.button.x, event.button.y);
                break;
            case SDL_MOUSEMOTION:
                // This is a hack to keep the motion from being so jumpy on
                // slow cards
                do {
                    prev_event = event;
                    retval = SDL_PollEvent(&event);
                } while(retval != 0 && event.type == SDL_MOUSEMOTION);
                if(retval != 0) {
                    // SDL_PushEvent(&event);
                    // event = prev_event;
                    mouse_motion(prev_event.motion.state,
                        prev_event.motion.x, prev_event.motion.y);
                    goto event_switch;
                }
                mouse_motion(event.motion.state,
                    event.motion.x, event.motion.y);
                break;
            case SDL_KEYUP:
                keyfunc(event.key.keysym.sym);
                break;
            case SDL_VIDEORESIZE:
                set_window_size(event.resize.w, event.resize.h);
                break;
            case SDL_QUIT:
                return;
        }
    }
}
Exemplo n.º 4
0
/* Extract any control sequences that are ment only for run_erl
 * and should not be forwarded to the pty.
 */
static int extract_ctrl_seq(char* buf, int len)
{
    static const char prefix[] = "\033_";
    static const char suffix[] = "\033\\";
    char* bufend = buf + len;
    char* start = buf;
    char* command;
    char* end;
    
    for (;;) {
	start = find_str(start, bufend-start, prefix);
	if (!start) break;
	
	command = start + strlen(prefix);
	end = find_str(command, bufend-command, suffix);
	if (end) {
	    unsigned col, row;
	    if (sscanf(command,"version=%u", &protocol_ver)==1) {
		/*fprintf(stderr,"to_erl v%u\n", protocol_ver);*/
	    }
	    else if (sscanf(command,"winsize=%u,%u", &col, &row)==2) {
		set_window_size(col,row);
	    }
	    else {
		ERROR2(LOG_ERR, "Ignoring unknown ctrl command '%.*s'\n",
		       (int)(end-command), command);
	    }
	  
	    /* Remove ctrl sequence from buf */
	    end += strlen(suffix);
	    memmove(start, end, bufend-end);
	    bufend -= end - start;
	}
	else {
	    ERROR2(LOG_ERR, "Missing suffix in ctrl sequence '%.*s'\n",
		   (int)(bufend-start), start);
	    break;
	}
    }
    return bufend - buf;
}
Exemplo n.º 5
0
/*!

\brief Updates mouse event.
\param[in] Value InputEventMouse containing the state of the mouse event.
\return Returns dmz::True if \a Value is different than the internal mosue event value.
\note The previous mouse event values are only updated if \a Value is different from
the current mouse event value.

*/
dmz::Boolean
dmz::InputEventMouse::update (const InputEventMouse &Value) {

   Boolean result (False);

   if (*this != Value) {

      set_window_size (Value.get_window_size_x (), Value.get_window_size_y ());
      set_mouse_position (Value.get_mouse_x (), Value.get_mouse_y ());

      set_mouse_screen_position (
         Value.get_mouse_screen_x (),
         Value.get_mouse_screen_y ());

      set_button_mask (Value.get_button_mask ());
      set_scroll_delta (Value.get_scroll_delta_x (), Value.get_scroll_delta_y ());

      result = True;
   }

   return result;
}
Exemplo n.º 6
0
int
main(int argc, char **argv)
{
    int ch, noinit, noset, quiet, Sflag, sflag, showterm;
    const char *ttype;
    int terasechar = -1;	/* new erase character */
    int intrchar = -1;		/* new interrupt character */
    int tkillchar = -1;		/* new kill character */
    int my_fd;
    bool opt_c = FALSE;		/* set control-chars */
    bool opt_w = FALSE;		/* set window-size */
    TTY mode, oldmode;

    my_fd = STDERR_FILENO;
    obsolete(argv);
    noinit = noset = quiet = Sflag = sflag = showterm = 0;
    while ((ch = getopt(argc, argv, "a:cd:e:Ii:k:m:p:qQrSsVw")) != -1) {
	switch (ch) {
	case 'c':		/* set control-chars */
	    opt_c = TRUE;
	    break;
	case 'a':		/* OBSOLETE: map identifier to type */
	    add_mapping("arpanet", optarg);
	    break;
	case 'd':		/* OBSOLETE: map identifier to type */
	    add_mapping("dialup", optarg);
	    break;
	case 'e':		/* erase character */
	    terasechar = arg_to_char();
	    break;
	case 'I':		/* no initialization strings */
	    noinit = 1;
	    break;
	case 'i':		/* interrupt character */
	    intrchar = arg_to_char();
	    break;
	case 'k':		/* kill character */
	    tkillchar = arg_to_char();
	    break;
	case 'm':		/* map identifier to type */
	    add_mapping(0, optarg);
	    break;
	case 'p':		/* OBSOLETE: map identifier to type */
	    add_mapping("plugboard", optarg);
	    break;
	case 'Q':		/* don't output control key settings */
	    quiet = 1;
	    break;
	case 'q':		/* display term only */
	    noset = 1;
	    break;
	case 'r':		/* display term on stderr */
	    showterm = 1;
	    break;
	case 'S':		/* OBSOLETE: output TERM & TERMCAP */
	    Sflag = 1;
	    break;
	case 's':		/* output TERM set command */
	    sflag = 1;
	    break;
	case 'V':		/* print curses-version */
	    puts(curses_version());
	    ExitProgram(EXIT_SUCCESS);
	case 'w':		/* set window-size */
	    opt_w = TRUE;
	    break;
	case '?':
	default:
	    usage();
	}
    }

    _nc_progname = _nc_rootname(*argv);
    argc -= optind;
    argv += optind;

    if (argc > 1)
	usage();

    if (!opt_c && !opt_w)
	opt_c = opt_w = TRUE;

    my_fd = save_tty_settings(&mode, TRUE);
    oldmode = mode;
#ifdef TERMIOS
    ospeed = (NCURSES_OSPEED) cfgetospeed(&mode);
#else
    ospeed = (NCURSES_OSPEED) mode.sg_ospeed;
#endif

    if (same_program(_nc_progname, PROG_RESET)) {
	reset_start(stderr, TRUE, FALSE);
	reset_tty_settings(my_fd, &mode);
    } else {
	reset_start(stderr, FALSE, TRUE);
    }

    ttype = get_termcap_entry(my_fd, *argv);

    if (!noset) {
#if HAVE_SIZECHANGE
	if (opt_w) {
	    set_window_size(my_fd, &lines, &columns);
	}
#endif
	if (opt_c) {
	    set_control_chars(&mode, terasechar, intrchar, tkillchar);
	    set_conversions(&mode);

	    if (!noinit) {
		if (send_init_strings(my_fd, &oldmode)) {
		    (void) putc('\r', stderr);
		    (void) fflush(stderr);
		    (void) napms(1000);		/* Settle the terminal. */
		}
	    }

	    update_tty_settings(&oldmode, &mode);
	}
    }

    if (noset) {
	(void) printf("%s\n", ttype);
    } else {
	if (showterm)
	    (void) fprintf(stderr, "Terminal type is %s.\n", ttype);
	/*
	 * If erase, kill and interrupt characters could have been
	 * modified and not -Q, display the changes.
	 */
	if (!quiet) {
	    print_tty_chars(&oldmode, &mode);
	}
    }

    if (Sflag)
	err("The -S option is not supported under terminfo.");

    if (sflag) {
	print_shell_commands(ttype);
    }

    ExitProgram(EXIT_SUCCESS);
}
Exemplo n.º 7
0
int main(int argc, char *argv[]) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH |
		GLUT_STENCIL);
	if((argc > 1) && (strcmpi(argv[1], "--helmet") == 0)) {
		/*left eye*/
		glutInitWindowPosition(0,0);
		glutInitWindowSize(640, 480);
		left_eye = glutCreateWindow("Escher World - Left Eye");

		glutSetWindow(left_eye);
		set_window_size(640, 480);
		glutDisplayFunc(displayleft);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);
/*		glutTimerFunc(10,child,1);*/

		/* right eye */
		glutInitWindowPosition(641,0);
		glutInitWindowSize(640, 480);
		right_eye = glutCreateWindow("Escher World - Right Eye");

		glutSetWindow(right_eye);
		set_window_size(640, 480);
		glutDisplayFunc(displayright);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);

		glutSetWindow(left_eye);
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);

		glutSetWindow(right_eye);
		create_menus();
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);

#ifdef USE_HELMET
/*		main_helmet();
		signal(SIGUSR1, cleanup);
*/		birdinit();
/*		glutTimerFunc(10,child,1);*/
#endif

	} else {
		glutInitWindowPosition(64,64);

		glutInitWindowSize(768, 832);
		glut_window = glutCreateWindow("Escher World");

		glutSetWindow(glut_window);
		set_window_size(768, 832);
		helmet = !helmet;
		glutDisplayFunc(displaymid);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);
	}

	glutMainLoop();

	return 0;
}
Exemplo n.º 8
0
int tty_ioctl(struct inode * inode, struct file * file,
	unsigned int cmd, unsigned long arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	struct tty_struct * termios_tty;
	pid_t pgrp;
	int dev;
	int termios_dev;
	int retval;

	if (MAJOR(file->f_rdev) != TTY_MAJOR) {
		printk("tty_ioctl: tty pseudo-major != TTY_MAJOR\n");
		return -EINVAL;
	}
	dev = MINOR(file->f_rdev);
	tty = TTY_TABLE(dev);
	if (!tty)
		return -EINVAL;
	if (IS_A_PTY(dev))
		other_tty = tty_table[PTY_OTHER(dev)];
	else
		other_tty = NULL;
	if (IS_A_PTY_MASTER(dev)) {
		termios_tty = other_tty;
		termios_dev = PTY_OTHER(dev);
	} else {
		termios_tty = tty;
		termios_dev = dev;
	}
	switch (cmd) {
		case TCGETS:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct termios));
			if (retval)
				return retval;
			memcpy_tofs((struct termios *) arg,
				    termios_tty->termios,
				    sizeof (struct termios));
			return 0;
		case TCSETSF:
		case TCSETSW:
		case TCSETS:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if (cmd == TCSETSF || cmd == TCSETSW) {
				if (cmd == TCSETSF)
					flush_input(termios_tty);
				wait_until_sent(termios_tty, 0);
			}
			return set_termios(termios_tty, (struct termios *) arg,
					   termios_dev);
		case TCGETA:
			return get_termio(termios_tty,(struct termio *) arg);
		case TCSETAF:
		case TCSETAW:
		case TCSETA:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if (cmd == TCSETAF || cmd == TCSETAW) {
				if (cmd == TCSETAF)
					flush_input(termios_tty);
				wait_until_sent(termios_tty, 0);
			}
			return set_termio(termios_tty, (struct termio *) arg,
					  termios_dev);
		case TCXONC:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			switch (arg) {
			case TCOOFF:
				stop_tty(tty);
				break;
			case TCOON:
				start_tty(tty);
				break;
			case TCIOFF:
				if (STOP_CHAR(tty) != __DISABLED_CHAR)
					put_tty_queue(STOP_CHAR(tty),
						      &tty->write_q);
				break;
			case TCION:
				if (START_CHAR(tty) != __DISABLED_CHAR)
					put_tty_queue(START_CHAR(tty),
						      &tty->write_q);
				break;
			default:
				return -EINVAL;
			}
			return 0;
		case TCFLSH:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			switch (arg) {
			case TCIFLUSH:
				flush_input(tty);
				break;
			case TCIOFLUSH:
				flush_input(tty);
				/* fall through */
			case TCOFLUSH:
				flush_output(tty);
				break;
			default:
				return -EINVAL;
			}
			return 0;
		case TIOCEXCL:
			set_bit(TTY_EXCLUSIVE, &tty->flags);
			return 0;
		case TIOCNXCL:
			clear_bit(TTY_EXCLUSIVE, &tty->flags);
			return 0;
		case TIOCSCTTY:
			if (current->leader &&
			    (current->session == tty->session))
				return 0;
			/*
			 * The process must be a session leader and
			 * not have a controlling tty already.
			 */
			if (!current->leader || (current->tty >= 0))
				return -EPERM;
			if (tty->session > 0) {
				/*
				 * This tty is already the controlling
				 * tty for another session group!
				 */
				if ((arg == 1) && suser()) {
					/*
					 * Steal it away
					 */
					struct task_struct *p;

					for_each_task(p)
						if (p->tty == dev)
							p->tty = -1;
				} else
					return -EPERM;
			}
			current->tty = dev;
			tty->session = current->session;
			tty->pgrp = current->pgrp;
			return 0;
		case TIOCGPGRP:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (pid_t));
			if (retval)
				return retval;
			if (current->tty != termios_dev)
				return -ENOTTY;
			put_fs_long(termios_tty->pgrp, (pid_t *) arg);
			return 0;
		case TIOCSPGRP:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if ((current->tty < 0) ||
			    (current->tty != termios_dev) ||
			    (termios_tty->session != current->session))
				return -ENOTTY;
			pgrp = get_fs_long((pid_t *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			termios_tty->pgrp = pgrp;
			return 0;
		case TIOCOUTQ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			put_fs_long(CHARS(&tty->write_q),
				    (unsigned long *) arg);
			return 0;
		case TIOCINQ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			if (L_ICANON(tty))
				put_fs_long(inq_canon(tty),
					(unsigned long *) arg);
			else
				put_fs_long(CHARS(&tty->secondary),
					(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			if ((current->tty != dev) && !suser())
				return -EPERM;
			retval = verify_area(VERIFY_READ, (void *) arg, 1);
			if (retval)
				return retval;
			put_tty_queue(get_fs_byte((char *) arg), &tty->read_q);
			TTY_READ_FLUSH(tty);
			return 0;
		case TIOCGWINSZ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct winsize));
			if (retval)
				return retval;
			memcpy_tofs((struct winsize *) arg, &tty->winsize,
				    sizeof (struct winsize));
			return 0;
		case TIOCSWINSZ:
			if (IS_A_PTY_MASTER(dev))
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
#ifdef CONFIG_SELECTION
				case 2:
					return set_selection(arg);
				case 3:
					return paste_selection(tty);
				case 4:
					unblank_screen();
					return 0;
#endif /* CONFIG_SELECTION */
				default: 
					return -EINVAL;
			}
		case TIOCCONS:
			if (IS_A_CONSOLE(dev)) {
				if (!suser())
					return -EPERM;
				redirect = NULL;
				return 0;
			}
			if (redirect)
				return -EBUSY;
			if (!suser())
				return -EPERM;
			if (IS_A_PTY_MASTER(dev))
				redirect = other_tty;
			else if (IS_A_PTY_SLAVE(dev))
				redirect = tty;
			else
				return -ENOTTY;
			return 0;
		case FIONBIO:
			arg = get_fs_long((unsigned long *) arg);
			if (arg)
				file->f_flags |= O_NONBLOCK;
			else
				file->f_flags &= ~O_NONBLOCK;
			return 0;
		case TIOCNOTTY:
			if (current->tty != dev)
				return -ENOTTY;
			if (current->leader)
				disassociate_ctty(0);
			current->tty = -1;
			return 0;
		case TIOCGETD:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			put_fs_long(tty->disc, (unsigned long *) arg);
			return 0;
		case TIOCSETD:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			arg = get_fs_long((unsigned long *) arg);
			return tty_set_ldisc(tty, arg);
		case TIOCGLCKTRMIOS:
			arg = get_fs_long((unsigned long *) arg);
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct termios));
			if (retval)
				return retval;
			memcpy_tofs((struct termios *) arg,
				    &termios_locked[termios_dev],
				    sizeof (struct termios));
			return 0;
		case TIOCSLCKTRMIOS:
			if (!suser())
				return -EPERM;
			arg = get_fs_long((unsigned long *) arg);
			memcpy_fromfs(&termios_locked[termios_dev],
				      (struct termios *) arg,
				      sizeof (struct termios));
			return 0;
		case TIOCPKT:
			if (!IS_A_PTY_MASTER(dev))
				return -ENOTTY;
			retval = verify_area(VERIFY_READ, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			if (get_fs_long(arg)) {
				if (!tty->packet) {
					tty->packet = 1;
					tty->link->ctrl_status = 0;
				}
			} else
				tty->packet = 0;
			return 0;
		case TCSBRK: case TCSBRKP:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			wait_until_sent(tty, 0);
			if (!tty->ioctl)
				return 0;
			tty->ioctl(tty, file, cmd, arg);
			return 0;
		default:
			if (tty->ioctl) {
				retval = (tty->ioctl)(tty, file, cmd, arg);
				if (retval != -EINVAL)
					return retval;
			}
			if (ldiscs[tty->disc].ioctl) {
				retval = (ldiscs[tty->disc].ioctl)
					(tty, file, cmd, arg);
				return retval;
			}
			return -EINVAL;
	}
Exemplo n.º 9
0
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	last_button_state=0;

	xmbstring=NULL;
	event_id=0;
	x11_window=0;
	last_click_ms=0;
	args=OS::get_singleton()->get_cmdline_args();
	current_videomode=p_desired;
	main_loop=NULL;
	last_timestamp=0;
	last_mouse_pos_valid=false;
	last_keyrelease_time=0;

	if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) {
		XInitThreads();
	}

	/** XLIB INITIALIZATION **/
	x11_display = XOpenDisplay(NULL);

	char * modifiers = XSetLocaleModifiers ("@im=none");
	ERR_FAIL_COND( modifiers == NULL );

	xim = XOpenIM (x11_display, NULL, NULL, NULL);


	if (xim == NULL) {
		WARN_PRINT("XOpenIM failed");
		xim_style=0L;
	} else {
		::XIMStyles *xim_styles=NULL;
		xim_style=0L;
		char *imvalret=NULL;
		imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
		if (imvalret != NULL || xim_styles == NULL) {
			fprintf (stderr, "Input method doesn't support any styles\n");
		}

		if (xim_styles) {
			xim_style = 0L;
			for (int i=0;i<xim_styles->count_styles;i++) {

				if (xim_styles->supported_styles[i] ==
				    (XIMPreeditNothing | XIMStatusNothing)) {

					    xim_style = xim_styles->supported_styles[i];
					    break;
				    }
			}

			XFree (xim_styles);
		}
		XFree( imvalret );
	}

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);

		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display,x11_window,&xwa);

		current_videomode.width = xwa.width;
		current_videomode.height = xwa.height;
	};
	*/

	// maybe contextgl wants to be in charge of creating the window
	//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)

	context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, false ) );
	context_gl->initialize();

	rasterizer = memnew( RasterizerGLES2 );

#endif
	visual_server = memnew( VisualServerRaster(rasterizer) );

	if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {

		visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
	}

#if 1
	// NEW_WM_API
	// borderless fullscreen window mode
	if (current_videomode.fullscreen) {
	// needed for lxde/openbox, possibly others
		Hints hints;
		Atom property;
		hints.flags = 2;
		hints.decorations = 0;
		property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
		XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
		XMapRaised(x11_display, x11_window);
		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
		XMoveResizeWindow(x11_display, x11_window, 0, 0, xwa.width, xwa.height);

		// code for netwm-compliants
		XEvent xev;
		Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
		Atom fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);

		memset(&xev, 0, sizeof(xev));
		xev.type = ClientMessage;
		xev.xclient.window = x11_window;
		xev.xclient.message_type = wm_state;
		xev.xclient.format = 32;
		xev.xclient.data.l[0] = 1;
		xev.xclient.data.l[1] = fullscreen;
		xev.xclient.data.l[2] = 0;

		XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureNotifyMask, &xev);
	}

	// disable resizable window
	if (!current_videomode.resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		XWindowAttributes xwa;
		if (current_videomode.fullscreen) {
			XGetWindowAttributes(x11_display,DefaultRootWindow(x11_display),&xwa);
		} else {
			XGetWindowAttributes(x11_display,x11_window,&xwa);
		}
		xsh->min_width = xwa.width;
		xsh->max_width = xwa.width;
		xsh->min_height = xwa.height;
		xsh->max_height = xwa.height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
		XFree(xsh);
	}
#else
	capture_idle = 0;
	minimized = false;
	maximized = false;

	if (current_videomode.fullscreen) {
		//set_wm_border(false);
		set_wm_fullscreen(true);
	}
	if (!current_videomode.resizable) {
		int screen = get_current_screen();
		Size2i screen_size = get_screen_size(screen);
		set_window_size(screen_size);
		set_window_resizable(false);
	}
#endif

	AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton();

	audio_driver_index=p_audio_driver;
	if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) {

		bool success=false;
		audio_driver_index=-1;
		for(int i=0;i<AudioDriverManagerSW::get_driver_count();i++) {
			if (i==p_audio_driver)
				continue;
			AudioDriverManagerSW::get_driver(i)->set_singleton();
			if (AudioDriverManagerSW::get_driver(i)->init()==OK) {
				success=true;
				print_line("Audio Driver Failed: "+String(AudioDriverManagerSW::get_driver(p_audio_driver)->get_name()));
				print_line("Using alternate audio driver: "+String(AudioDriverManagerSW::get_driver(i)->get_name()));
				audio_driver_index=i;
				break;
			}
		}
		if (!success) {
			ERR_PRINT("Initializing audio failed.");
		}

	}

	sample_manager = memnew( SampleManagerMallocSW );
	audio_server = memnew( AudioServerSW(sample_manager) );
	audio_server->init();
	spatial_sound_server = memnew( SpatialSoundServerSW );
	spatial_sound_server->init();
	spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
	spatial_sound_2d_server->init();


	ERR_FAIL_COND(!visual_server);
	ERR_FAIL_COND(x11_window==0);

	XSetWindowAttributes new_attr;

	new_attr.event_mask=KeyPressMask | KeyReleaseMask | ButtonPressMask |
			   ButtonReleaseMask | EnterWindowMask |
			   LeaveWindowMask | PointerMotionMask |
			   Button1MotionMask |
			   Button2MotionMask | Button3MotionMask |
			   Button4MotionMask | Button5MotionMask |
			   ButtonMotionMask | KeymapStateMask |
			   ExposureMask | VisibilityChangeMask |
			   StructureNotifyMask |
			   SubstructureNotifyMask | SubstructureRedirectMask |
			   FocusChangeMask | PropertyChangeMask |
			   ColormapChangeMask | OwnerGrabButtonMask;

	XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr);

	XClassHint* classHint;

	/* set the titlebar name */
	XStoreName(x11_display, x11_window, "Godot");

	/* set the name and class hints for the window manager to use */
	classHint = XAllocClassHint();
	if (classHint) {
		classHint->res_name = (char *)"Godot";
		classHint->res_class = (char *)"Godot";
	}
	XSetClassHint(x11_display, x11_window, classHint);
	XFree(classHint);

	wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
	XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);


	if (xim && xim_style) {

		xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL);
	} else {

		xic=NULL;
		WARN_PRINT("XCreateIC couldn't create xic");

	}

	XcursorSetTheme(x11_display,"default");
	cursor_size = XcursorGetDefaultSize(x11_display);
	cursor_theme = XcursorGetTheme(x11_display);

	if (!cursor_theme) {
		print_line("not found theme");
		cursor_theme="default";
	}

	for(int i=0;i<CURSOR_MAX;i++) {

		cursors[i]=None;
		img[i]=NULL;
	}

	current_cursor=CURSOR_ARROW;

	if (cursor_theme) {
		//print_line("cursor theme: "+String(cursor_theme));
		for(int i=0;i<CURSOR_MAX;i++) {

			static const char *cursor_file[]={
				"left_ptr",
				"xterm",
				"hand2",
				"cross",
				"watch",
				"left_ptr_watch",
				"fleur",
				"hand1",
				"X_cursor",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"size_bdiag",
				"size_fdiag",
				"hand1",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"question_arrow"
			};

			img[i] = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size);
			if (img[i]) {
				cursors[i]=XcursorImageLoadCursor(x11_display,img[i]);
				//print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i]));
			} else {
				if (OS::is_stdout_verbose())
					print_line("failed cursor: "+String(cursor_file[i]));
			}
		}
	}


	{
		Pixmap cursormask;
		 XGCValues xgc;
		 GC gc;
		 XColor col;
		 Cursor cursor;

		cursormask = XCreatePixmap(x11_display, RootWindow(x11_display,DefaultScreen(x11_display)), 1, 1, 1);
		xgc.function = GXclear;
		gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
		XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
		col.pixel = 0;
		col.red = 0;
		col.flags = 4;
		cursor = XCreatePixmapCursor(x11_display,
			      cursormask, cursormask,
			      &col, &col, 0, 0);
		 XFreePixmap(x11_display, cursormask);
		 XFreeGC(x11_display, gc);



		 if (cursor == None)
		 {
			 ERR_PRINT("FAILED CREATING CURSOR");
		 }

		 null_cursor=cursor;
	}
	set_cursor_shape(CURSOR_BUSY);


	visual_server->init();
	//
	physics_server = memnew( PhysicsServerSW );
	physics_server->init();
	//physics_2d_server = memnew( Physics2DServerSW );
	physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
	physics_2d_server->init();

	input = memnew( InputDefault );
#ifdef JOYDEV_ENABLED
	joystick = memnew( joystick_linux(input));
#endif
	_ensure_data_dir();
}
Exemplo n.º 10
0
extern int main(int argc, char **argv)
#endif
{
	struct termios mode;
	enum   output_type output_type;
	int    optc;
	int    require_set_attr;
	int    speed_was_set;
	int    verbose_output;
	int    recoverable_output;
	int    k;
	int    noargs = 1;
	char * file_name = NULL;
	int    fd;
	const char *device_name;

	output_type = changed;
	verbose_output = 0;
	recoverable_output = 0;

	/* Don't print error messages for unrecognized options.  */
	opterr = 0;

	while ((optc = getopt(argc, argv, "agF:")) != -1) {
		switch (optc) {
		case 'a':
			verbose_output = 1;
			output_type = all;
			break;

		case 'g':
			recoverable_output = 1;
			output_type = recoverable;
			break;

		case 'F':
			if (file_name)
				error_msg_and_die("only one device may be specified");
			file_name = optarg;
			break;

		default:                /* unrecognized option */
			noargs = 0;
			break;
		}

		if (noargs == 0)
			break;
	}

	if (optind < argc)
		noargs = 0;

	/* Specifying both -a and -g gets an error.  */
	if (verbose_output && recoverable_output)
		error_msg_and_die ("verbose and stty-readable output styles are mutually exclusive");

	/* Specifying any other arguments with -a or -g gets an error.  */
	if (!noargs && (verbose_output || recoverable_output))
		error_msg_and_die ("modes may not be set when specifying an output style");

	/* FIXME: it'd be better not to open the file until we've verified
	   that all arguments are valid.  Otherwise, we could end up doing
	   only some of the requested operations and then failing, probably
	   leaving things in an undesirable state.  */

	if (file_name) {
		int fdflags;

		device_name = file_name;
		fd = open(device_name, O_RDONLY | O_NONBLOCK);
		if (fd < 0)
			perror_msg_and_die("%s", device_name);
		if ((fdflags = fcntl(fd, F_GETFL)) == -1
			|| fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
			perror_msg_and_die("%s: couldn't reset non-blocking mode",
							   device_name);
	} else {
		fd = 0;
		device_name = "standard input";
	}

	/* Initialize to all zeroes so there is no risk memcmp will report a
	   spurious difference in an uninitialized portion of the structure.  */
	memset(&mode, 0, sizeof(mode));
	if (tcgetattr(fd, &mode))
		perror_msg_and_die("%s", device_name);

	if (verbose_output || recoverable_output || noargs) {
		max_col = screen_columns();
		current_col = 0;
		display_settings(output_type, &mode, fd, device_name);
		return EXIT_SUCCESS;
	}

	speed_was_set = 0;
	require_set_attr = 0;
	k = 0;
	while (++k < argc) {
		int match_found = 0;
		int reversed = 0;
		int i;

		if (argv[k][0] == '-') {
			char *find_dev_opt;

			++argv[k];

     /* Handle "-a", "-ag", "-aF/dev/foo", "-aF /dev/foo", etc.
	Find the options that have been parsed.  This is really
	gross, but it's needed because stty SETTINGS look like options to
	getopt(), so we need to work around things in a really horrible
	way.  If any new options are ever added to stty, the short option
	MUST NOT be a letter which is the first letter of one of the
	possible stty settings.
     */
			find_dev_opt = strchr(argv[k], 'F'); /* find -*F* */
			if(find_dev_opt) {
				if(find_dev_opt[1]==0)  /* -*F   /dev/foo */
					k++;            /* skip  /dev/foo */
				continue;   /* else -*F/dev/foo - no skip */
			}
			if(argv[k][0]=='a' || argv[k][0]=='g')
				continue;
			/* Is not options - is reverse params */
			reversed = 1;
		}
		for (i = 0; i < NUM_mode_info; ++i)
			if (STREQ(argv[k], mode_info[i].name)) {
				match_found = set_mode(&mode_info[i], reversed, &mode);
				require_set_attr = 1;
				break;
			}

		if (match_found == 0 && reversed)
			error_msg_and_die("invalid argument `%s'", --argv[k]);

		if (match_found == 0)
			for (i = 0; i < NUM_control_info; ++i)
				if (STREQ(argv[k], control_info[i].name)) {
					if (k == argc - 1)
					    error_msg_and_die("missing argument to `%s'", argv[k]);
					match_found = 1;
					++k;
					set_control_char(&control_info[i], argv[k], &mode);
					require_set_attr = 1;
					break;
				}

		if (match_found == 0) {
			if (STREQ(argv[k], "ispeed")) {
				if (k == argc - 1)
				    error_msg_and_die("missing argument to `%s'", argv[k]);
				++k;
				set_speed(input_speed, argv[k], &mode);
				speed_was_set = 1;
				require_set_attr = 1;
			} else if (STREQ(argv[k], "ospeed")) {
				if (k == argc - 1)
				    error_msg_and_die("missing argument to `%s'", argv[k]);
				++k;
				set_speed(output_speed, argv[k], &mode);
				speed_was_set = 1;
				require_set_attr = 1;
			}
#ifdef TIOCGWINSZ
			else if (STREQ(argv[k], "rows")) {
				if (k == argc - 1)
				    error_msg_and_die("missing argument to `%s'", argv[k]);
				++k;
				set_window_size((int) parse_number(argv[k], stty_suffixes),
								-1, fd, device_name);
			} else if (STREQ(argv[k], "cols") || STREQ(argv[k], "columns")) {
				if (k == argc - 1)
				    error_msg_and_die("missing argument to `%s'", argv[k]);
				++k;
				set_window_size(-1,
						(int) parse_number(argv[k], stty_suffixes),
						fd, device_name);
			} else if (STREQ(argv[k], "size")) {
				max_col = screen_columns();
				current_col = 0;
				display_window_size(0, fd, device_name);
			}
#endif
#ifdef HAVE_C_LINE
			else if (STREQ(argv[k], "line")) {
				if (k == argc - 1)
					error_msg_and_die("missing argument to `%s'", argv[k]);
				++k;
				mode.c_line = parse_number(argv[k], stty_suffixes);
				require_set_attr = 1;
			}
#endif
			else if (STREQ(argv[k], "speed")) {
				max_col = screen_columns();
				display_speed(&mode, 0);
			} else if (recover_mode(argv[k], &mode) == 1)
				require_set_attr = 1;
			else if (string_to_baud(argv[k]) != (speed_t) - 1) {
				set_speed(both_speeds, argv[k], &mode);
				speed_was_set = 1;
				require_set_attr = 1;
			} else
				error_msg_and_die("invalid argument `%s'", argv[k]);
		}
	}

	if (require_set_attr) {
		struct termios new_mode;

		if (tcsetattr(fd, TCSADRAIN, &mode))
			perror_msg_and_die("%s", device_name);

		/* POSIX (according to Zlotnick's book) tcsetattr returns zero if
		   it performs *any* of the requested operations.  This means it
		   can report `success' when it has actually failed to perform
		   some proper subset of the requested operations.  To detect
		   this partial failure, get the current terminal attributes and
		   compare them to the requested ones.  */

		/* Initialize to all zeroes so there is no risk memcmp will report a
		   spurious difference in an uninitialized portion of the structure.  */
		memset(&new_mode, 0, sizeof(new_mode));
		if (tcgetattr(fd, &new_mode))
			perror_msg_and_die("%s", device_name);

		/* Normally, one shouldn't use memcmp to compare structures that
		   may have `holes' containing uninitialized data, but we have been
		   careful to initialize the storage of these two variables to all
		   zeroes.  One might think it more efficient simply to compare the
		   modified fields, but that would require enumerating those fields --
		   and not all systems have the same fields in this structure.  */

		if (memcmp(&mode, &new_mode, sizeof(mode)) != 0) {
#ifdef CIBAUD
			/* SunOS 4.1.3 (at least) has the problem that after this sequence,
			   tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2);
			   sometimes (m1 != m2).  The only difference is in the four bits
			   of the c_cflag field corresponding to the baud rate.  To save
			   Sun users a little confusion, don't report an error if this
			   happens.  But suppress the error only if we haven't tried to
			   set the baud rate explicitly -- otherwise we'd never give an
			   error for a true failure to set the baud rate.  */

			new_mode.c_cflag &= (~CIBAUD);
			if (speed_was_set || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif
				error_msg_and_die ("%s: unable to perform all requested operations",
					 device_name);
		}
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 11
0
static void
set_window_size(int fd, const struct window_size* ws)
{
    int ret;
    struct winsize wz = {
        .ws_row = ws->row,
        .ws_col = ws->col,
        .ws_xpixel = ws->xpixel,
        .ws_ypixel = ws->ypixel,
    };

    do {
        ret = ioctl(fd, TIOCSWINSZ, &wz);
    } while (ret == -1 && errno == EINTR);

    dbg("TIOCSWINSZ(%ux%u): %d", wz.ws_row, wz.ws_col, ret);
}

struct stub {
    struct fb_adb_sh sh;
    struct child* child;
};

static void
stub_process_msg(struct fb_adb_sh* sh, struct msg mhdr)
{
    if (mhdr.type == MSG_WINDOW_SIZE) {
        struct msg_window_size m;
        read_cmdmsg(sh, mhdr, &m, sizeof (m));
        dbgmsg(&m.msg, "recv");
        struct stub* stub = (struct stub*) sh;
        if (stub->child->pty_master)
            set_window_size(stub->child->pty_master->fd, &m.ws);

        return;
    }

    fb_adb_sh_process_msg(sh, mhdr);
}

static void
setup_pty(int master, int slave, void* arg)
{
    struct msg_shex_hello* shex_hello = arg;
    char* hello_end = (char*) shex_hello + shex_hello->msg.size;
    struct termios attr = { 0 };
    xtcgetattr(slave, &attr);
    if (shex_hello->ispeed)
        cfsetispeed(&attr, shex_hello->ispeed);
    if (shex_hello->ospeed)
        cfsetospeed(&attr, shex_hello->ospeed);

    const struct termbit* tb = &termbits[0];
    const struct termbit* tb_end = tb + nr_termbits;
    struct term_control* tc = &shex_hello->tctl[0];

    while ((char*)(tc+1) <= hello_end && tb < tb_end) {
        int cmp = strncmp(tc->name, tb->name, sizeof (tc->name));
        if (cmp < 0) {
            dbg("tc not present: %.*s", (int) sizeof (tc->name), tc->name);
            tc++;
            continue;
        }

        if (cmp > 0) {
            dbg("tc not sent: %s", tb->name);
            tb++;
            continue;
        }

        tcflag_t* flg = NULL;
        if (tb->thing == TERM_IFLAG) {
            flg = &attr.c_iflag;
        } else if (tb->thing == TERM_OFLAG) {
            flg = &attr.c_oflag;
        } else if (tb->thing == TERM_LFLAG) {
            flg = &attr.c_lflag;
        } else if (tb->thing == TERM_C_CC) {
            if (tc->value == shex_hello->posix_vdisable_value)
                attr.c_cc[tb->value] = _POSIX_VDISABLE;
            else
                attr.c_cc[tb->value] = tc->value;

            dbg("c_cc[%s] = %d", tb->name, tc->value);
        }

        if (flg) {
            if (tc->value) {
                dbg("pty %s: set", tb->name);
                *flg |= tb->value;
            } else {
                dbg("pty %s: reset", tb->name);
                *flg &= ~tb->value;
            }
        }

        tc++;
        tb++;
    }

    xtcsetattr(slave, &attr);
    if (shex_hello->have_ws) {
        dbg("ws %ux%u (%ux%u)",
            shex_hello->ws.row,
            shex_hello->ws.col,
            shex_hello->ws.xpixel,
            shex_hello->ws.ypixel);
        set_window_size(master, &shex_hello->ws);
    }
}

static char**
read_child_arglist(size_t expected)
{
    char** argv;

    if (expected >= SIZE_MAX / sizeof (*argv))
        die(EFBIG, "too many arguments");

    argv = xalloc(sizeof (*argv) * (1+expected));
    for (size_t argno = 0; argno < expected; ++argno) {
        SCOPED_RESLIST(rl_read_arg);
        struct msg_cmdline_argument* m;
        struct msg* mhdr = read_msg(0, read_all_adb_encoded);
        reslist_pop_nodestroy(rl_read_arg);

        const char* argval;
        size_t arglen;

        if (mhdr->type == MSG_CMDLINE_ARGUMENT) {
            m = (struct msg_cmdline_argument*) mhdr;
            if (mhdr->size < sizeof (*m))
                die(ECOMM,
                    "bad handshake: MSG_CMDLINE_ARGUMENT size %u < %u",
                    (unsigned) mhdr->size,
                    (unsigned) sizeof (*m));

            argval = m->value;
            arglen = m->msg.size - sizeof (*m);
        } else if (mhdr->type == MSG_CMDLINE_DEFAULT_SH ||
                   mhdr->type == MSG_CMDLINE_DEFAULT_SH_LOGIN)
        {
            argval = getenv("SHELL");
            if (argval == NULL)
                argval = DEFAULT_SHELL;

            if (mhdr->type == MSG_CMDLINE_DEFAULT_SH_LOGIN)
                argval = xaprintf("-%s", argval);

            arglen = strlen(argval);
        } else {
            die(ECOMM,
                "bad handshake: unknown init msg s=%u t=%u",
                (unsigned) mhdr->size, (unsigned) mhdr->type);
        }

        argv[argno] = xalloc(arglen + 1);
        memcpy(argv[argno], argval, arglen);
        argv[argno][arglen] = '\0';
    }

    argv[expected] = NULL;
    return argv;
}
Exemplo n.º 12
0
int stty_main(int argc UNUSED_PARAM, char **argv)
{
	struct termios mode;
	void (*output_func)(const struct termios *, int);
	const char *file_name = NULL;
	int display_all = 0;
	int stty_state;
	int k;

	INIT_G();

	stty_state = STTY_noargs;
	output_func = do_display;

	/* First pass: only parse/verify command line params */
	k = 0;
	while (argv[++k]) {
		const struct mode_info *mp;
		const struct control_info *cp;
		const char *arg = argv[k];
		const char *argnext = argv[k+1];
		int param;

		if (arg[0] == '-') {
			int i;
			mp = find_mode(arg+1);
			if (mp) {
				if (!(mp->flags & REV))
					goto invalid_argument;
				stty_state &= ~STTY_noargs;
				continue;
			}
			/* It is an option - parse it */
			i = 0;
			while (arg[++i]) {
				switch (arg[i]) {
				case 'a':
					stty_state |= STTY_verbose_output;
					output_func = do_display;
					display_all = 1;
					break;
				case 'g':
					stty_state |= STTY_recoverable_output;
					output_func = display_recoverable;
					break;
				case 'F':
					if (file_name)
						bb_error_msg_and_die("only one device may be specified");
					file_name = &arg[i+1]; /* "-Fdevice" ? */
					if (!file_name[0]) { /* nope, "-F device" */
						int p = k+1; /* argv[p] is argnext */
						file_name = argnext;
						if (!file_name)
							bb_error_msg_and_die(bb_msg_requires_arg, "-F");
						/* remove -F param from arg[vc] */
						while (argv[p]) {
							argv[p] = argv[p+1];
							++p;
						}
					}
					goto end_option;
				default:
					goto invalid_argument;
				}
			}
 end_option:
			continue;
		}

		mp = find_mode(arg);
		if (mp) {
			stty_state &= ~STTY_noargs;
			continue;
		}

		cp = find_control(arg);
		if (cp) {
			if (!argnext)
				bb_error_msg_and_die(bb_msg_requires_arg, arg);
			/* called for the side effect of xfunc death only */
			set_control_char_or_die(cp, argnext, &mode);
			stty_state &= ~STTY_noargs;
			++k;
			continue;
		}

		param = find_param(arg);
		if (param & param_need_arg) {
			if (!argnext)
				bb_error_msg_and_die(bb_msg_requires_arg, arg);
			++k;
		}

		switch (param) {
#ifdef __linux__
		case param_line:
# ifndef TIOCGWINSZ
			xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes);
			break;
# endif /* else fall-through */
#endif
#ifdef TIOCGWINSZ
		case param_rows:
		case param_cols:
		case param_columns:
			xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes);
			break;
		case param_size:
#endif
		case param_speed:
			break;
		case param_ispeed:
			/* called for the side effect of xfunc death only */
			set_speed_or_die(input_speed, argnext, &mode);
			break;
		case param_ospeed:
			/* called for the side effect of xfunc death only */
			set_speed_or_die(output_speed, argnext, &mode);
			break;
		default:
			if (recover_mode(arg, &mode) == 1) break;
			if (tty_value_to_baud(xatou(arg)) != (speed_t) -1) break;
 invalid_argument:
			bb_error_msg_and_die("invalid argument '%s'", arg);
		}
		stty_state &= ~STTY_noargs;
	}

	/* Specifying both -a and -g is an error */
	if ((stty_state & (STTY_verbose_output | STTY_recoverable_output)) ==
		(STTY_verbose_output | STTY_recoverable_output)
	) {
		bb_error_msg_and_die("-a and -g are mutually exclusive");
	}
	/* Specifying -a or -g with non-options is an error */
	if ((stty_state & (STTY_verbose_output | STTY_recoverable_output))
	 && !(stty_state & STTY_noargs)
	) {
		bb_error_msg_and_die("modes may not be set when -a or -g is used");
	}

	/* Now it is safe to start doing things */
	if (file_name) {
		G.device_name = file_name;
		xmove_fd(xopen_nonblocking(G.device_name), STDIN_FILENO);
		ndelay_off(STDIN_FILENO);
	}

	/* Initialize to all zeroes so there is no risk memcmp will report a
	   spurious difference in an uninitialized portion of the structure */
	memset(&mode, 0, sizeof(mode));
	if (tcgetattr(STDIN_FILENO, &mode))
		perror_on_device_and_die("%s");

	if (stty_state & (STTY_verbose_output | STTY_recoverable_output | STTY_noargs)) {
		G.max_col = get_terminal_width(STDOUT_FILENO);
		output_func(&mode, display_all);
		return EXIT_SUCCESS;
	}

	/* Second pass: perform actions */
	k = 0;
	while (argv[++k]) {
		const struct mode_info *mp;
		const struct control_info *cp;
		const char *arg = argv[k];
		const char *argnext = argv[k+1];
		int param;

		if (arg[0] == '-') {
			mp = find_mode(arg+1);
			if (mp) {
				set_mode(mp, 1 /* reversed */, &mode);
				stty_state |= STTY_require_set_attr;
			}
			/* It is an option - already parsed. Skip it */
			continue;
		}

		mp = find_mode(arg);
		if (mp) {
			set_mode(mp, 0 /* non-reversed */, &mode);
			stty_state |= STTY_require_set_attr;
			continue;
		}

		cp = find_control(arg);
		if (cp) {
			++k;
			set_control_char_or_die(cp, argnext, &mode);
			stty_state |= STTY_require_set_attr;
			continue;
		}

		param = find_param(arg);
		if (param & param_need_arg) {
			++k;
		}

		switch (param) {
#ifdef __linux__
		case param_line:
			mode.c_line = xatoul_sfx(argnext, stty_suffixes);
			stty_state |= STTY_require_set_attr;
			break;
#endif
#ifdef TIOCGWINSZ
		case param_cols:
		case param_columns:
			set_window_size(-1, xatoul_sfx(argnext, stty_suffixes));
			break;
		case param_size:
			display_window_size(0);
			break;
		case param_rows:
			set_window_size(xatoul_sfx(argnext, stty_suffixes), -1);
			break;
#endif
		case param_speed:
			display_speed(&mode, 0);
			break;
		case param_ispeed:
			set_speed_or_die(input_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		case param_ospeed:
			set_speed_or_die(output_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		default:
			if (recover_mode(arg, &mode) == 1)
				stty_state |= STTY_require_set_attr;
			else /* true: if (tty_value_to_baud(xatou(arg)) != (speed_t) -1) */{
				set_speed_or_die(both_speeds, arg, &mode);
				stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			} /* else - impossible (caught in the first pass):
				bb_error_msg_and_die("invalid argument '%s'", arg); */
		}
	}

	if (stty_state & STTY_require_set_attr) {
		struct termios new_mode;

		if (tcsetattr(STDIN_FILENO, TCSADRAIN, &mode))
			perror_on_device_and_die("%s");

		/* POSIX (according to Zlotnick's book) tcsetattr returns zero if
		   it performs *any* of the requested operations.  This means it
		   can report 'success' when it has actually failed to perform
		   some proper subset of the requested operations.  To detect
		   this partial failure, get the current terminal attributes and
		   compare them to the requested ones */

		/* Initialize to all zeroes so there is no risk memcmp will report a
		   spurious difference in an uninitialized portion of the structure */
		memset(&new_mode, 0, sizeof(new_mode));
		if (tcgetattr(STDIN_FILENO, &new_mode))
			perror_on_device_and_die("%s");

		if (memcmp(&mode, &new_mode, sizeof(mode)) != 0) {
/*
 * I think the below chunk is not necessary on Linux.
 * If you are deleting it, also delete STTY_speed_was_set bit -
 * it is only ever checked here.
 */
#if 0 /* was "if CIBAUD" */
			/* SunOS 4.1.3 (at least) has the problem that after this sequence,
			   tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2);
			   sometimes (m1 != m2).  The only difference is in the four bits
			   of the c_cflag field corresponding to the baud rate.  To save
			   Sun users a little confusion, don't report an error if this
			   happens.  But suppress the error only if we haven't tried to
			   set the baud rate explicitly -- otherwise we'd never give an
			   error for a true failure to set the baud rate */

			new_mode.c_cflag &= (~CIBAUD);
			if ((stty_state & STTY_speed_was_set)
			 || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif
				perror_on_device_and_die("%s: cannot perform all requested operations");
		}
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 13
0
int main(int argc, char **argv)
{
   set_window_size(100, 100);
   return run(argc, argv, init, reshape,
              draw, 0);
}
Exemplo n.º 14
0
static LRESULT CALLBACK
startup_wnd_proc(
	HWND		hWnd,
	UINT		uMsg,
	WPARAM		wParam,
	LPARAM		lParam)
{
	MSG				msg;
	Sint32			screenType;
	Sint32			drawMode;
	Sint32			drawMethod;
	Sint32			vsync;
	Sint32			psgType;
	Sint32			soundBuffer;

	switch (uMsg)
	{
	case WM_CREATE:
		EnableWindow(WINMAIN_GetHwnd(), FALSE);//メインウィンドウを無効化してモーダルに。
		_hFontB = CreateFont(  0,						// 高さ。0 = デフォルト
		                       0,						// 幅。0なら高さに合った幅
    		                   0,						// 角度
        		               0,						// ベースラインとの角度
            		           FW_NORMAL,				// 太さ
                		       FALSE,					// イタリック
	                    	   FALSE,					// アンダーライン
		                       FALSE,					// 打ち消し線
    		                   0,						// 日本語を取り扱うときはSHIFTJIS_CHARSETにする。
        		               0,						// 出力精度
            		           0,						// クリッピング精度
                		       0,						// 出力品質
                    		   0,						// ピッチとファミリー
		                       ""						// 書体名
							); //英語のデフォルトフォントに設定
		_FontWidth	= get_font_width(hWnd);
		_FontHeight = get_font_height(hWnd);
		set_window_size(hWnd);
		break;

	case WM_PAINT:
		update_window(hWnd);
		break;

	case WM_COMMAND:
		switch(LOWORD(wParam))
		{
			case BUTTON_CDROM:
				_CDorHu = 1; //戻り値を設定
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				break;
			case BUTTON_CUE:
				_CDorHu = 2; //戻り値を設定
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				break;
			case BUTTON_HUCARD:
				_CDorHu = 3; //戻り値を設定
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				break;
			case BUTTON_REPLAY:
				_CDorHu = 4; //戻り値を設定
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				break;
			case BUTTON_OPTION:
				soundBuffer = 0; //全項目の値が設定されたかどうかの判断にも使用。
				OPTION_Init(_hInstance, &screenType, &drawMode, &drawMethod, &vsync, &psgType, &soundBuffer); //Optionウィンドウを表示
				//メッセージループ
				while (soundBuffer == 0) //ダイアログが結果を返すまでループ
				{ 
					GetMessage(&msg ,NULL, 0, 0);
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
				//Ok(SET)ボタンが押されていた場合、スクリーン設定を変更する。
				if (screenType > 0)
				{
					switch (screenType)
					{
						case 1:	APP_SetStartFullScreen(FALSE); break;
						case 2:
							APP_SetMagnification(2); //x2倍に設定
							APP_SetStartFullScreen(FALSE);
							break;
						case 3:
							APP_SetMagnification(3); //x3倍に設定
							APP_SetStartFullScreen(FALSE);
							break;
						case 4:
							APP_SetMagnification(4); //x4倍に設定
							APP_SetStartFullScreen(FALSE);
							break;
						case 5:	APP_SetStartFullScreen(TRUE); break;
						case 6:
							APP_SetFullScreen640(); //640x480に設定
							APP_SetStartFullScreen(TRUE);
							break;
					}
				}
				//Ok(SET)ボタンが押されていた場合、DrawMode設定を変更する。
				if (drawMode > 0)
				{
					switch (drawMode)
					{
						case 1: APP_SetScanLineType(1,TRUE); break;
						case 2: APP_SetScanLineType(4,TRUE); break;
						case 3: APP_SetScanLineType(2,TRUE); break;
						case 4: APP_SetScanLineType(0,TRUE); break;
					}
				}
				//Ok(SET)ボタンが押されていた場合、DrawMethod設定を変更する。
				if (drawMethod > 0)
				{
					APP_SetDrawMethod(drawMethod);
				}
				//Ok(SET)ボタンが押されていた場合、V-Sync設定を変更する。
				if (screenType > 0)
				{
					if (vsync == 2)
						APP_SetSyncTo60HzScreen(FALSE);
					else //==1
						APP_SetSyncTo60HzScreen(TRUE);
				}
				//Ok(SET)ボタンが押されていた場合、PSGクォリティ設定を変更する。
				if (psgType > 0)
				{
					if (psgType == 3)
						APP_SetPsgQuality(1);
					else if (psgType == 2)
						APP_SetPsgQuality(2);
					else //==1
						APP_SetPsgQuality(4);
				}
				//Ok(SET)ボタンが押されていた場合、PSGクォリティ設定を変更する。
				if (soundBuffer > 0)
				{
					switch (soundBuffer)
					{
						case  1: APP_SetSoundBufferSize(1024); break;
						case  2: APP_SetSoundBufferSize(1152); break;
						case  3: APP_SetSoundBufferSize(1280); break;
						case  4: APP_SetSoundBufferSize(1408); break;
						case  5: APP_SetSoundBufferSize(1536); break;
						case  7: APP_SetSoundBufferSize(1792); break;
						case  8: APP_SetSoundBufferSize(2048); break;
						case  9: APP_SetSoundBufferSize(2176); break;
						case 10: APP_SetSoundBufferSize(2304); break;
						case 11: APP_SetSoundBufferSize(2560); break;
						case 12: APP_SetSoundBufferSize(3072); break;
						default: //==6
							APP_SetSoundBufferSize(1664); break;
					}
				}
				break;
		}
		break;

	case WM_KEYDOWN:
		if (wParam == VK_ESCAPE)
			PostMessage(hWnd, WM_CLOSE, 0, 0);
		if ((wParam == 'C')||(wParam == VK_RETURN)) //「C」キーまたは 「Enter」キー
		{
			_CDorHu = 1; //戻り値を設定
			PostMessage(hWnd, WM_CLOSE, 0, 0);
		}
		if (wParam == 'P') //「P」キー
		{
			_CDorHu = 2; //戻り値を設定
			PostMessage(hWnd, WM_CLOSE, 0, 0);
		}
		if ((wParam == 'H')||(wParam == 'O')||(wParam == VK_SPACE)) //「H」キー「O」キーまたは スペースキー
		{
			_CDorHu = 3; //戻り値を設定
			PostMessage(hWnd, WM_CLOSE, 0, 0);
		}
		if (wParam == 'R') //「R」キー
		{
			_CDorHu = 4; //戻り値を設定
			PostMessage(hWnd, WM_CLOSE, 0, 0);
		}
		break;

	case WM_CLOSE:
		STARTUP_Deinit();
		return 0;
	}

	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    set_window_size(64, 64);
    return run(argc, argv, init, reshape,
               draw, key_press);
}
Exemplo n.º 16
0
int main( int argc, char* args[] ) 
{
	
	// this is the last time (SDL_Getticks()) that beasts were evaluated
	int beastLastEval=0;
	// this is how many times per second the beasts should be evaluated
	int beastEvalsPerSec = 30;
	
	paused = 0;
	//get a random seed.
	sgenrand(time(NULL));
	
    //mouse variables and cell types
    int x, y, sleepTime = 0, countVar = 0;
	
    //mouse is held variables
    int mouseStatusLeft = 0, mouseStatusRight = 0;
    
    // these keep track of the position of the right mouse button when it was clicked down
    int mouseRDx;
	int mouseRDy;
	
	//make sure the program waits for a quit
	int quit = false;
	
	init_mats();
	init_graphics();
	init_controls();
	
    //Initialize
    if( init() == false ) return 1;
	
    //Load the files
    if( load_files() == false ) return 2;
	
    //Update the screen
    if( SDL_Flip( screen ) == -1 ) return 3;
    
    gen_world();
	
	// these keep track of the WASD keys.
	int keyw=0, keya=0, keys=0, keyd=0;
	int key; // used as a stand-int for the verbose event.key.keysym.sym
	bool keyF3=true;
	
	//these are used to calculating and keeping track of the FPS
	int ticksSinceLastFPSUpdate = 0;
	int cumulativeFrames = 0;
	int currentTicks = 0;
	
	SDL_Rect screenRect;
	screenRect.x = screenRect.y = 0;
	screenRect.w = SCREEN_WIDTH;
	screenRect.h = SCREEN_HEIGHT;
	
	
    //While the user hasn't quit
    while(1){
		
    	//While there's an event to handle
    	while( SDL_PollEvent( &event ) ){
			
    		//If the user has Xed out the window
    		if( event.type == SDL_QUIT || quit == true ){
				//Quit the program
				clean_up();
				return 0;
			}
			
            if( event.type == SDL_MOUSEBUTTONDOWN ){						/// mouse down
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 1;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 1;
                    mouseRDx = x;
                    mouseRDy = y;
                }
                
                else if( event.button.button == SDL_BUTTON_WHEELUP )
					;//zoom_in(x,y);
				else if( event.button.button == SDL_BUTTON_WHEELDOWN )
					;//zoom_out(x,y);
				
            }
            else if(event.type == SDL_MOUSEBUTTONUP){						/// mouse up
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 0;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 0;
                }
            }
            else if( event.type == SDL_MOUSEMOTION ){						/// mouse motion
				x = event.motion.x;
				y = event.motion.y;
				/*
				// if the alt key (camera panning key) is down and the coordinates have changed, then let the screen be panned!
				if(alt && x != mouse_x_when_pan && y != mouse_y_when_pan){
					// this adjusts the x-axis camera (this scales with the CELL_SIZE)
					camera_x += (x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE;
					camera_y += (y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE;
					//calculate the remainders of the mouse motion.
					// these values represent the motion of the mouse that is not utilized by the discrete nature of the operation on the camera_x and camera_y values.
					remainder_panning_motion_x = (x-mouse_x_when_pan+remainder_panning_motion_x) - (int)((x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE)*CELL_SIZE;
					remainder_panning_motion_y = (y-mouse_y_when_pan+remainder_panning_motion_y) - (int)((y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE)*CELL_SIZE;
					// make sure the camera is not out of bounds.
					verify_camera();
					
					//reset the user's curcor position to the original position the curcor was in when the user started panning the camera
					SDL_WarpMouse(mouse_x_when_pan, mouse_y_when_pan);
				}
				*/
            }
            else if(event.type == SDL_VIDEORESIZE){							/// window resize
				// don't resize the grid.
				//float new_cell_size = CELL_SIZE * event.resize.h/((float)SCREEN_HEIGHT); // adjust the pixel size.
				//if(new_cell_size - ((int)new_cell_size) >= 0.5f) CELL_SIZE = new_cell_size + 1;
				//else CELL_SIZE = new_cell_size;
				screenRect.w = SCREEN_WIDTH = event.resize.w;
				screenRect.h = SCREEN_HEIGHT = event.resize.h;
				set_window_size(event.resize.w, event.resize.h);		// set window to correct dimensions
			}
			
            if( event.type == SDL_KEYDOWN ){		///keyboard event
                key = event.key.keysym.sym;
				if     (key == controlsGame.pan[d_up])		camera_pan(d_up);		// pan up
				else if(key == controlsGame.pan[d_down])	camera_pan(d_down);		// pan down
				else if(key == controlsGame.pan[d_left])	camera_pan(d_left);		// pan left
				else if(key == controlsGame.pan[d_right])	camera_pan(d_right);	// pan right
				else if(key == controlsGame.debug)			keyF3 ^= 1;				// toggle the keyF3 state
				
			}
			if( event.type == SDL_KEYUP ){								///keyboard event
                // nothing here yet
			}
                
		
    	} // end while(event)
		//no more events to handle at the moment.
		if(mouseStatusLeft==true && beast_find_at_cell(x/CELL_SIZE+cameraX,y/CELL_SIZE+cameraY) == NULL){
			// add beast function
			struct beastData *myBeast;
			myBeast = beast_create(NULL);
			if(myBeast != NULL ){
				myBeast->x = x/CELL_SIZE + cameraX;
				myBeast->y = y/CELL_SIZE + cameraY;
			}
		}
		
		if(SDL_GetTicks()-beastLastEval > 1000/beastEvalsPerSec){
			// evaluate all beasts
			beasts_evaluate();
			beastLastEval = SDL_GetTicks();
		}
		
        // print the grid data
        print_grid(screen);
        print_beasts(screen);
        print_beasts_targets(screen);
        
        // print debugging information
        if(keyF3) print_debugging_information(screen);
        //updates the screen
        SDL_Flip( screen );
        SDL_FillRect(screen, &screenRect, 0);
        //----------------------------------------------------
		// FPS calculation and variable handling
		//----------------------------------------------------
        currentTicks = SDL_GetTicks();
        // it is officially the next second
        if(currentTicks >= ticksSinceLastFPSUpdate + 1000){
			// calculate the FPS
			FPS = cumulativeFrames;//(cumulativeFrames*1000 ) / (currentTicks-ticksSinceLastFPSUpdate);
			cumulativeFrames=0;				// reset cumulative amount of frames
			ticksSinceLastFPSUpdate = currentTicks;	// reset the last FPS update to the number of ticks now.
        }
        cumulativeFrames++;
		
    }// end while(quit == false)


    //Free the surface and quit SDL
    clean_up();

    return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
    bool fullscreen = false;

    if (SDL_Init(0) != 0){
        ERR("SDL_Init\n");
        return 1;
    }

    SDL_Window* Window = SDL_CreateWindow("SDL Nine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if (!Window) {
        ERR("SDL_CreateWindow\n");
        return 1;
    }

    d3d = SDL_Direct3DCreate9Ex(Window);
    if (!d3d) {
        ERR("X11_Direct3DCreate9\n");
        return 1;
    }

    {
        HWND FakeWnd= (HWND)Window;

        D3DDISPLAYMODEEX mode;
        D3DPRESENT_PARAMETERS d3dpp;
        fillin_present_parameters(Window, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen, d3dpp, mode);

        // create a device class using this information and the info from the d3dpp stuct
        HRESULT hr = d3d->CreateDeviceEx(D3DADAPTER_DEFAULT,
            D3DDEVTYPE_HAL,
            FakeWnd,
            D3DCREATE_HARDWARE_VERTEXPROCESSING,
            &d3dpp, &mode, 
            &d3ddev);

        if (FAILED(hr)) {
            ERR("X11_Direct3DCreate9\n");
            return 1;
        }
    }

    init_graphics();    // call the function to initialize the triangle

    Uint32 MainWindowID = SDL_GetWindowID(Window);
    bool quit = false;
    SDL_Event e;

    //While application is running
    while (!quit)
    {
        //Handle events on queue
        while (SDL_PollEvent(&e) != 0)
        {
            //User requests quit
            if (e.type == SDL_QUIT)
            {
                quit = true;
            }
            else if (e.type == SDL_WINDOWEVENT && e.window.windowID == MainWindowID)
            {
                switch (e.window.event) {
                case SDL_WINDOWEVENT_SIZE_CHANGED:
                    {
                        int width = e.window.data1;
                        int height = e.window.data2;

                        bool ok = set_window_size(Window, width, height, fullscreen);
                        if (ok)
                            load_triangle(width, height, v_buffer);
                    } break;
                }
            }
            else if (e.type == SDL_KEYDOWN && e.window.windowID == MainWindowID && e.key.keysym.sym == SDLK_F11 && e.key.state == SDL_PRESSED)
            {
                fullscreen = !fullscreen;
                bool ok = set_window_size(Window, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen);
                if (ok)
                    load_triangle(SCREEN_WIDTH, SCREEN_HEIGHT, v_buffer);
            }
        }

        //Render quad
        render_frame();
    }

    // clean up DirectX
    {
        v_buffer->Release();    // close and release the vertex buffer
        d3ddev->Release();    // close and release the 3D device
        d3d->Release();    // close and release Direct3D
    }

    SDL_Quit();

    return 0;
}
Exemplo n.º 18
0
int main( int argc, char* args[] )
{

	//get a random seed.
	srand(time(NULL));

    //mouse variables and cell types
    int x, y, sleepTime = 0, countVar = 0;

    //mouse is held variables
    int mouseStatusLeft = 0, mouseStatusRight = 0;

	//make sure the program waits for a quit
	int quit = false;

    //Initialize
    if( init() == false ) return 1;

    //Load the files
    if( load_files() == false ) return 2;

    //Update the screen
    //if( SDL_Flip( screen ) == -1 ) return 3;
    //if(SDL_RenderPresent( screen ) == -1 ) return 3;

    //initialize the cell stuff. This gets the cell system up and running. This also sets all cells to m_air and all the saturation to m_no_saturaion
    init_cell_stuff();
	
	/*
	CELL_SIZE = 4;
	int i;//
	//putting test materials into grid

    for(i=0; i<GRID_WIDTH; i++){
		if(get_rand(1,4)==1)
			grid[i+camera_x][GRID_HEIGHT-1-get_rand(7,15)+camera_y].mat = m_plant_root;
		if(get_rand(1,10)==10)
			grid[i+camera_x][camera_y+get_rand(20,35)].mat = m_spring;
		grid[i+camera_x][camera_y+get_rand(30,34)+30].mat = m_earth;
		grid[i+camera_x][camera_y+get_rand(30,34)+30].mat = m_earth;
		grid[i+camera_x][camera_y+get_rand(30,34)+30].mat = m_earth;
    }
    */
    CELL_SIZE = 8;
    sleepTime = 0;
	//int i;//
	//putting test materials into grid

    /*
    for(i=7 ; i<GRID_WIDTH ; i+=15){
		for(j=26 ; j<GRID_HEIGHT ; j+=20){
			grid[i][j].mat = m_anti_scurge;
		}
    }
    */

	//--------------------------------------
	//for(i=0 ; i<GRID_WIDTH*GRID_HEIGHT / 2 ; i++)
	//	grid[get_rand(0,GRID_WIDTH-1)][get_rand(0,GRID_HEIGHT-1)].mat = m_plant;


	//int keyw=0, keya=0, keys=0, keyd=0;
	//unsigned lastPanTime = 0;
	bool alt = 0; // this keeps track of the state of the alt key
	//these variables store the position of the user's cursor at the moment that the user decided to pan the screen
	int mouse_x_when_pan=0;
	int mouse_y_when_pan=0;
	// these are for keeping track of the motion of the mouse when the user is panning. these keep the panning from being really jumpy.
	// without them, there is a truncation error when adjusting the camera_x and camera_y materials and re-setting the mouse coordinates to its original state.
	// these keep track of the truncation error and add it to the next operation so that the mouse motion feels fluid.
	int remainder_panning_motion_x=0;
	int remainder_panning_motion_y=0;

	//last minute verification that the initial start up values for the grid size and the camera positions are valid.
	verify_grid_and_cell_size();
	verify_camera();

    //While the user hasn't quit
    while(1){

    	//While there's an event to handle
    	while( SDL_PollEvent( &event ) ){

    		//If the user has Xed out the window
    		if( event.type == SDL_QUIT || quit == true ){
				//Quit the program
				clean_up();
				return 0;
			}

            if( event.type == SDL_MOUSEBUTTONDOWN ){						/// mouse down
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 1;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 1;
                }
            }
            else if(event.type == SDL_MOUSEWHEEL){
				if(event.wheel.y > 0)
					zoom_in(x,y);
				if(event.wheel.y < 0)
					zoom_out(x,y);
			}
            else if(event.type == SDL_MOUSEBUTTONUP){						/// mouse up
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 0;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 0;
                }
            }
            else if( event.type == SDL_MOUSEMOTION ){						/// mouse motion
				x = event.motion.x;
				y = event.motion.y;
				// if the alt key (camera panning key) is down and the coordinates have changed, then let the screen be panned!
				if(alt && x != mouse_x_when_pan && y != mouse_y_when_pan){
					// this adjusts the x-axis camera (this scales with the CELL_SIZE)
					camera_x += (x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE;
					camera_y += (y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE;
					//calculate the remainders of the mouse motion.
					// these values represent the motion of the mouse that is not utilized by the discrete nature of the operation on the camera_x and camera_y values.
					remainder_panning_motion_x = (x-mouse_x_when_pan+remainder_panning_motion_x) - (int)((x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE)*CELL_SIZE;
					remainder_panning_motion_y = (y-mouse_y_when_pan+remainder_panning_motion_y) - (int)((y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE)*CELL_SIZE;
					// make sure the camera is not out of bounds.
					verify_camera();

					//reset the user's curcor position to the original position the curcor was in when the user started panning the camera
					SDL_WarpMouseInWindow(window, mouse_x_when_pan, mouse_y_when_pan);
				}
            }
            else if(event.type == SDL_WINDOWEVENT_RESIZED ){							/// window resize

				//float new_cell_size = CELL_SIZE * event.resize.h/((float)SCREEN_HEIGHT); // adjust the pixel size.
				float new_cell_size = CELL_SIZE * event.window.data1/((float)SCREEN_HEIGHT); // adjust the pixel size.
				if(new_cell_size - ((int)new_cell_size) >= 0.5f) CELL_SIZE = new_cell_size + 1;
				else CELL_SIZE = new_cell_size;
				//SCREEN_WIDTH = event.resize.w;
				//SCREEN_HEIGHT = event.resize.h;
				SCREEN_WIDTH = event.window.data1;
				SCREEN_HEIGHT = event.window.data2;
				verify_grid_and_cell_size(); // make sure the window isn't too big for the cell size

				//set_window_size(event.resize.w, event.resize.h);
				set_window_size(event.window.data1, event.window.data2);
				verify_camera();
			}

            if( event.type == SDL_KEYDOWN ){								///keyboard event
                switch( event.key.keysym.sym ){
				case SDLK_UP: break; //change block type up
				case SDLK_DOWN: break; // change block type down
				case SDLK_c: reset_cells();  break;//clear the screen
				case SDLK_p: print_saturation_data(); break; // prints the cellSat[][] array to stdout. this is for debuggin purposes.
				case SDLK_r:  randomize_grid(); break; // randomize grid
				case SDLK_LEFT: if(paused != 1) {sleepTime /= 2;} break; //speeds up the game
				case SDLK_RIGHT: if(paused != 1) {if(sleepTime == 0){sleepTime = 1;} {sleepTime *= 2;} if(sleepTime > 2000) {sleepTime = 2000;}} break; //slows down the game
				case SDLK_SPACE: if(paused == 0) {paused = 1;} else if(paused == 1) {paused = 0;} break; //pause the game
				case SDLK_ESCAPE: quit = true; // quit with escape
				case SDLK_w: gen_world(w_normal,0); break; // generate a world
				/*
				case SDLK_w: keyw=1; break; // store key state
				case SDLK_a: keya=1; break;
				case SDLK_s: keys=1; break;
				case SDLK_d: keyd=1; break;
				*/
				case SDLK_LALT:
				case SDLK_RALT:
					// store the state of the alt key.
					alt = 1;
					// turn off the cursor
					SDL_ShowCursor(SDL_DISABLE);
					// store the position of the mouse. this will allow the program to make the cursor stay stationary
					mouse_x_when_pan = x;
					mouse_y_when_pan = y;
					//reset the remainder mouse motion variables for x and y.
					remainder_panning_motion_x = 0;
					remainder_panning_motion_y = 0;
					break;
				default: break;
				}
			}
			if( event.type == SDL_KEYUP ){								///keyboard event
                switch( event.key.keysym.sym ){
				/*
				case SDLK_w: keyw=0; break;//lastPanTime=0; break; // store key state
				case SDLK_a: keya=0; break;//lastPanTime=0; break;
				case SDLK_s: keys=0; break;//lastPanTime=0; break;
				case SDLK_d: keyd=0; break;//lastPanTime=0; break;
				*/
				case SDLK_LALT:
				case SDLK_RALT:
					// show the cursor again.
					SDL_ShowCursor(SDL_ENABLE);
					alt = 0;
					break;
				default: break;
				}
			}


    	} // end while(event)
		//no more events to handle at the moment.
		/*
		//this handles time-controlled panning
		if(SDL_GetTicks() - MIN_PAN_INTERVAL > lastPanTime){
			if(keyw) pan(D_UP);
			if(keya) pan(D_LEFT);
			if(keys) pan(D_DOWN);
			if(keyd) pan(D_RIGHT);
			lastPanTime = SDL_GetTicks();
			//#if (DEBUG_GRIDSIM)
			//	printf("\nlastPanTime = %d\n", lastPanTime);
			//#endif
		}
		*/
		//checks if the mouse is held or not
        if(mouseStatusLeft == 1 && mouseModifier == 0){
			//make sure the mouse isn't inside either of the two GUIs.
			if(y >= 50 && x < SCREEN_WIDTH - 200)
            setcell(x, y, currentMat);
            }

        else if(mouseStatusRight == 1 && mouseModifier == 0){
            deletecell(x, y, currentMat);
        }

        //speed of gameplay
        countVar++;
        if(sleepTime <= 0)
        {
            sleepTime = 0;
        }

        //evealuate cells
        if(countVar >= sleepTime && paused != 1){
            evaluate_grid();
            countVar = 0;
        }

        //updates screen with cells
        print_cells();

        //displays selection gui
        selectionGUI(x, y, mouseStatusLeft);

        //displays brushes and misc gui
        brushesGUI(x, y, mouseStatusLeft);

        // If the user is not panning, then it is fine to show the cursor.
        if(!alt){
			//displays cursor
			cursorDisplay(x, y);
        }
		
		//draw_line(screen, 300, 300, x, y, 1, mats[currentMat].color);		// test the line drawing function
        
        //updates the screen
        //SDL_Flip( screen );
        //SDL_RenderPresent( screen );
		SDL_UpdateWindowSurface(window);
    }// end while(quit == false)


    //Free the surface and quit SDL
    clean_up();

    return 0;
}
int main(int argc, char **argv)
{
	FILE *input;
	FILE *repeats = 0;
	FILE *output;

	int start_x, end_x, start_y, end_y;

	debug_config(progname);
	get_options(argc, argv, progname);

	unsigned long start_mem, cand_mem, table_mem;

	input = fopen(sequence_filename, "r");
	if(!input) fatal("couldn't open %s: %s\n",sequence_filename,strerror(errno));

	if(repeat_filename) {
		repeats = fopen(repeat_filename, "r");
		if(!repeats) fatal("couldn't open %s: %s\n",repeat_filename,strerror(errno));
	}

	if(output_filename) {
		output = fopen(output_filename, "w");
	} else {
		output = stdout;
	}

	// Data is in the form:
	// >id metadata
	// data
	// >id metadata
	// data
	// >>
	// ...

	set_k(kmer_size);
	set_window_size(window_size);

	// If we only give one file, do an all vs. all
	// on them.
	if(!second_sequence_filename) {
		num_seqs = load_seqs(input);
		start_x = 0;
		end_x = num_seqs;
		start_y = 0;
		end_y = num_seqs;
	}
	// If we had two files, do not compare ones from
	// the same file to each other.
	else {
		FILE *input2 = fopen(second_sequence_filename, "r");
		if(!input2) {
			fprintf(stderr, "Could not open file %s for reading.\n", second_sequence_filename);
			exit(1);
		}
		num_seqs = load_seqs_two_files(input, &end_x, input2, &end_y);
		start_x = 0;
		start_y = end_x;
		debug(D_DEBUG,"First file contains %d sequences, stored from (%d,%d].\n", end_x, start_x, end_x);
		debug(D_DEBUG,"Second file contains %d sequences, stored from (%d,%d].\n", end_y-end_x, start_y, end_y);
	}
	fclose(input);

	debug(D_DEBUG,"Loaded %d sequences\n",num_seqs);

	init_cand_table(num_seqs * 5);
	init_mer_table(num_seqs * 5);

	if(repeats) {
		int repeat_count = init_repeat_mer_table(repeats, 2000000, 0);
		fclose(repeats);
		debug(D_DEBUG,"Loaded %d repeated mers\n", repeat_count);
	}

	if(rectangle_size == -1) {
		// Do get_mem_avail*0.95 to leave some memory for overhead
		rectangle_size = DYNAMIC_RECTANGLE_SIZE(max_mem_kb);
		debug(D_DEBUG,"Mem avail: %lu, rectangle size: %d\n",(unsigned long)MEMORY_FOR_MERS(max_mem_kb), rectangle_size);
	}

	int curr_start_x = start_x;
	int curr_start_y = start_y;

	candidate_t *output_list = 0;
	int num_in_list;

	while(curr_start_y < end_y) {
		while(curr_start_x < end_x) {
			if(start_x == start_y) {
				debug(D_DEBUG,"Loading mer table (%d,%d)\n", curr_rect_x, curr_rect_y);
			} else {
				debug(D_DEBUG,"Loading mer table for [%d,%d) and [%d,%d)\n",curr_start_x, MIN(curr_start_x + rectangle_size, end_x), curr_start_y, MIN(curr_start_y + rectangle_size, end_y));
			}

			start_mem = get_mem_usage();

			load_mer_table_subset(curr_start_x, MIN(curr_start_x + rectangle_size, end_x), curr_start_y, MIN(curr_start_y + rectangle_size, end_y), (curr_start_x == curr_start_y));

			table_mem = get_mem_usage();

			debug(D_DEBUG,"Finished loading, now generating candidates\n");
			debug(D_DEBUG,"Memory used: %lu\n", table_mem - start_mem);

			generate_candidates();
			cand_mem = get_mem_usage();

			debug(D_DEBUG,"Total candidates generated: %llu\n", (long long unsigned int) total_cand);
			debug(D_DEBUG,"Candidate memory used: %lu\n", cand_mem - table_mem);

			output_list = retrieve_candidates(&num_in_list);
			output_candidate_list(output, output_list, num_in_list);
			free(output_list);
			fflush(output);

			debug(D_DEBUG,"Now freeing\n");

			free_cand_table();
			free_mer_table();

			debug(D_DEBUG,"Successfully output and freed!\n");

			curr_rect_x++;
			curr_start_x += rectangle_size;
		}
		curr_rect_y++;
		curr_start_y += rectangle_size;
		curr_rect_x = curr_rect_y;
		if(start_y == 0) {
			curr_start_x = curr_start_y;
		} else {
			curr_start_x = start_x;
		}
	}

	fclose(output);

	return 0;
}
Exemplo n.º 20
0
    // internal initialization. performed when run is invoked
    void Raspi_App::init()
    {
        gettimeofday(&m_startTime, NULL);

        esInitContext(m_context.get());
        esCreateWindow(m_context.get(), name().c_str(),
                       ES_WINDOW_RGB | ES_WINDOW_ALPHA | ES_WINDOW_DEPTH /*| ES_WINDOW_MULTISAMPLE*/);

        // set graphical log stream
        Logger::get()->add_outstream(&m_outstream_gl);

        // version
        LOG_INFO<<"OpenGL: " << glGetString(GL_VERSION);
        LOG_INFO<<"GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION);

        set_window_size(gl::vec2(m_context->width, m_context->height));
        LOG_INFO<<"Context: " << gl::window_dimension().x << " x " << gl::window_dimension().y;

        // file search paths
        if(!args().empty()){ fs::add_search_path(fs::get_directory_part(args().front())); }
        // fs::add_search_path("./");
        fs::add_search_path("./res");
        fs::add_search_path("/usr/local/share/fonts");

        get_input_file_descriptors(&m_mouse_fd, &m_keyboard_fd, &m_touch_fd);

        m_timer_device_scan = Timer(background_queue().io_service(), [this]()
        {
            int mouse_fd = m_mouse_fd, keyboard_fd = m_keyboard_fd;
            int *mp = nullptr, *kp = nullptr;
            bool has_changed = false;

            // check for keyboard and mouse being added/removed
            auto mouse_handler = find_mouse_handler();
            auto kb_handler = find_keyboard_handler();

            if((!m_keyboard_fd && !kb_handler.empty()) ||
               (m_keyboard_fd && kb_handler.empty()))
            {
                keyboard_fd = 0;
                kp = &keyboard_fd;
                has_changed = true;
            }
            if((!m_mouse_fd && !mouse_handler.empty()) ||
               (m_mouse_fd && mouse_handler.empty()))
            {
                mouse_fd = 0;
                mp = &mouse_fd;
                has_changed = true;
            }
            if(!has_changed){ return; }

            get_input_file_descriptors(mp, kp, nullptr);
            main_queue().submit([this, mouse_fd, keyboard_fd]
            {
                if(mouse_fd && !m_mouse_fd)
                {
                    LOG_TRACE << "mouse connected";
                    m_mouse_fd = mouse_fd;
                }
                else if(!mouse_fd && m_mouse_fd)
                {
                     LOG_TRACE << "mouse disconnected";
                     close(m_mouse_fd); m_mouse_fd = 0;
                }
                if(keyboard_fd && !m_keyboard_fd)
                {
                    LOG_TRACE << "keyboard connected";
                    m_keyboard_fd = keyboard_fd;
                }
                else if(!keyboard_fd && m_keyboard_fd)
                {
                    LOG_TRACE << "keyboard disconnected";
                    close(m_keyboard_fd); m_keyboard_fd = 0;
                }
            });
        });
        m_timer_device_scan.set_periodic();
        m_timer_device_scan.expires_from_now(5.0);

        // make sure touchscreen backlight stays on
        // TODO: use timer here
        // set_lcd_backlight(true);

        // center cursor
        current_mouse_pos = gl::window_dimension() / 2.f;

        // user setup hook
        setup();
    }
Exemplo n.º 21
0
int tty_ioctl(struct inode * inode, struct file * file,
	unsigned int cmd, unsigned int arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	int pgrp;
	int dev;

	if (MAJOR(file->f_rdev) != 4) {
		printk("tty_ioctl: tty pseudo-major != 4\n");
		return -EINVAL;
	}
	dev = MINOR(file->f_rdev);
	tty = TTY_TABLE(dev);
	if (!tty)
		return -EINVAL;

	if (IS_A_PTY(dev))
		other_tty = tty_table[PTY_OTHER(dev)];
	else
		other_tty = NULL;
		
	switch (cmd) {
		case TCGETS:
			return get_termios(tty,(struct termios *) arg);
		case TCSETSF:
			flush_input(tty);
		/* fallthrough */
		case TCSETSW:
			wait_until_sent(tty);
		/* fallthrough */
		case TCSETS:
			return set_termios(tty,(struct termios *) arg, dev);
		case TCGETA:
			return get_termio(tty,(struct termio *) arg);
		case TCSETAF:
			flush_input(tty);
		/* fallthrough */
		case TCSETAW:
			wait_until_sent(tty); /* fallthrough */
		case TCSETA:
			return set_termio(tty,(struct termio *) arg, dev);
		case TCXONC:
			switch (arg) {
			case TCOOFF:
				tty->stopped = 1;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCOON:
				tty->stopped = 0;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCIOFF:
				if (STOP_CHAR(tty))
					put_tty_queue(STOP_CHAR(tty),
						      &tty->write_q);
				return 0;
			case TCION:
				if (START_CHAR(tty))
					put_tty_queue(START_CHAR(tty),
						      &tty->write_q);
				return 0;
			}
			return -EINVAL; /* not implemented */
		case TCFLSH:
			if (arg==0)
				flush_input(tty);
			else if (arg==1)
				flush_output(tty);
			else if (arg==2) {
				flush_input(tty);
				flush_output(tty);
			} else
				return -EINVAL;
			return 0;
		case TIOCEXCL:
			return -EINVAL; /* not implemented */
		case TIOCNXCL:
			return -EINVAL; /* not implemented */
		case TIOCSCTTY:
			return -EINVAL; /* set controlling term NI */
		case TIOCGPGRP:
			verify_area((void *) arg,4);
			put_fs_long(tty->pgrp,(unsigned long *) arg);
			return 0;
		case TIOCSPGRP:
			if ((current->tty < 0) ||
			    (current->tty != dev) ||
			    (tty->session != current->session))
				return -ENOTTY;
			pgrp=get_fs_long((unsigned long *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			tty->pgrp = pgrp;			
			return 0;
		case TIOCOUTQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(&tty->write_q),
				    (unsigned long *) arg);
			return 0;
		case TIOCINQ:
			verify_area((void *) arg,4);
			if (L_CANON(tty) && !tty->secondary.data)
				put_fs_long(0, (unsigned long *) arg);
			else
				put_fs_long(CHARS(&tty->secondary),
					(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			return -EINVAL; /* not implemented */
		case TIOCGWINSZ:
			return get_window_size(tty,(struct winsize *) arg);
		case TIOCSWINSZ:
			if (IS_A_PTY_MASTER(dev))
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCGSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCSSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
				default: 
					return -EINVAL;
			}
		case TIOCCONS:
			if (!IS_A_PTY(dev))
				return -EINVAL;
			if (redirect)
				return -EBUSY;
			if (!suser())
				return -EPERM;
			if (IS_A_PTY_MASTER(dev))
				redirect = other_tty;
			else
				redirect = tty;
			return 0;
		case FIONBIO:
			if (arg)
				file->f_flags |= O_NONBLOCK;
			else
				file->f_flags &= ~O_NONBLOCK;
			return 0;
		case TIOCNOTTY:
			if (MINOR(file->f_rdev) != current->tty)
				return -EINVAL;
			current->tty = -1;
			if (current->leader) {
				if (tty->pgrp > 0)
					kill_pg(tty->pgrp, SIGHUP, 0);
				tty->pgrp = -1;
				tty->session = 0;
			}
			return 0;

	       case TIOCPKT:
			{
			   int on;
			   if (!IS_A_PTY_MASTER(dev))
			     return (-EINVAL);
			   verify_area ((unsigned long *)arg, sizeof (int));
			   on=get_fs_long ((unsigned long *)arg);
			   if (on )
			     tty->packet = 1;
			   else
			     tty->packet = 0;
			   return (0);
			}

		default:
			if (tty->ioctl)
				return (tty->ioctl)(tty, file, cmd, arg);
			else
				return -EINVAL;
	}
}
Exemplo n.º 22
0
int tty_ioctl(int dev, int cmd, int arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	int pgrp;

	if (MAJOR(dev) == 5) {
		dev = current->tty;
		if (dev<0)
			return -EINVAL;
	} else
		dev=MINOR(dev);
	tty = tty_table + (dev ? ((dev < 64)? dev-1:dev) : fg_console);

	if (IS_A_PTY(dev))
		other_tty = tty_table + PTY_OTHER(dev);
	else
		other_tty = NULL;
		
	if (!(tty->write_q && tty->read_q && tty->secondary && tty->write))
		return -EINVAL;
	switch (cmd) {
		case TCGETS:
			return get_termios(tty,(struct termios *) arg);
		case TCSETSF:
			flush(tty->read_q);
			flush(tty->secondary);
			if (other_tty)
				flush(other_tty->write_q);
		/* fallthrough */
		case TCSETSW:
			wait_until_sent(tty);
		/* fallthrough */
		case TCSETS:
			return set_termios(tty,(struct termios *) arg, dev);
		case TCGETA:
			return get_termio(tty,(struct termio *) arg);
		case TCSETAF:
			flush(tty->read_q);
			flush(tty->secondary);
			if (other_tty)
				flush(other_tty->write_q);
		/* fallthrough */
		case TCSETAW:
			wait_until_sent(tty); /* fallthrough */
		case TCSETA:
			return set_termio(tty,(struct termio *) arg, dev);
		case TCSBRK:
			if (!arg) {
				wait_until_sent(tty);
				send_break(tty);
			}
			return 0;
		case TCXONC:
			switch (arg) {
			case TCOOFF:
				tty->stopped = 1;
				tty->write(tty);
				return 0;
			case TCOON:
				tty->stopped = 0;
				tty->write(tty);
				return 0;
			case TCIOFF:
				if (STOP_CHAR(tty))
					PUTCH(STOP_CHAR(tty),tty->write_q);
				return 0;
			case TCION:
				if (START_CHAR(tty))
					PUTCH(START_CHAR(tty),tty->write_q);
				return 0;
			}
			return -EINVAL; /* not implemented */
		case TCFLSH:
			if (arg==0) {
				flush(tty->read_q);
				flush(tty->secondary);
				if (other_tty)
					flush(other_tty->write_q);
			} else if (arg==1)
				flush(tty->write_q);
			else if (arg==2) {
				flush(tty->read_q);
				flush(tty->secondary);
				flush(tty->write_q);
				if (other_tty)
					flush(other_tty->write_q);
			} else
				return -EINVAL;
			return 0;
		case TIOCEXCL:
			return -EINVAL; /* not implemented */
		case TIOCNXCL:
			return -EINVAL; /* not implemented */
		case TIOCSCTTY:
			return -EINVAL; /* set controlling term NI */
		case TIOCGPGRP:
			verify_area((void *) arg,4);
			put_fs_long(tty->pgrp,(unsigned long *) arg);
			return 0;
		case TIOCSPGRP:
			if ((current->tty < 0) ||
			    (current->tty != dev) ||
			    (tty->session != current->session))
				return -ENOTTY;
			pgrp=get_fs_long((unsigned long *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			tty->pgrp = pgrp;			
			return 0;
		case TIOCOUTQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(tty->write_q),(unsigned long *) arg);
			return 0;
		case TIOCINQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(tty->secondary),
				(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			return -EINVAL; /* not implemented */
		case TIOCGWINSZ:
			return get_window_size(tty,(struct winsize *) arg);
		case TIOCSWINSZ:
			if (other_tty)
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCMGET:
			return -EINVAL; /* not implemented */
		case TIOCMBIS:
			return -EINVAL; /* not implemented */
		case TIOCMBIC:
			return -EINVAL; /* not implemented */
		case TIOCMSET:
			return -EINVAL; /* not implemented */
		case TIOCGSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCSSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
				default: 
					return -EINVAL;
			}
		default:
			return -EINVAL;
	}
}