コード例 #1
0
ファイル: ui.c プロジェクト: jens-na/abook-call
int
init_ui()
{
    ui_init_curses();
#ifdef DEBUG
    fprintf(stderr, "init_abook():\n");
    fprintf(stderr, "  COLS = %d, LINES = %d\n", COLS, LINES);
#endif
    if( LINES < MIN_LINES || COLS < MIN_COLS ) {
        clear();
        refresh();
        endwin();
        fprintf(stderr, _("Your terminal size is %dx%d\n"), COLS, LINES);
        fprintf(stderr, _("Terminal is too small. Minimum terminal "
                          "size for abook is "
                          "%dx%d\n"), MIN_COLS, MIN_LINES);
        return 1;
    }

    init_list();
    init_windows();

    ui_initialized = TRUE;

#ifdef SIGWINCH
    signal(SIGWINCH, win_changed);
#endif

    return 0;
}
コード例 #2
0
ファイル: ui.c プロジェクト: jens-na/abook-call
static void
resize_abook()
{
#ifdef TIOCGWINSZ
    struct winsize winsz;

    ioctl(0, TIOCGWINSZ, &winsz);
#ifdef DEBUG
    if(winsz.ws_col >= MIN_COLS && winsz.ws_row >= MIN_LINES) {
        fprintf(stderr, "Warning: COLS=%d, LINES=%d\n", winsz.ws_col, winsz.ws_row);
    }
#endif

    if(winsz.ws_col >= MIN_COLS && winsz.ws_row >= MIN_LINES) {
#ifdef HAVE_RESIZETERM
        resizeterm(winsz.ws_row, winsz.ws_col);
#else
        COLS = winsz.ws_col;
        LINES = winsz.ws_row;
#endif
    }

    should_resize = FALSE;
    close_list(); /* we need to recreate windows */
    init_list();
    free_windows();
    init_windows();
    refresh_screen();
    refresh();
#endif /* TIOCGWINSZ */
}
コード例 #3
0
ファイル: clamdtop.c プロジェクト: Jyang772/clamav-devel
static void init_ncurses(int num_clamd, int use_default)
{
	int default_bg = use_default ? DEFAULT_COLOR : COLOR_BLACK;
	int default_fg = use_default ? DEFAULT_COLOR : COLOR_WHITE;
	initscr();
	curses_inited = 1;

	start_color();
	keypad(stdscr, TRUE);	/* enable keyboard mapping */
	nonl();			/* tell curses not to do NL->CR/NL on output */
	halfdelay(UPDATE_INTERVAL*10); /* timeout of 2s when waiting for input*/
	noecho();		/* dont echo input */
	curs_set(0);		/* turn off cursor */
	if (use_default)
	    use_default_colors();

	init_pair(header_color, COLOR_BLACK, COLOR_WHITE);
	init_pair(version_color, default_fg, default_bg);
	init_pair(error_color, COLOR_WHITE, COLOR_RED);
	init_pair(value_color, COLOR_GREEN, default_bg);
	init_pair(descr_color, COLOR_CYAN, default_bg);
	init_pair(selected_color, COLOR_BLACK, COLOR_CYAN);
	init_pair(queue_header_color, COLOR_BLACK, COLOR_GREEN);
	init_pair(activ_color, COLOR_MAGENTA, default_bg);
	init_pair(dim_color, COLOR_GREEN, default_bg);
	init_pair(red_color, COLOR_RED, default_bg);

	init_windows(num_clamd);
}
コード例 #4
0
ファイル: main.c プロジェクト: buharin/fastbuild_python
int main(int argc, char *argv[])
{
    SETUP_THE_NUMBERS;
    TEARDOWN_THE_NUMBERS;
    char *char_string = string("asdasd");
    int c;

    while ((c = getopt(argc, argv, "hv")) != -1) {
        switch (c) {
            case 'h':
                print_help_message();
                prepare_for_exit();
                return EXIT_FAILURE;
            case 'v':
                print_licence_message();
                prepare_for_exit();
                return EXIT_FAILURE;
        }
    }
    random_init();
    set_signals();
    init_windows();
    init_modes();

    loop();

    prepare_for_exit();
    free_memory();
    return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: hand.c プロジェクト: ylmeng/grab_box
int main(int argc, char **argv)
{
	struct ctx ctx = { };
	int key;
	char *imageFile = argv[1];
	ctx.image = cvLoadImage(imageFile, 1);
	//init_capture(&ctx);
	//init_recording(&ctx);
	init_windows();
	init_ctx(&ctx);

	//do {
		// ctx.image = cvQueryFrame(ctx.capture); 
		//ctx.image = cvLoadImage("/home/csrobot/Downloads/grab_box/images/OtivvoH.jpg", 1);
		//fprintf(stdout, "image loaded\n");
		filter_and_threshold(&ctx);
		find_contour(&ctx);
		find_convex_hull(&ctx);
		find_fingers(&ctx);

		display(&ctx);
		cvWriteFrame(ctx.writer, ctx.image);

		key = cvWaitKey(0);
	//} while (key != 'q');

	return 0;
}
コード例 #6
0
ファイル: main.c プロジェクト: Niautanor/ProjectTox-Core
int main(int argc, char* argv[]) {
  int ch;
  int i = 0;
  int f_flag = 0;
  char *filename = "data";
  ToxWindow* a;

    for(i = 0; i < argc; i++) {
        if(argv[i][0] == '-') {
            if(argv[i][1] == 'f') {
                if(argv[i + 1] != NULL)
                    filename = argv[i + 1];
                else {
                    f_flag = -1;
                }
            }
        }
    }

  init_term();
  init_tox();
  load_data(filename);
  init_windows();

  if(f_flag == -1) {
    attron(COLOR_PAIR(3) | A_BOLD);
    wprintw(prompt->window, "You passed '-f' without giving an argument!\n"
                            "defaulting to 'data' for a keyfile...\n");
    attroff(COLOR_PAIR(3) | A_BOLD);
  }
    

  while(true) {
    // Update tox.
    do_tox();

    // Draw.
    a = &windows[w_active];
    prepare_window(a->window);
    a->blink = false;
    draw_bar();
    a->onDraw(a);

    // Handle input.
    ch = getch();
    if(ch == '\t') {
      w_active = (w_active + 1) % w_num;
    }
    else if(ch == KEY_BTAB) {
      w_active = (w_active + w_num - 1) % w_num;
    }
    else if(ch != ERR) {
      a->onKey(a, ch);
    }

  }

  return 0;
}
コード例 #7
0
ファイル: main.c プロジェクト: bingbuidea/ProjectTox-Core
int main(int argc, char *argv[])
{
  int ch;
  int f_flag = 0;
  char *filename = "data";
  ToxWindow* a;

  int i = 0;
  for (i = 0; i < argc; ++i) {
    if (argv[i] == NULL)
      break;
    else if (argv[i][0] == '-') {
      if (argv[i][1] == 'f') {
        if (argv[i + 1] != NULL)
          filename = argv[i + 1];
        else
          f_flag = -1;
      }
    }
  }

  init_term();
  init_tox();
  load_data(filename);
  init_windows();
  init_window_status();

  if (f_flag == -1) {
    attron(COLOR_PAIR(3) | A_BOLD);
    wprintw(prompt->window, "You passed '-f' without giving an argument!\n"
                            "defaulting to 'data' for a keyfile...\n");
    attroff(COLOR_PAIR(3) | A_BOLD);
  }
  
  while(true) {
    /* Update tox */
    do_tox();

    /* Draw */
    a = &windows[active_window];
    prepare_window(a->window);
    a->blink = false;
    draw_bar();
    a->onDraw(a);

    /* Handle input */
    ch = getch();
    if (ch == '\t' || ch == KEY_BTAB)
      set_active_window(ch);
    else if (ch != ERR)
      a->onKey(a, ch);
  }
  return 0;
}
コード例 #8
0
ファイル: v_api.c プロジェクト: pqhwan/TCP
int v_accept(int socket, struct in_addr *node){

	socket_t *lso = fd_lookup(socket); //lso -> listening socket

	socket_t *nso;//nso -> new socket
	struct in_addr anyaddr;
	anyaddr.s_addr = 0;
	if(lso->state != LISTENING) return -1; //"this is not a listening socket"

	//get the request
	void *request;
	DQ(lso->q, &request);

	//make an active socket for this connection
	int s = v_socket();
	v_bind(s, &anyaddr, lso->myport);
	nso = fd_lookup(s);
	memcpy(&(nso->uraddr), request+TCPHDRSIZE, SIZE32);
	memcpy(&(nso->myaddr), request+TCPHDRSIZE+SIZE32, SIZE32);
	nso->urport = ((tcphdr *)request)->sourceport;

	nso->ackseq= ++(((tcphdr *)request)->seqnum);

	nso->myseq = rand() % MAXSEQ;
#ifdef SIMPLESEQ
	nso->myseq = 0;
#endif

	set_socketstate(nso, SYN_RCVD);

	init_windows(nso);
	nso->sendw->adwindow = ((tcphdr *)request)->adwindow;
	
	//send respones (second grip)
	tcp_send_handshake(2, nso);

	//initiate buffer mamagement
	pthread_t mgmt_thr;
	pthread_attr_t thr_attr;
	pthread_attr_init(&thr_attr);
	pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&mgmt_thr, &thr_attr, buf_mgmt ,(void *) s);

	//add to socket_table
	HASH_ADD(hh2, socket_table, urport, keylen, nso);
	free(request);

	//if caller wants request origin
	if(node!=NULL) node->s_addr = nso->uraddr;

	return s;
}
コード例 #9
0
ファイル: nscreen.cpp プロジェクト: jpdef/nwindows
Nscreen::Nscreen(){
    //default constructor uses stdin and out
    this->numwindows = 1;
    scrptr = newterm("xterm",stdin,stdout);    
    set_term(scrptr);
    getmaxyx(stdscr,MAX_Y, MAX_X);

    start_color();
    init_pair(1,COLOR_WHITE,COLOR_BLUE);

    init_windows();
    cw=0;
}
コード例 #10
0
ファイル: winceapp_export.cpp プロジェクト: sfsy1989/j2me
DWORD WINAPI CreateWinCEWindow(LPVOID lpParam) {
    static MidpReentryData newSignal;
    static MidpEvent newMidpEvent;

    int screenSize = sizeof(gxj_pixel_type) * CHAM_WIDTH * CHAM_HEIGHT;

/* IMPL_NOTE:  Need a better way to load the library */
#ifdef CVM_PRELOAD_LIB
    instanceMain = LoadLibrary(TEXT("cvmi.dll"));
#else
#ifdef CVM_DEBUG
    instanceMain = LoadLibrary(TEXT("libmidp_g.dll"));
#else
    instanceMain = LoadLibrary(TEXT("libmidp.dll"));
#endif
#endif

    gxj_system_screen_buffer.width = CHAM_WIDTH;
    gxj_system_screen_buffer.height = CHAM_HEIGHT;
    gxj_system_screen_buffer.alphaData = 0;
    gxj_system_screen_buffer.pixelData = (gxj_pixel_type *)midpMalloc(screenSize);
    memset(gxj_system_screen_buffer.pixelData, 0xff, screenSize);

    if (!init_windows(GetModuleHandle(NULL), SW_SHOW)) {
        REPORT_ERROR(LC_AMS, "init_gui() failed");
        MessageBox(NULL, TEXT("Failed to start JWC"), TEXT("Bye"), MB_OK);
    }

    updateVisibleDesktop();

#if JWC_WINCE_USE_DIRECT_DRAW
    init_DirectDraw();
#else
    if (GXOpenDisplay(hwndMain, 0) == 0) {
        REPORT_ERROR(LC_HIGHUI, "GXOpenDisplay() failed");
    }
    gxDispProps = GXGetDisplayProperties();
#endif

    createEditors();

#ifdef ENABLE_JSR_184
    engine_initialize();
#endif

    MIDP_EVENT_INITIALIZE(newMidpEvent);
    while (1) {
        checkForSystemSignal(&newSignal, &newMidpEvent, 200);
    }
}
コード例 #11
0
std::string main_menu::handle_input_timeout( input_context &ctxt )
{
    inp_mngr.set_timeout( 125 );

    std::string action = ctxt.handle_input();

    if( action == "TIMEOUT" ) {
        init_windows();
    }

    inp_mngr.reset_timeout();

    return action;
}
コード例 #12
0
ファイル: main.c プロジェクト: buharin/fastbuild_python
/**
 * @sig: number of the signal
 *
 * Signal handler called if signal is emmitted.
 */
static void signal_handler(const int sig)
{
    prepare_for_exit();
#ifdef SIGWINCH
    if (SIGWINCH == sig) {
        refresh();
        init_windows();
        gamemode_draw();

        return;
    }
#endif
    free_memory();
    exit(EXIT_FAILURE);
}
コード例 #13
0
int main(int argc, char **argv)
{


	if (argc <= 1) 
		cmdline_help();

	init_windows();
	init_buffers();

	for (argv++; *argv != NULL ; argv++) 
		current_buf = load_buffer(*argv);
		

	paint_buffer(current_buf);
	statusprintf("%s", current_buf->name);

	refresh();
	input_loop();

}
コード例 #14
0
ファイル: main.c プロジェクト: Astonex/ProjectTox-Core
int main(int argc, char* argv[]) {
  int ch;
  ToxWindow* a;

  init_term();
  init_tox();
  load_data();
  init_windows();

  while(true) {
    // Update tox.
    do_tox();

    // Draw.
    a = &windows[w_active];
    prepare_window(a->window);
    a->blink = false;
    draw_bar();
    a->onDraw(a);

    // Handle input.
    ch = getch();
    if(ch == '\t') {
      w_active = (w_active + 1) % w_num;
    }
    else if(ch == KEY_BTAB) {
      w_active = (w_active + w_num - 1) % w_num;
    }
    else if(ch != ERR) {
      a->onKey(a, ch);
    }

  }

  return 0;
}
コード例 #15
0
bool main_menu::opening_screen()
{
    // Play title music, whoo!
    play_music( "title" );

    world_generator->set_active_world( NULL );
    world_generator->init();

    init_windows();
    init_strings();
    print_menu( w_open, 0, iMenuOffsetX, iMenuOffsetY );

    if( !assure_dir_exist( FILENAMES["config_dir"] ) ) {
        popup( _( "Unable to make config directory. Check permissions." ) );
        return false;
    }

    if( !assure_dir_exist( FILENAMES["savedir"] ) ) {
        popup( _( "Unable to make save directory. Check permissions." ) );
        return false;
    }

    if( !assure_dir_exist( FILENAMES["templatedir"] ) ) {
        popup( _( "Unable to make templates directory. Check permissions." ) );
        return false;
    }

    for( std::string path : get_files_from_path( ".template", FILENAMES["templatedir"], false,
            true ) ) {
        path = native_to_utf8( path );
        path.erase( path.find( ".template" ), std::string::npos );
        path.erase( 0, path.find_last_of( "\\//" ) + 1 );
        templates.push_back( path );
    }
    std::sort( templates.begin(), templates.end(), std::greater<std::string>() );

    ctxt.register_cardinal();
    ctxt.register_action( "QUIT" );
    ctxt.register_action( "CONFIRM" );
    ctxt.register_action( "DELETE_TEMPLATE" );
    // for the menu shortcuts
    ctxt.register_action( "ANY_INPUT" );
    bool start = false;

    g->u = player();

    // Make [Load Game] the default cursor position if there's game save available
    if( !world_generator->all_worldnames().empty() ) {
        sel1 = 2;
    }

    while( !start ) {
        print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );

        if( layer == 1 ) {
            if( sel1 == 0 ) { // Print the MOTD.
                const int motdy = ( iMenuOffsetY - mmenu_motd.size() ) * 2 / 3;
                const int motdx = 8 + extra_w / 2;
                for( size_t i = 0; i < mmenu_motd.size(); i++ ) {
                    mvwprintz( w_open, motdy + i, motdx, c_light_red, mmenu_motd[i].c_str() );
                }

                wrefresh( w_open );
                catacurses::refresh();
            }

            std::string action = handle_input_timeout( ctxt );

            std::string sInput = ctxt.get_raw_input().text;
            // check automatic menu shortcuts
            for( size_t i = 0; i < vMenuHotkeys.size(); ++i ) {
                for( auto hotkey : vMenuHotkeys[i] ) {
                    if( sInput == hotkey ) {
                        sel1 = i;
                        action = "CONFIRM";
                    }
                }
            }
            // also check special keys
            if( action == "QUIT" ) {
                if( query_yn( _( "Really quit?" ) ) ) {
                    sel1 = 8;
                    action = "CONFIRM";
                }
            } else if( action == "LEFT" ) {
                if( sel1 > 0 ) {
                    sel1--;
                } else {
                    sel1 = 8;
                }
                on_move();
            } else if( action == "RIGHT" ) {
                if( sel1 < 8 ) {
                    sel1++;
                } else {
                    sel1 = 0;
                }
                on_move();
            }
            if( ( action == "UP" || action == "CONFIRM" ) && sel1 > 0 ) {
                if( sel1 == 6 ) {
                    display_help();
                } else if( sel1 == 7 ) {
                    display_credits();
                } else if( sel1 == 8 ) {
                    return false;
                } else {
                    sel2 = 0;
                    layer = 2;
                    print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );

                    switch( sel1 ) {
                        case 1:
                            start = new_character_tab();
                            break;
                        case 2:
                            start = load_character_tab();
                            break;
                        case 3:
                            world_tab();
                            break;
                        default:
                            break;
                    }
                }
            }
        } else if( layer == 2 ) {
            if( sel1 == 4 ) { // Special game
                if( MAP_SHARING::isSharing() ) { // Thee can't save special games, therefore thee can't share them
                    layer = 1;
                    popup( _( "Special games don't work with shared maps." ) );
                    continue;
                }

                std::vector<std::string> special_names;
                int xoffset = 32 + iMenuOffsetX  + extra_w / 2;
                int yoffset = iMenuOffsetY - 2;
                int xlen = 0;
                for( int i = 1; i < NUM_SPECIAL_GAMES; i++ ) {
                    std::string spec_name = special_game_name( special_game_id( i ) );
                    special_names.push_back( spec_name );
                    xlen += spec_name.size() + 2;
                }
                xlen += special_names.size() - 1;
                print_menu_items( w_open, special_names, sel2, yoffset, xoffset - ( xlen / 4 ) );

                wrefresh( w_open );
                catacurses::refresh();
                std::string action = handle_input_timeout( ctxt );
                if( action == "LEFT" ) {
                    if( sel2 > 0 ) {
                        sel2--;
                    } else {
                        sel2 = NUM_SPECIAL_GAMES - 2;
                    }
                    on_move();
                } else if( action == "RIGHT" ) {
                    if( sel2 < NUM_SPECIAL_GAMES - 2 ) {
                        sel2++;
                    } else {
                        sel2 = 0;
                    }
                    on_move();
                } else if( action == "DOWN" || action == "QUIT" ) {
                    layer = 1;
                }
                if( action == "UP" || action == "CONFIRM" ) {
                    if( sel2 >= 0 && sel2 < NUM_SPECIAL_GAMES - 1 ) {
                        g->gamemode = get_special_game( special_game_id( sel2 + 1 ) );
                        // check world
                        WORLDPTR world = world_generator->make_new_world( special_game_id( sel2 + 1 ) );
                        if( world == NULL ) {
                            continue;
                        }
                        world_generator->set_active_world( world );
                        try {
                            g->setup();
                        } catch( const std::exception &err ) {
                            debugmsg( "Error: %s", err.what() );
                            g->gamemode.reset();
                            g->u = player();
                            continue;
                        }
                        if( !g->gamemode->init() ) {
                            g->gamemode.reset();
                            g->u = player();
                            continue;
                        }
                        start = true;
                    }
                }
            } else if( sel1 == 5 ) {  // Settings Menu
                int settings_subs_to_display = vSettingsSubItems.size();
                std::vector<std::string> settings_subs;
                int xoffset = 46 + iMenuOffsetX + extra_w / 2;
                int yoffset = iMenuOffsetY - 2;
                int xlen = 0;
                for( int i = 0; i < settings_subs_to_display; ++i ) {
                    settings_subs.push_back( vSettingsSubItems[i] );
                    xlen += vSettingsSubItems[i].size() + 2; // Open and close brackets added
                }
                xlen += settings_subs.size() - 1;
                if( settings_subs.size() > 1 ) {
                    xoffset -= 6;
                }
                print_menu_items( w_open, settings_subs, sel2, yoffset, xoffset - ( xlen / 4 ) );
                wrefresh( w_open );
                catacurses::refresh();
                std::string action = handle_input_timeout( ctxt );
                std::string sInput = ctxt.get_raw_input().text;
                for( int i = 0; i < settings_subs_to_display; ++i ) {
                    for( auto hotkey : vSettingsHotkeys[i] ) {
                        if( sInput == hotkey ) {
                            sel2 = i;
                            action = "CONFIRM";
                        }
                    }
                }

                if( action == "LEFT" ) {
                    if( sel2 > 0 ) {
                        --sel2;
                    } else {
                        sel2 = settings_subs_to_display - 1;
                    }
                    on_move();
                } else if( action == "RIGHT" ) {
                    if( sel2 < settings_subs_to_display - 1 ) {
                        ++sel2;
                    } else {
                        sel2 = 0;
                    }
                    on_move();
                } else if( action == "DOWN" || action == "QUIT" ) {
                    layer = 1;
                }

                if( action == "UP" || action == "CONFIRM" ) {
                    if( sel2 == 0 ) {
                        get_options().show( true );
                        // The language may have changed- gracefully handle this.
                        init_strings();
                        print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );
                    } else if( sel2 == 1 ) {
                        input_context ctxt_default = get_default_mode_input_context();
                        ctxt_default.display_menu();
                    } else if( sel2 == 2 ) {
                        get_auto_pickup().show();
                    } else if( sel2 == 3 ) {
                        get_safemode().show();
                    } else if( sel2 == 4 ) {
                        all_colors.show_gui();
                    }
                }
            }
        }
    }
    if( start ) {
        g->refresh_all();
        g->draw();
    }
    return start;
}
コード例 #16
0
ファイル: cmod.c プロジェクト: imclab/cmod
int main(int argc, char *argv[])
{
  char *buff;
  int ch;
  int i;

  initscr();
  cbreak();
  noecho();
  nonl();
  curs_set(0);
  // nodelay(stdscr, TRUE);
  intrflush(stdscr, FALSE);
  keypad(stdscr, TRUE);

  if((color = has_colors())) {
    start_color();
    init_pair(1, COLOR_WHITE, COLOR_BLUE);
    init_pair(2, COLOR_CYAN, COLOR_BLUE);
  }

  signal(SIGINT, cleanup);

  init_windows();
  init_bass();

  create_playlist(&playlist_h, &playlist_t);

  if(argc>1) {
    if(strncmp("/", argv[1], 1) != 0) {
      error("argument must be an absolute path", FALSE);
    }
    if(dirname(opendir(argv[1]))) { // is a dir
      if(add(&playlist_h, argv[1], &playlist_t)) {
        p_p++;
        c_p_p++;
        nsongs++;
        active_win = PLAYLIST_WIN;
        bass_loop = BASS_MUSIC_LOOP;
        play(argv[1], PLAYING_PLAYLIST);
      }
      current_path = strdup((char*)dirname(argv[1]));
    } else {
      error("argument not valid", FALSE);
    }
  } else {
    current_path = (char*)malloc(sizeof(char)*PATH_MAX);
    current_path = (char*)getcwd(current_path, PATH_MAX);
  }

  entries = refresh_browser(current_path, 0);

  mvprintw(0, 0, "%s", current_path);

  repaint_windows();

  while((ch = getch()) != 'q') {
    switch(ch) {
      case 'a': // add song to playlist
          if(active_win == BROWSER_WIN) {
            if(!is_dir(current_path, entries[p_b])) {
              buff = mystrcat(current_path,entries[p_b],1);
              if(add(&playlist_h, buff, &playlist_t)) {
                if(p_p == -1) p_p++;
                nsongs++;
                repaint_windows();
              }
              free(buff);
            }
          }
        break;
      case 'e': // add all songs in current dir
          if(active_win == BROWSER_WIN) {
            for(i=0; i<nfiles; i++) {
              if(!is_dir(current_path, entries[i])) {
                buff = mystrcat(current_path,entries[i],1);
                if(add(&playlist_h, buff, &playlist_t)) {
                  if(p_p == -1) p_p++;
                  nsongs++;
                }
                free(buff);
              }
            }
          }
          repaint_windows();
        break;
      case 'c': // recursive add
          if(active_win == BROWSER_WIN) {
            //printw("---%s+++", current_path);
            add_recursive(current_path, entries, nfiles);
            repaint_windows();
            //printw("---%s", current_path);
          }
        break;
      case 'd': // remove one song from playlist
          if(active_win == PLAYLIST_WIN) {
            if(del(&playlist_h, p_p, &playlist_t)) {
              nsongs--;
              if(p_p > nsongs - 1) {
                p_p = nsongs - 1;
              }
              if(p_p < c_p_p) {
                c_p_p--;
              }
              //stop();
              repaint_windows();
            }
          }
        break;
      case 'r': // remove all songs from playlist
          if(del_all(&playlist_h, &playlist_t)) {
            p_p = -1;
            c_p_p = -1;
            nsongs = 0;
            repaint_windows();
          }
        break;
      case ' ': // start playback or browse filesystem
      case 13: //enter key
          if(active_win == BROWSER_WIN) {
            if(strcmp(entries[p_b], "..\0") == 0) {
              current_path = dirname(current_path);
              p_b = 0;
              entries = refresh_browser(current_path, 0);
            } else {
              if(is_dir(current_path, entries[p_b])) {
                current_path = dir_up(current_path, entries[p_b]);
                p_b = 0;
                entries = refresh_browser(current_path, 0);
              } else {
                buff = mystrcat(current_path,entries[p_b],1);
                play(buff, PLAYING_BROWSER);
                free(buff);
                c_p_p = -1;
                if(p_b < nfiles-1) {
                  p_b++;
                }
              }
            }
            refresh_path();
          } else { // PLAYLIST_WIN
            if(nsongs != 0) {
              play(get(&playlist_h, p_p, &playlist_t)->file, PLAYING_PLAYLIST);
              c_p_p = p_p;
              if(p_p < nsongs - 1) {
                p_p++;
              }
            }
          }
          repaint_windows();
        break;

      case 's': // stop playback
          stop();
          c_p_p = -1;
          repaint_windows();
          clear_statusbar(NULL);
        break;

      case 'n': // next song
          next();
        break;

      case 'p': // prev song
          prev();
        break;

      case 'g': // go to current song
          p_p = c_p_p;
          repaint_windows();
        break;

      case 'l': // toggle loop
          loop();
          stop();
          c_p_p = -1;
          repaint_windows();
        break;

      case 'z': // toggle random
          random_mode();
        break;

      case '.': // seek forward
          seek(1);
        break;

      case ',': // seek backward
          seek(-1);
        break;

      case '+':
          volume_up();
        break;

      case '-':
          volume_down();
        break;

      case '>':
          amplify_up();
        break;

      case '<':
          amplify_down();
        break;

      case KEY_UP:
        if(active_win == BROWSER_WIN) {
          if(p_b > 0) {
            p_b--;
          }
        } else {
          if(p_p > 0) {
            p_p--;
          }
        }
        repaint_windows();
        break;

      case KEY_DOWN:
        if(active_win == BROWSER_WIN) {
          if(p_b < nfiles-1) {
            p_b++;
          }
        } else {
          if(p_p < nsongs - 1) {
            p_p++;
          }
        }
        repaint_windows();
        break;

      case KEY_LEFT:
      case KEY_RIGHT:
          switch_activewindow();
          repaint_windows();
        break;

      case KEY_HOME:
          if(active_win == BROWSER_WIN) {
            p_b = 0;
          } else {
            if(p_p != -1) p_p = 0;
          }
          repaint_windows();
        break;

      case KEY_END:
          if(active_win == BROWSER_WIN) {
            p_b = nfiles-1;
          } else {
            if(p_p != -1) p_p = nsongs - 1;
          }
          repaint_windows();
        break;

      case KEY_NPAGE:
        if(active_win == BROWSER_WIN) {
          if((p_b + (browser_win->_maxy - 2)) < nfiles-1 ) {
            p_b += browser_win->_maxy - 1;
          } else {
            p_b = nfiles-1;
          }
        } else {
          if((p_p + (playlist_win->_maxy - 2)) < nsongs) {
            p_p += playlist_win->_maxy - 1;
          } else {
            p_p = nsongs - 1;
          }
        }
        repaint_windows();
        break;

      case KEY_PPAGE:
        if(active_win == BROWSER_WIN) {
          if((p_b - (browser_win->_maxy - 2)) > 0) {
            p_b -= browser_win->_maxy - 1;
          } else {
            p_b = 0;
          }
        } else {
          if((p_p - (playlist_win->_maxy - 2)) > 0) {
            p_p -= playlist_win->_maxy - 1;
          } else {
            if(p_p != -1) p_p = 0;
          }
        }
        repaint_windows();
        break;
    }

    //usleep(10);

    //update_status();

  }

  cleanup();

  return 0;

}
コード例 #17
0
ファイル: main.cpp プロジェクト: light64/project_nao
int main(int argc, char **argv)
{
    struct ctx ctx = { };
    int key;
    CvPoint last_center;
    last_center.x = 0;
    last_center.y = 0;
    int threshold_x = 50;
    int threshold_y = 50;

    init_capture(&ctx);
    init_windows();
    init_ctx(&ctx);

    do
    {
        ctx.image = cvQueryFrame(ctx.capture);

        filter_and_threshold(&ctx);
        find_contour(&ctx);
        find_convex_hull(&ctx);
        find_fingers(&ctx);

        display(&ctx);
//cvWriteFrame(ctx.writer, ctx.image);

//printf("num: %d rad: %d def: %d x: %d y: %d\n", ctx.num_fingers, ctx.hand_radius, ctx.num_defects, ctx.hand_center.x, ctx.hand_center.y);

        if(ctx.num_fingers && ctx.hand_radius)
        {
            if(!last_center.x)
            {
                last_center = ctx.hand_center;

            }
            else
            {
                //Check If Position changed

                if( abs(ctx.hand_center.x - last_center.x)  > threshold_x )
                {
                    if( ctx.hand_center.x - last_center.x > 0 )
                    {
                        printf("move left\n");
                    }
                    else
                    {
                        printf("move right\n");
                    }
                }

                if( abs(ctx.hand_center.y - last_center.y)  > threshold_y )
                {
                    if( ctx.hand_center.y - last_center.y > 0 )
                    {
                        printf("move down\n");
                    }
                    else
                    {
                        printf("move up\n");
                    }
                }


                last_center = ctx.hand_center;

            }



        }




        key = cvWaitKey(1);
    }
    while (key != 'q');

    return 0;
}
コード例 #18
0
ファイル: main.c プロジェクト: stqism/toxic
int main(int argc, char *argv[])
{
    char *user_config_dir = get_user_config_dir();
    int config_err = 0;

    f_loadfromfile = 1;
    int f_flag = 0;
    int i = 0;
    int f_use_ipv4 = 0;

    /* Make sure all written files are read/writeable only by the current user. */
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    for (i = 0; i < argc; ++i) {
        if (argv[i] == NULL)
            break;
        else if (argv[i][0] == '-') {
            if (argv[i][1] == 'f') {
                if (argv[i + 1] != NULL)
                    DATA_FILE = strdup(argv[i + 1]);
                else
                    f_flag = -1;
            } else if (argv[i][1] == 'n') {
                f_loadfromfile = 0;
            } else if (argv[i][1] == '4') {
                f_use_ipv4 = 1;
            }
        }
    }

    config_err = create_user_config_dir(user_config_dir);
    if (DATA_FILE == NULL ) {
        if (config_err) {
            DATA_FILE = strdup("data");
        } else {
            DATA_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("data") + 1);
            if (DATA_FILE != NULL) {
                strcpy(DATA_FILE, user_config_dir);
                strcat(DATA_FILE, CONFIGDIR);
                strcat(DATA_FILE, "data");     
            } else {
                endwin();
                fprintf(stderr, "malloc() failed. Aborting...\n");
                exit(EXIT_FAILURE);
            }
        }
    }

    free(user_config_dir);

    init_term();
    Tox *m = init_tox(f_use_ipv4);

    if (m == NULL) {
        endwin();
        fprintf(stderr, "Failed to initialize network. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    prompt = init_windows(m);

    /* create new thread for ncurses stuff */
    if (pthread_mutex_init(&Winthread.lock, NULL) != 0) {
        endwin();
        fprintf(stderr, "Mutex init failed. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&Winthread.tid, NULL, thread_winref, (void *) m) != 0) {
        endwin();
        fprintf(stderr, "Thread creation failed. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    uint8_t *msg;

#ifdef _SUPPORT_AUDIO

    av = init_audio(prompt, m);

    if ( errors() == NoError )
        msg = "Audio started with no problems.";
    else /* Get error code and stuff */
        msg = "Error starting audio!";

    line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);

#endif /* _SUPPORT_AUDIO */

    if (f_loadfromfile)
        load_data(m, DATA_FILE);

    if (f_flag == -1) {
        msg = "You passed '-f' without giving an argument. Defaulting to 'data' for a keyfile...";
        line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);
    }

    if (config_err) {
        msg = "Unable to determine configuration directory. Defaulting to 'data' for a keyfile...";
        line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);
    }

    sort_friendlist_index();
    prompt_init_statusbar(prompt, m);

    while (true) {
        update_unix_time();
        do_toxic(m, prompt);
        usleep(10000);
    }
        
    return 0;
}
コード例 #19
0
ファイル: toxic.c プロジェクト: jin-eld/toxic
int main(int argc, char *argv[])
{
    char *user_config_dir = get_user_config_dir();
    int config_err = 0;

    parse_args(argc, argv);

    /* Make sure all written files are read/writeable only by the current user. */
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    signal(SIGINT, ignore_SIGINT);

    config_err = create_user_config_dir(user_config_dir);

    if (DATA_FILE == NULL ) {
        if (config_err) {
            DATA_FILE = strdup("data");
        } else {
            DATA_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("data") + 1);

            if (DATA_FILE != NULL) {
                strcpy(DATA_FILE, user_config_dir);
                strcat(DATA_FILE, CONFIGDIR);
                strcat(DATA_FILE, "data");
            } else {
                endwin();
                fprintf(stderr, "malloc() failed. Aborting...\n");
                exit(EXIT_FAILURE);
            }
        }
    }

    free(user_config_dir);

    /* init user_settings struct and load settings from conf file */
    user_settings = malloc(sizeof(struct user_settings));

    if (user_settings == NULL) {
        endwin();
        fprintf(stderr, "malloc() failed. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    memset(user_settings, 0, sizeof(struct user_settings));

    char *p = arg_opts.config_path[0] ? arg_opts.config_path : NULL;
    int settings_err = settings_load(user_settings, p);

    Tox *m = init_tox(arg_opts.use_ipv4);
    init_term();

    if (m == NULL) {
        endwin();
        fprintf(stderr, "Failed to initialize network. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    if (!arg_opts.ignore_data_file)
        load_data(m, DATA_FILE);

    prompt = init_windows(m);

    /* create new thread for ncurses stuff */
    if (pthread_mutex_init(&Winthread.lock, NULL) != 0) {
        endwin();
        fprintf(stderr, "Mutex init failed. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&Winthread.tid, NULL, thread_winref, (void *) m) != 0) {
        endwin();
        fprintf(stderr, "Thread creation failed. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    uint8_t *msg;

#ifdef _SUPPORT_AUDIO

    av = init_audio(prompt, m);
    
    device_set(prompt, input, user_settings->audio_in_dev);
    device_set(prompt, output, user_settings->audio_out_dev);

    if ( errors() == NoError )
        msg = "Audio initiated with no problems.";
    else /* Get error code and stuff */
        msg = "Error initiating audio!";

    line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);

#endif /* _SUPPORT_AUDIO */

    if (config_err) {
        msg = "Unable to determine configuration directory. Defaulting to 'data' for a keyfile...";
        line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);
    }


    if (settings_err == -1) {
        msg = "Failed to load user settings";
        line_info_add(prompt, NULL, NULL, NULL, msg, SYS_MSG, 0, 0);
    }


    sort_friendlist_index();
    prompt_init_statusbar(prompt, m);

    while (true) {
        update_unix_time();
        do_toxic(m, prompt);
        usleep(10000);
    }

    return 0;
}
コード例 #20
0
int main(int argc, char **argv)
{
    parse_args(argc, argv);

    /* Use the -b flag to enable stderr */
    if (!arg_opts.debug)
        freopen("/dev/null", "w", stderr);

    if (arg_opts.encrypt_data && arg_opts.unencrypt_data) {
        arg_opts.encrypt_data = 0;
        arg_opts.unencrypt_data = 0;
        queue_init_message("Warning: Using --unencrypt-data and --encrypt-data simultaneously has no effect");
    }

    /* Make sure all written files are read/writeable only by the current user. */
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    init_default_data_files();

    bool datafile_exists = file_exists(DATA_FILE);

    if (!datafile_exists && !arg_opts.unencrypt_data)
        first_time_encrypt("Creating new data file. Would you like to encrypt it? Y/n (q to quit)");
    else if (arg_opts.encrypt_data)
        first_time_encrypt("Encrypt existing data file? Y/n (q to quit)");


    /* init user_settings struct and load settings from conf file */
    user_settings = calloc(1, sizeof(struct user_settings));

    if (user_settings == NULL)
        exit_toxic_err("failed in main", FATALERR_MEMORY);

    const char *p = arg_opts.config_path[0] ? arg_opts.config_path : NULL;

    if (settings_load(user_settings, p) == -1) {
        queue_init_message("Failed to load user settings");
    }

    int curl_init = curl_global_init(CURL_GLOBAL_ALL);
    int nameserver_ret = name_lookup_init(curl_init);

    if (nameserver_ret == -1) {
        queue_init_message("curl failed to initialize; name lookup service is disabled.");
    } else if (nameserver_ret == -2) {
        queue_init_message("Name lookup server list could not be found.");
    } else if (nameserver_ret == -3) {
        queue_init_message("Name lookup server list does not contain any valid entries.");
    }

#ifdef X11

    if (init_xtra(DnD_callback) == -1)
        queue_init_message("X failed to initialize");

#endif

    Tox *m = load_toxic(DATA_FILE);

    if (arg_opts.encrypt_data && !datafile_exists)
        arg_opts.encrypt_data = 0;


    init_term();

    prompt = init_windows(m);
    prompt_init_statusbar(prompt, m);

    /* thread for ncurses stuff */
    if (pthread_mutex_init(&Winthread.lock, NULL) != 0)
        exit_toxic_err("failed in main", FATALERR_MUTEX_INIT);

    if (pthread_create(&Winthread.tid, NULL, thread_winref, (void *) m) != 0)
        exit_toxic_err("failed in main", FATALERR_THREAD_CREATE);

    /* thread for message queue */
    if (pthread_create(&cqueue_thread.tid, NULL, thread_cqueue, (void *) m) != 0)
        exit_toxic_err("failed in main", FATALERR_THREAD_CREATE);

#ifdef AUDIO

    av = init_audio(prompt, m);

#ifdef VIDEO
    init_video(prompt, m);

#endif /* VIDEO */

    /* AV thread */
    if (pthread_create(&av_thread.tid, NULL, thread_av, (void *) av) != 0)
        exit_toxic_err("failed in main", FATALERR_THREAD_CREATE);

    set_primary_device(input, user_settings->audio_in_dev);
    set_primary_device(output, user_settings->audio_out_dev);

#elif SOUND_NOTIFY

    if ( init_devices() == de_InternalError )
        queue_init_message("Failed to init audio devices");

#endif /* AUDIO */

    init_notify(60, 3000);

    /* screen/tmux auto-away timer */
    if (init_mplex_away_timer(m) == -1)
        queue_init_message("Failed to init mplex auto-away.");

    int nodeslist_ret = load_DHT_nodeslist();

    if (nodeslist_ret != 0) {
        queue_init_message("DHT nodeslist failed to load (error %d)", nodeslist_ret);
    }

    pthread_mutex_lock(&Winthread.lock);
    print_init_messages(prompt);
    pthread_mutex_unlock(&Winthread.lock);

    cleanup_init_messages();

    /* set user avatar from config file. if no path is supplied tox_unset_avatar is called */
    char avatarstr[MAX_STR_SIZE];
    snprintf(avatarstr, sizeof(avatarstr), "/avatar \"%s\"", user_settings->avatar_path);
    execute(prompt->chatwin->history, prompt, m, avatarstr, GLOBAL_COMMAND_MODE);

    time_t last_save = get_unix_time();

    while (true) {
        do_toxic(m);

        time_t cur_time = get_unix_time();

        if (timed_out(last_save, AUTOSAVE_FREQ)) {
            pthread_mutex_lock(&Winthread.lock);

            if (store_data(m, DATA_FILE) != 0)
                line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, RED, "WARNING: Failed to save to data file");

            pthread_mutex_unlock(&Winthread.lock);

            last_save = cur_time;
        }

        usleep(tox_iteration_interval(m) * 1000);
    }

    return 0;
}
コード例 #21
0
ファイル: main.c プロジェクト: carriercomm/ProjectTox-Core
int main(int argc, char *argv[])
{
    char *user_config_dir = get_user_config_dir();
    int config_err = 0;

    f_loadfromfile = 1;
    int f_flag = 0;
    int i = 0;

    for (i = 0; i < argc; ++i) {
        if (argv[i] == NULL)
            break;
        else if (argv[i][0] == '-') {
            if (argv[i][1] == 'f') {
                if (argv[i + 1] != NULL)
                    DATA_FILE = strdup(argv[i + 1]);
                else
                    f_flag = -1;
            } else if (argv[i][1] == 'n') {
                f_loadfromfile = 0;
            }
        }
    }

    if (DATA_FILE == NULL ) {
        config_err = create_user_config_dir(user_config_dir);

        if (config_err) {
            DATA_FILE = strdup("data");
            SRVLIST_FILE = strdup("../../other/DHTservers");
        } else {
            DATA_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("data") + 1);
            strcpy(DATA_FILE, user_config_dir);
            strcat(DATA_FILE, CONFIGDIR);
            strcat(DATA_FILE, "data");

            SRVLIST_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("DHTservers") + 1);
            strcpy(SRVLIST_FILE, user_config_dir);
            strcat(SRVLIST_FILE, CONFIGDIR);
            strcat(SRVLIST_FILE, "DHTservers");
        }
    }

    free(user_config_dir);

    init_term();
    Messenger *m = init_tox();
    ToxWindow *prompt = init_windows(m);

    if (f_loadfromfile)
        load_data(m, DATA_FILE);

    if (f_flag == -1) {
        attron(COLOR_PAIR(3) | A_BOLD);
        wprintw(prompt->window, "You passed '-f' without giving an argument.\n"
                "defaulting to 'data' for a keyfile...\n");
        attroff(COLOR_PAIR(3) | A_BOLD);
    }

    if (config_err) {
        attron(COLOR_PAIR(3) | A_BOLD);
        wprintw(prompt->window, "Unable to determine configuration directory.\n"
                "defaulting to 'data' for a keyfile...\n");
        attroff(COLOR_PAIR(3) | A_BOLD);
    }

    while (true) {
        /* Update tox */
        do_tox(m, prompt);

        /* Draw */
        draw_active_window(m);
    }

    cleanupMessenger(m);
    free(DATA_FILE);
    free(SRVLIST_FILE);
    return 0;
}
コード例 #22
0
ファイル: main.c プロジェクト: UlricE/SiagOffice
void realmain(int argc, char **argv)
{
	char b[256];
	struct stat statbuf;
	/* vars from oldmain */
	buffer *buf = NULL;
	char path[1024];
	int i;

	setlocale(LC_NUMERIC, "C");
	common_init("Egon Animator %s. No Warranty");

	sprintf(b, "%s/%ld", siag_basedir, (long)getpid());
	mkdir(b, 0700);
	sprintf(b, "%s/egon.scm", siag_basedir);
	egonrc = MwStrdup(b);

	init_interpreters();
	siod_interpreter = init_parser(argc, argv);
	init_python_parser();
	init_guile_parser();
	init_ruby_parser();
	waitforchild(0);

	init_position();
	init_cmds();

	buf = new_buffer("noname.egon", "noname.egon");

	sprintf(path, "%s/egon/egon.scm", datadir);
	if (stat(path, &statbuf)) {
		fprintf(stderr, "Can't find the runtime library (egon.scm).\n");
		fprintf(stderr, "Expected it in %s\n", path);
		fprintf(stderr, "SIAGHOME (if set) is '%s'\n", datadir);
		fprintf(stderr, "Please read installation instructions.\n");
		exit(EXIT_FAILURE);
	}

	setvar(cintern("libdir"), strcons(-1, libdir), NIL);
	setvar(cintern("datadir"), strcons(-1, datadir), NIL);
	setvar(cintern("docdir"), strcons(-1, docdir), NIL);

	/* load runtime library */
	sprintf(b, "(load \"%s/egon/egon.scm\")", datadir);
	execute(b);

	init_windows(buf, &argc, argv);
	setlocale(LC_NUMERIC, "C");	/* possibly hosed by X */

	/* load user customizations, if any */
	if (!stat(egonrc, &statbuf)) {
		sprintf(b, "(load \"%s\")", egonrc);
		execute(b);
	}

	execute("(init-windows)");
	execute("(create-menus)");

	fileio_init();
	for (i = 1; i < argc; i++) {
		if (argv[i][0] != '-') {
			strcpy(path, argv[i]);
			free_buffer(w_list->buf);
			buf = new_buffer(buffer_name(argv[i]), path);
			loadmatrix(path, buf, guess_file_format(path));
			buf->change = FALSE;
			w_list->buf = buf;
		}
	}
	pr_scr_flag = TRUE;

	execute("(popup-editor)");
	/* this works, for reasons beyond my comprehension */
	execute("(print-version)");
	execute("(print-version)");
	activate_window(w_list);
#ifdef HAVE_LIBTCL
	Tcl_Main(argc, argv, Tcl_AppInit);
#else
	mainloop();
#endif
}
コード例 #23
0
ファイル: toxic.c プロジェクト: dardevelin/toxic
int main(int argc, char *argv[])
{
    init_signal_catchers();
    parse_args(argc, argv);

    /* Make sure all written files are read/writeable only by the current user. */
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    int config_err = init_data_files();

    /* init user_settings struct and load settings from conf file */
    user_settings_ = calloc(1, sizeof(struct user_settings));

    if (user_settings_ == NULL)
        exit_toxic_err("failed in main", FATALERR_MEMORY);

    char *p = arg_opts.config_path[0] ? arg_opts.config_path : NULL;
    int settings_err = settings_load(user_settings_, p);

    Tox *m = init_tox();
    init_term();

    /* enable stderr for debugging */
    if (!arg_opts.debug)
        freopen("/dev/null", "w", stderr);

    if (m == NULL)
        exit_toxic_err("failed in main", FATALERR_NETWORKINIT);

    if (!arg_opts.ignore_data_file)
        load_data(m, DATA_FILE);

    prompt = init_windows(m);
    prompt_init_statusbar(prompt, m);

    /* thread for ncurses stuff */
    if (pthread_mutex_init(&Winthread.lock, NULL) != 0)
        exit_toxic_err("failed in main", FATALERR_MUTEX_INIT);

    if (pthread_create(&Winthread.tid, NULL, thread_winref, (void *) m) != 0)
        exit_toxic_err("failed in main", FATALERR_THREAD_CREATE);

#ifdef _AUDIO

    av = init_audio(prompt, m);


    set_primary_device(input, user_settings_->audio_in_dev);
    set_primary_device(output, user_settings_->audio_out_dev);
#elif _SOUND_NOTIFY
    if ( init_devices() == de_InternalError )
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, "Failed to init devices");

#endif /* _AUDIO */
    
    init_notify(60, 3000);

#ifdef _SOUND_NOTIFY
//     sound_notify(prompt, self_log_in, 0, NULL);
#endif /* _SOUND_NOTIFY */
    
    const char *msg;
    
    if (config_err) {
        msg = "Unable to determine configuration directory. Defaulting to 'data' for data file...";
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, msg);
    }

    if (settings_err == -1)
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, "Failed to load user settings");

    if (arg_opts.use_proxy && !arg_opts.force_tcp) {
        msg = "* WARNING: Using a proxy without disabling UDP may leak your real IP address.";
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, RED, "%s", msg);
        msg = "  Use the -t option to disable UDP.";
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, RED, "%s", msg);
    }

    uint64_t last_save = (uint64_t) time(NULL);
    uint64_t looptimer = last_save;
    useconds_t msleepval = 40000;
    uint64_t loopcount = 0;

    while (true) {
        update_unix_time();
        do_toxic(m, prompt);
        uint64_t cur_time = get_unix_time();

        if (timed_out(last_save, cur_time, AUTOSAVE_FREQ)) {
            pthread_mutex_lock(&Winthread.lock);
            store_data(m, DATA_FILE);
            pthread_mutex_unlock(&Winthread.lock);

            last_save = cur_time;
        }

        msleepval = optimal_msleepval(&looptimer, &loopcount, cur_time, msleepval);
        usleep(msleepval);
    }

    return 0;
}
コード例 #24
0
ファイル: toxic.c プロジェクト: gracchus163/toxic
int main(int argc, char *argv[])
{
    char *user_config_dir = get_user_config_dir();
    int config_err = 0;

    parse_args(argc, argv);

    /* Make sure all written files are read/writeable only by the current user. */
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    signal(SIGINT, catch_SIGINT);

    config_err = create_user_config_dir(user_config_dir);

    if (DATA_FILE == NULL ) {
        if (config_err) {
            DATA_FILE = strdup("data");

            if (DATA_FILE == NULL)
                exit_toxic_err("failed in main", FATALERR_MEMORY);
        } else {
            DATA_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("data") + 1);

            if (DATA_FILE == NULL)
                exit_toxic_err("failed in main", FATALERR_MEMORY);

            strcpy(DATA_FILE, user_config_dir);
            strcat(DATA_FILE, CONFIGDIR);
            strcat(DATA_FILE, "data");
        }
    }

    free(user_config_dir);

    /* init user_settings struct and load settings from conf file */
    user_settings_ = calloc(1, sizeof(struct user_settings));

    if (user_settings_ == NULL)
        exit_toxic_err("failed in main", FATALERR_MEMORY);

    char *p = arg_opts.config_path[0] ? arg_opts.config_path : NULL;
    int settings_err = settings_load(user_settings_, p);

    Tox *m = init_tox(arg_opts.use_ipv4);
    init_term();

    if (m == NULL)
        exit_toxic_err("failed in main", FATALERR_NETWORKINIT);

    if (!arg_opts.ignore_data_file)
        load_data(m, DATA_FILE);

    prompt = init_windows(m);
    prompt_init_statusbar(prompt, m);

    /* thread for ncurses stuff */
    if (pthread_mutex_init(&Winthread.lock, NULL) != 0)
        exit_toxic_err("failed in main", FATALERR_MUTEX_INIT);

    if (pthread_create(&Winthread.tid, NULL, thread_winref, (void *) m) != 0)
        exit_toxic_err("failed in main", FATALERR_THREAD_CREATE);

#ifdef _AUDIO

    av = init_audio(prompt, m);


    set_primary_device(input, user_settings_->audio_in_dev);
    set_primary_device(output, user_settings_->audio_out_dev);
#elif _SOUND_NOTIFY
    if ( init_devices() == de_InternalError )
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, "Failed to init devices");

#endif /* _AUDIO */
    
    init_notify(60, 3000);

#ifdef _SOUND_NOTIFY
    notify(prompt, self_log_in, 0);
#endif /* _SOUND_NOTIFY */
    
    const char *msg;

    if (config_err) {
        msg = "Unable to determine configuration directory. Defaulting to 'data' for a keyfile...";
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, msg);
    }

    if (settings_err == -1) {
        msg = "Failed to load user settings";
        line_info_add(prompt, NULL, NULL, NULL, SYS_MSG, 0, 0, msg);
    }

    sort_friendlist_index();

    uint64_t last_save = (uint64_t) time(NULL);

    while (true) {
        update_unix_time();
        do_toxic(m, prompt);
        uint64_t cur_time = get_unix_time();

        if (timed_out(last_save, cur_time, AUTOSAVE_FREQ)) {
            pthread_mutex_lock(&Winthread.lock);
            store_data(m, DATA_FILE);
            pthread_mutex_unlock(&Winthread.lock);

            last_save = cur_time;
        }

        usleep(40000);
    }

    return 0;
}
コード例 #25
0
ファイル: v_api.c プロジェクト: pqhwan/TCP
int v_connect(int socket, struct in_addr *addr, uint16_t port){

#ifdef DEBUG
	printf(" v_connect() Trying to connect\n");
#endif

	//bind the socket to a random port
	int ret;
	struct in_addr any_addr;
	any_addr.s_addr = 0;

	ret = v_bind(socket, &any_addr, rand()%MAXPORT);

	//something went wrong at v_bind (no socket, not valid pnum)
	if(ret < 0) {	
#ifdef DEBUG
	printf(" v_connect() error : v_bind() failed\n");
#endif
		
		return -1; 

	}

#ifdef DEBUG
	printf(" v_connect() : v_bind() success\n");
#endif

	socket_t *so = fd_lookup(socket);
	if (so == NULL) {

#ifdef DEBUG
		printf(" v_connect() error : fd_lookup() failed\n");
#endif
		set_socketstate(so, CLOSE);
		return -1;
	}

#ifdef DEBUG
	printf(" v_connect() : fd_lookup() success\n");
#endif
	
	//store it in the lookup table (urport, myport, uraddr) + init windows
	init_windows(so);	
	
	//populate socket with info	
	so->urport = port;
	so->uraddr = addr->s_addr;
	//my addr is the interface IP address we will be sending request out to
	interface_t *i = get_nexthop(so->uraddr);
	if (i == NULL) {
		set_socketstate(so, CLOSE);
		return -EHOSTUNREACH;
	}

	so->myaddr = i->sourcevip;
	so->myseq = rand() % MAXSEQ;
#ifdef SIMPLESEQ
	so->myseq = 0;
#endif

#ifdef DEBUG
	printf(" v_connect() : so->* success\n");
#endif

#ifdef DEBUG
			printf(" v_connect: Added socket %d to socket_table"_NORMAL_"\n", so->id);
#endif

	HASH_ADD(hh2, socket_table, urport, keylen, so);

	set_socketstate(so, SYN_SENT);

#ifdef DEBUG
	printf(" v_connect() : socket %d moved into state SYN_SENT\n", so->id);
#endif

	tcp_send_handshake(1, so);
	
#ifdef DEBUG
			printf(_RED_" v_connect: send syn"_NORMAL_"\n");
			printf(_BLUE_" v_connect: timed out"_NORMAL_"\n");
#endif

	time_t now = time(NULL);
	time_t next = now;
	time_t diff = 0;
	int count = 0;

	//send a connection request (first grip)
	while ((count < MAX_SYN_REQ)) {

		if (so->state == ESTABLISHED) {
			break;
		}
		
		next = time(NULL);
		diff = next-now;

		if (diff == 1) {
			tcp_send_handshake(1, so);
			count++;

#ifdef DEBUG
			printf(_RED_" v_connect: send syn"_NORMAL_"\n");
			printf(_BLUE_" v_connect: timed out"_NORMAL_"\n");
#endif

			now = next;
		}
	}

	// Could not connect
	if (so->state == SYN_SENT || so->state == CLOSE) {
		set_socketstate(so, CLOSED);
		return -ENOTCONN;
	}

	//commence buffer management
    int s = (int)socket;
    pthread_attr_t thr_attr;
    pthread_attr_init(&thr_attr);
    pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&so->th, &thr_attr, buf_mgmt, (void *) s);

	return 0;
}
コード例 #26
0
ファイル: client.c プロジェクト: urchinfinity/chatroom
int main(int argc, char *argv[]) {

    if (argc != 2) {
        fprintf(stderr, "usage: %s [ip]\n", argv[0]);
        exit(1);
    }

    init_user();
    init_connection(argv[1]);
    signup_signin();

    init_curses();
    init_windows_attr();
    init_windows();
     
    // catch response from server
    pthread_t response_thd;
    if(pthread_create(&response_thd, NULL, response_handler, (void *)0))
        ERR_EXIT("Create response thread failed");

    get_online();

    while (1) {
        int c = wgetch(target->win);
        switch(c) {
            case '\t':
                target->text[target->len] = '\0';
                strcat(target->text, "    ");
                target->len += 4;
                target->y += 4;
                break;
            case KEY_BACKSPACE:
                if (target->y != 0) {
                    target->len--;
                    if (target->offset == 0)
                        mvwaddch(target->win, target->x,--target->y,' ');
                    else {
                        int i;
                        for (i = target->len + target->offset; i < target->len; i++) {
                            target->text[i] = target->text[i + 1];
                            mvwaddch(target->win, target->x, i, target->text[i]);
                        }
                        mvwaddch(target->win, target->x, i,' ');
                        target->y--;
                    }
                    wrefresh(target->win);
                }
                break;
            case 27: //esc
                close_client();
            case KEY_MOUSE:
                // waddstr(target->win, "clicked");
                if(getmouse(&event) == OK)
                    serve_mouse_event(event.y, event.x);
                break;
            case 13: //enter
                target->text[target->len] = '\0';
                if (strcmp(target->type, COMMENT) == 0) {
                    send_cmt();
                } else {
                    upload_file();
                }
                reset_input();
                break;
            case KEY_DOWN:
                break;
            case KEY_UP:
                break;
            case KEY_LEFT:
                if (target->len != 0) {
                    target->y--;
                    target->offset--;
                }
                break;
            case KEY_RIGHT:
                if (target->offset != 0) {
                    target->y++;
                    target->offset++;
                }
                break;
            default:
                mvwaddch(target->win, target->x, target->y, c);
                if (target->offset == 0) {
                    target->text[target->len++] = c;
                } else {
                    int i;
                    for (i = target->len; i > target->len + target->offset; i--)
                        target->text[i] = target->text[i - 1];
                    target->text[i] = c;
                    target->len++;
                    while (i++ < target->len - 1)
                        mvwaddch(target->win, target->x, i, target->text[i]);
                }
                wrefresh(target->win);
                // wprintw(target->win, "%d", c);
                target->y++;
                break;
        }
        wmove(target->win, target->x, target->y);
        wrefresh(target->win);
    }
    close_client();
}
コード例 #27
0
ファイル: goaccess.c プロジェクト: kingland/goaccess
int
main (int argc, char **argv)
{
  int quit = 0;

#if defined(__GLIBC__)
  setup_signal_handlers ();
#endif

  /* command line/config options */
  verify_global_config (argc, argv);
  parse_conf_file (&argc, &argv);
  parse_cmd_line (argc, argv);

  /* initialize storage */
  init_storage ();
  /* setup to use the current locale */
  set_locale ();

#ifdef HAVE_LIBGEOIP
  init_geoip ();
#endif

  /* init logger */
  logger = init_log ();
  set_signal_data (logger);

  /* init parsing spinner */
  parsing_spinner = new_gspinner ();
  parsing_spinner->process = &logger->process;

  /* outputting to stdout */
  if (conf.output_html) {
    ui_spinner_create (parsing_spinner);
    goto out;
  }

  /* init curses */
  set_input_opts ();
  if (conf.no_color || has_colors () == FALSE) {
    conf.color_scheme = NO_COLOR;
    conf.no_color = 1;
  } else {
    start_color ();
  }
  init_colors ();
  init_windows (&header_win, &main_win);
  set_curses_spinner (parsing_spinner);

  /* configuration dialog */
  if (isatty (STDIN_FILENO) && (conf.log_format == NULL || conf.load_conf_dlg)) {
    refresh ();
    quit = render_confdlg (logger, parsing_spinner);
  }
  /* straight parsing */
  else {
    ui_spinner_create (parsing_spinner);
  }

out:

  /* main processing event */
  time (&start_proc);
  if (conf.load_from_disk)
    set_general_stats ();
  else if (!quit && parse_log (&logger, NULL, -1))
    FATAL ("Error while processing file");

  logger->offset = logger->process;

  /* no valid entries to process from the log */
  if (logger->process == 0)
    FATAL ("Nothing valid to process.");

  /* init reverse lookup thread */
  gdns_init ();
  parse_initial_sort ();
  allocate_holder ();

  end_spinner ();
  time (&end_proc);

  /* stdout */
  if (conf.output_html)
    standard_output ();
  /* curses */
  else
    curses_output ();

  /* clean */
  house_keeping ();

  return EXIT_SUCCESS;
}
コード例 #28
0
int main (int argc, char *argv[])
{
  int i;

  OleInitialize(NULL);

  SetConsoleTitle(LUACOM_VERSION);

#if defined(LUA4)
  lua_State *lua_state = lua_open(0);
  lua_baselibopen (lua_state);
  lua_mathlibopen (lua_state);
  lua_iolibopen   (lua_state);
  lua_strlibopen (lua_state);
#elif defined(LUA5)
  lua_State *lua_state = lua_open();
  luaopen_base (lua_state);
  luaopen_math (lua_state);
  luaopen_io   (lua_state);
  luaopen_string (lua_state);
  luaopen_table (lua_state);
#endif

  lua_pushstring(lua_state, "> "); lua_setglobal(lua_state, "_PROMPT");

  luacom_open(lua_state);
  init_windows(lua_state);
  if (argc < 2) {  /* no arguments? */
    if (isatty(0)) {
      printf("%s  %s\n", LUACOM_VERSION, LUACOM_COPYRIGHT);
      manual_input(lua_state, 1);
    }
    else
      ldo(lua_state, lua_dofile, NULL);  /* executes stdin as a file */
  }
  else for (i=1; i<argc; i++) {
    if (argv[i][0] == '-') {  /* option? */
      switch (argv[i][1]) {
        case 0:
          ldo(lua_state, lua_dofile, NULL);  /* executes stdin as a file */
          break;
        case 'i':
          manual_input(lua_state, 1);
          break;
        case 'q':
          manual_input(lua_state, 0);
          break;
        case 'v':
          printf("%s  %s\n(written by %s)\n\n",
                 LUACOM_VERSION, LUACOM_COPYRIGHT, LUACOM_AUTHORS);
          break;
        case 'e':
          i++;
          if (ldo(lua_state, lua_dostring, argv[i]) != 0) {
            fprintf(stderr, "lua: error running argument `%s'\n", argv[i]);
            return 1;
          }
          break;
        default:
          print_message();
          exit(1);
      }
    }
    else if (strchr(argv[i], '='))
      assign(lua_state, argv[i]);
    else {
      int result = ldo(lua_state, lua_dofile, argv[i]);
      if (result) {
        if (result == 2) {
          fprintf(stderr, "lua: cannot execute file ");
          perror(argv[i]);
        }
        exit(1);
      }
    }
  }

  luacom_close(lua_state);
  lua_close(lua_state);

  OleUninitialize();

  return 0;
}
コード例 #29
0
ファイル: clamdtop.c プロジェクト: Jyang772/clamav-devel
int main(int argc, char *argv[])
{
	int ch = 0;
	struct timeval tv_last, tv;
	unsigned i;

	atexit(cleanup);
	setup_connections(argc, argv);
	init_ncurses(global.num_clamd, default_colors);

	memset(&tv_last, 0, sizeof(tv_last));
	do {
		if (toupper(ch) == 'H') {
			ch = show_help();
		}
		switch(ch) {
			case KEY_RESIZE:
				resize();
				endwin();
				refresh();
				init_windows(global.num_clamd);
				break;
			case 'R':
			case 'r':
				for (i=0;i<global.num_clamd;i++)
					global.all_stats[i].biggest_queue = 1;
				biggest_mem = 0;
				break;
			case KEY_UP:
				if (global.num_clamd > 1) {
					if (detail_selected == -1)
						detail_selected = global.num_clamd-1;
					else
						--detail_selected;
				}
				break;
			case KEY_DOWN:
				if (global.num_clamd > 1) {
					if (detail_selected == -1)
						detail_selected = 0;
					else {
						if((unsigned)++detail_selected >= global.num_clamd)
							detail_selected = -1;
					}
				}
				break;
		}
		gettimeofday(&tv, NULL);
		header();
		if(tv.tv_sec - tv_last.tv_sec >= MIN_INTERVAL) {
			free_global_stats();
			for(i=0;i<global.num_clamd;i++) {
				unsigned biggest_q;
				struct stats *stats = &global.all_stats[i];
				if (global.conn[i].sd != -1)
					send_string(&global.conn[i], "nSTATS\n");
				biggest_q = stats->biggest_queue;
				memset(stats, 0, sizeof(*stats));
				stats->biggest_queue = biggest_q;
				parse_stats(&global.conn[i], stats, i);
			}
			if (global.tasks)
				qsort(global.tasks, global.n, sizeof(*global.tasks), tasks_compare);
			tv_last = tv;
		}
		/* always show, so that screen resizes take effect instantly*/
		output_all();
		for(i=0;i<global.num_clamd;i++) {
			if (global.conn[i].sd == -1)
				reconnect(&global.conn[i]);
		}
	} while(toupper(ch = getch()) != 'Q');
	free_global_stats();
	normal_exit = 1;
	return 0;
}
コード例 #30
0
ファイル: main.c プロジェクト: FullName/toxic
int main(int argc, char *argv[])
{
    char *user_config_dir = get_user_config_dir();
    int config_err = 0;

    f_loadfromfile = 1;
    int f_flag = 0;
    int i = 0;

    for (i = 0; i < argc; ++i) {
        if (argv[i] == NULL)
            break;
        else if (argv[i][0] == '-') {
            if (argv[i][1] == 'f') {
                if (argv[i + 1] != NULL)
                    DATA_FILE = strdup(argv[i + 1]);
                else
                    f_flag = -1;
            } else if (argv[i][1] == 'n') {
                f_loadfromfile = 0;
            }
        }
    }

    config_err = create_user_config_dir(user_config_dir);
    if (DATA_FILE == NULL ) {
        if (config_err) {
            DATA_FILE = strdup("data");
        } else {
            DATA_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("data") + 1);
            if (DATA_FILE != NULL) {
                strcpy(DATA_FILE, user_config_dir);
                strcat(DATA_FILE, CONFIGDIR);
                strcat(DATA_FILE, "data");
            } else {
                endwin();
                fprintf(stderr, "malloc() failed. Aborting...\n");
                exit(EXIT_FAILURE);
            }
        }
    }

    if (config_err) {
        SRVLIST_FILE = strdup(PACKAGE_DATADIR "/DHTservers");
    } else {
        SRVLIST_FILE = malloc(strlen(user_config_dir) + strlen(CONFIGDIR) + strlen("DHTservers") + 1);
        if (SRVLIST_FILE != NULL) {
            strcpy(SRVLIST_FILE, user_config_dir);
            strcat(SRVLIST_FILE, CONFIGDIR);
            strcat(SRVLIST_FILE, "DHTservers");
        } else {
            endwin();
            fprintf(stderr, "malloc() failed. Aborting...\n");
            exit(EXIT_FAILURE);
        }
    }

    free(user_config_dir);

    init_term();
    Tox *m = init_tox();

    if (m == NULL) {
        endwin();
        fprintf(stderr, "Failed to initialize network. Aborting...\n");
        exit(EXIT_FAILURE);
    }

    prompt = init_windows(m);

    if (f_loadfromfile)
        load_data(m, DATA_FILE);

    if (f_flag == -1) {
        attron(COLOR_PAIR(RED) | A_BOLD);
        wprintw(prompt->window, "You passed '-f' without giving an argument.\n"
                "defaulting to 'data' for a keyfile...\n");
        attroff(COLOR_PAIR(RED) | A_BOLD);
    }

    if (config_err) {
        attron(COLOR_PAIR(RED) | A_BOLD);
        wprintw(prompt->window, "Unable to determine configuration directory.\n"
                "defaulting to 'data' for a keyfile...\n");
        attroff(COLOR_PAIR(RED) | A_BOLD);
    }

    prompt_init_statusbar(prompt, m);

    while (true) {
        /* Update tox */
        do_tox(m, prompt);

        /* Draw */
        draw_active_window(m);
    }

    exit_toxic(m);
    return 0;
}