void setup() { setup_screen(); player = create_sprite(screen_width()/2, screen_height() - 5, 1, 1, "S"); player->dy = 0; player->dx = 0; bullet = create_sprite(-1, -1, 1, 1, "*"); bullet->dy = 0; bullet->dx = 0; for (int i = 0; i < 3; i++) { alien[i] = create_sprite(4+4*i, 0, 1, 1, "@"); } for (int j = 0; j < 4; j++) { alien[j+3] = create_sprite(2+4*j, 3, 1, 1, "@"); } for (int k = 0; k < 3; k++) { alien[k+7] = create_sprite(4+4*k, 6, 1, 1, "@"); } for (int r = 0; r < 10; r++) { alien[r]->dx = 0.1; alien[r]->dy = 0; } tim = create_timer(25); }
int main() { setup_screen(); simple_timer(); cleanup_screen(); return 0; }
static int control(uint32_t request, void *data) { switch(request) { case VOCTRL_GET_IMAGE: return get_image(data); case VOCTRL_QUERY_FORMAT: switch(*((uint32_t*)data)) { case IMGFMT_YV12: case IMGFMT_I420: case IMGFMT_IYUV: case IMGFMT_YUY2: case IMGFMT_UYVY: case IMGFMT_BGR16: case IMGFMT_BGR24: case IMGFMT_BGR32: return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN; } return 0; /* Not supported */ case VOCTRL_FULLSCREEN: setup_screen(!vo_fs); return 0; } return VO_NOTIMPL; }
int main( void ) { srand( time( NULL ) ); setup_screen(); demo(); cleanup_screen(); return 0; }
int main( void ) { Game game; setup_screen(); game.dog = create_sprite( 0, 0, 1, 1, "D" ); draw_sprite( game.dog ); wait_char(); cleanup_screen(); }
int main( void ) { setup_screen(); srand( time( NULL ) ); demo(); timer_pause( 5000 ); cleanup_screen(); return 0; }
int main() { setup_screen(); draw_paddles(); draw_string(0, screen_height( ) - 1, "Press any key to finish..."); wait_char(); cleanup_screen(); return 0; }
int main(int argc, char *argv[]) { struct timeval t_start, t_stop; srandom(time(NULL)); setup_screen(); setup_players(); gettimeofday(&t_start, NULL); clrscr(); frame_counter = 0; alive_count = n_players; while ((alive_count > 1) && !Button()) { do_frame(); frame_counter++; { struct timeval t_now; gettimeofday(&t_now, NULL); useconds_t d = (t_now.tv_sec - t_start.tv_sec) * 1000000 + (t_now.tv_usec - t_start.tv_usec); long nap = frame_counter * (1000000.0 / TARGET_FPS) - d; if (nap > 0) { usleep(nap); } } } gettimeofday(&t_stop, NULL); { long delta = (t_stop.tv_sec - t_start.tv_sec) * 1000000 + (t_stop.tv_usec - t_start.tv_usec); printf("%d frames took %lu microseconds, so %g frames/sec\n", frame_counter, delta, frame_counter / (delta / 1000000.0)); } { int i; for (i = 0; i < n_players; i++) { player_t *p = &players[i]; if (p->is_dead) { printf("player %d DIED\n", i); } else { printf("PLAYER %d SURVIVED!!!\n", i); } } } }
int main() { srand(time(NULL)); setup_screen(); int start_x; int start_y; get_start_pos(&start_x, &start_y); zombie_racer(start_x, start_y); cleanup_screen(); return 0; }
int main( void ) { setup_screen(); draw_string( 10, 10, "Hello CAB202!!!" ); show_screen(); while ( 1 ) { play_one_square(); play_ten_squares(); walk_the_walk(); } return 0; }
int UIItems_PlatformC(int index, int reason) { int zoomchanged = 0; if (reason == UIMENU_OK) { reason = UIMENU_RIGHT; } if (reason == UIMENU_CANCEL) { UIMenu_PrevMenu(); } if (reason == UIMENU_LEFT) { switch (index) { case 1: // Zoom clc_zoom--; if (clc_zoom < 1) clc_zoom = 4; zoomchanged = 1; break; case 2: // Display FPS clc_displayfps = !clc_displayfps; break; } } if (reason == UIMENU_RIGHT) { switch (index) { case 1: // Zoom clc_zoom++; if (clc_zoom > 4) clc_zoom = 1; zoomchanged = 1; break; case 2: // Display FPS clc_displayfps = !clc_displayfps; break; case 9: // Define joystick JoystickEnterMenu(); break; } } UIMenu_ChangeItem(UIItems_Platform, 1, "Zoom: %s", clc_zoom_txt[clc_zoom]); UIMenu_ChangeItem(UIItems_Platform, 2, "Display FPS: %s", clc_displayfps ? "Yes" : "No"); if (zoomchanged) setup_screen(); return 1; }
int main(void) { struct winsize w; static pa_simple *server; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); //get info on size of screen if(w.ws_col < 5 | w.ws_row < 5) { puts("Fix your terminal m9."); exit(1); } float read_buffer[N]; //buffer into which data will be read double end_buffer[N]; //buffer used as input to fftw fftw_complex out[N]; //buffer for output from fftw #ifdef SMOOTHING unsigned int avg[SMOOTHING][w.ws_col]; #endif char current = 0; unsigned int col; long unsigned int i; #ifdef SMOOTHING i = SMOOTHING; while(i--) memset(avg[i], 0, sizeof(unsigned int) * w.ws_col); #endif server = pulseaudio_begin(); setup_screen(); printf("\e[1;1HAttempting search for most efficient DFT algorithm... FFTW_PATIENT"); fflush(stdout); fftw_plan p = fftw_plan_dft_r2c_1d(N, end_buffer, out, FFTW_PATIENT); while(run) { pulseaudio_read(server, read_buffer, N); for(i = 0; i < N; i++) { end_buffer[i] = (read_buffer[i] * (0.5f * (1 - cos(2 * PI * i / (N - 1))))) * INPUT_AMPLIFY; //apply hann window } fftw_execute(p); printf("\e[f"); #ifdef LOG unsigned int last = 0; #endif for(i = 1; i < w.ws_col + 1; i++) { double freq_logvalue; #ifdef LOG unsigned long int pos = i * i * ((N - TOP_FREQ_SUB) / 2) / (w.ws_col*w.ws_col); if(pos<=last) pos = last + 1; if(pos >= N/2) pos = N/2 - 1; last = (unsigned int) pos; freq_logvalue = log10(cabs(out[pos]) / (N / 2)) * AMPLIFY; //normalize #else freq_logvalue = log10(cabs(out[i * ((N - TOP_FREQ_SUB) / 2) / w.ws_col]) / (N / 2)) * AMPLIFY; #endif freq_logvalue = 1 - (freq_logvalue > -CUTOFF ? freq_logvalue : -CUTOFF) / -CUTOFF; //cut out at -80 col = (unsigned int) ((freq_logvalue > 1 ? 1 : freq_logvalue) * w.ws_row); #ifdef SMOOTHING avg[current][i - 1] = col; } current++; if(current == SMOOTHING) current = 0; for(i = 1; i < w.ws_col + 1; i++) { //col = (avg[0][i - 1] + avg[1][i - 1]) / 2; unsigned char sm = SMOOTHING; col = 0; while(sm--) { col += avg[sm][i - 1]; } col /= SMOOTHING; #endif puts("\e[1;1H"); if(col > (unsigned int) (0.75 * w.ws_row)) puts("\e[31m"); else if(col > (unsigned int) (0.55 * w.ws_row)) puts("\e[33m"); else puts("\e[32m"); prnt('|', col, (unsigned int) i, w.ws_row); prnt(' ', w.ws_row - col, (unsigned int) i, w.ws_row - col); } fflush(stdout); //gotta go faster than that TODO: add some timing functions to cap framerate } clean_screen(); pulseaudio_end(server); return EXIT_SUCCESS; }
int main(int argc, char **argv) { FILE *file; int samples; char *sample_buffer; int rtn, final_return_code = -1, exit_application = 0; int bsize, bytes_read, total_written = 0; fd_set rfds, wfds; char input_file[PATH_MAX]; char cwd[PATH_MAX]; /* * Before we can listen for events from the BlackBerry Tablet OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); if (setup_screen() != EXIT_SUCCESS) { printf("Unable to set up the screen. Exiting."); exit(-1); } /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry Tablet OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * * For this sample, we request Navigator events so we can track when * the system is terminating the application (NAVIGATOR_EXIT event). * This allows us to clean up application resources. * * We request Audio Device events because we want to make sure that * we properly handle changes in audio output. * * We request dialog events to properly initialize the dialog * subsystem in order to display status and error messages. */ if (BPS_SUCCESS != navigator_request_events(0)) { fprintf(stderr, "Error requesting navigator events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != dialog_request_events(0)) { fprintf(stderr, "Error requesting dialog events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != audiodevice_request_events(0)) { fprintf(stderr, "Error requesting audio device events: %s", strerror(errno)); exit(-1); } /* * Create and display the dialog. */ create_dialog(); /* * Open and check the input file. */ getcwd(cwd, PATH_MAX); rtn = snprintf(input_file, PATH_MAX, "%s/%s", cwd, WAV_RELATIVE_PATH); if (rtn > PATH_MAX - 1) { err("File name and path too long"); goto fail1; } if ((file = fopen(input_file, "r")) == 0) { err("File open failed"); goto fail1; } if (check_hdr(file) == -1) { err("check_hdr failed"); goto fail2; } /* * Parse the headers in the wav file to figure out what kind of data we * are dealing with in the file. */ samples = find_tag(file, "fmt "); fread(&wav_header, sizeof(wav_header), 1, file); fseek(file,(samples - sizeof(wave_hdr)), SEEK_CUR); sample_rate = ENDIAN_LE32(wav_header.samples_per_sec); sample_channels = ENDIAN_LE16(wav_header.channels); sample_bits = ENDIAN_LE16(wav_header.bits_per_sample); snprintf(msg, MSG_SIZE, "SampleRate = %d, channels = %d, SampleBits = %d\n", sample_rate, sample_channels, sample_bits); show_dialog_message(msg); if (setup_snd(NULL)) { goto fail2; } bsize = setup.buf.block.frag_size; samples = find_tag(file, "data"); sample_buffer = malloc(bsize); if (!sample_buffer) { goto fail3; } FD_ZERO(&rfds); FD_ZERO(&wfds); bytes_read = 1; while (total_written < samples && bytes_read > 0 ) { bps_event_t *event = NULL; while (BPS_SUCCESS == bps_get_event(&event, 0) && event) { /* * If it is a NAVIGATOR_EXIT event then we are done so stop * processing events, clean up and exit */ if (bps_event_get_domain(event) == navigator_get_domain()) { if (NAVIGATOR_EXIT == bps_event_get_code(event)) { exit_application = 1; goto success; } } if (bps_event_get_domain(event) == audiodevice_get_domain()) { /* * If it is a audio device event then it means a new audio device * has been enabled and a switch is required. We close the old, * open the new audio device using the path and get the card number so * that we can close and re-open the mixer with the new card * number. */ const char * audiodevice_path = audiodevice_event_get_path(event); if (NULL == audiodevice_path) { snprintf(msg, MSG_SIZE, "audiodevice_event_get_path failed: %s\n", snd_strerror(rtn)); show_dialog_message(msg); goto fail5; } if ((rtn = snd_mixer_close(mixer_handle)) < 0) { snprintf(msg, MSG_SIZE, "snd_mixer_close failed: %s\n", snd_strerror(rtn)); show_dialog_message(msg); goto fail4; } if ((rtn = snd_pcm_close(pcm_handle)) < 0) { snprintf(msg, MSG_SIZE, "snd_pcm_close failed: %s\n", snd_strerror(rtn)); show_dialog_message(msg); goto fail3; } if (setup_snd(audiodevice_path)) { /* * setup_snd() closes pcm and mixer handles in the case of error so we * skip clean up of the handles in the case of failure. */ goto fail3; } } } if (tcgetpgrp(0) == getpid()) FD_SET(STDIN_FILENO, &rfds); FD_SET(snd_mixer_file_descriptor(mixer_handle), &rfds); FD_SET(snd_pcm_file_descriptor(pcm_handle, SND_PCM_CHANNEL_PLAYBACK), &wfds); rtn = max(snd_mixer_file_descriptor(mixer_handle), snd_pcm_file_descriptor(pcm_handle, SND_PCM_CHANNEL_PLAYBACK)); if (select(rtn + 1, &rfds, &wfds, NULL, NULL) == -1) { err("select"); goto fail5; } if (FD_ISSET(snd_pcm_file_descriptor(pcm_handle, SND_PCM_CHANNEL_PLAYBACK), &wfds)) { snd_pcm_channel_status_t status; int written = 0; if ((bytes_read = fread(sample_buffer, 1, min(samples - total_written, bsize), file)) <= 0) continue; written = snd_pcm_plugin_write(pcm_handle, sample_buffer, bytes_read); if (written < bytes_read) { memset(&status, 0, sizeof(status)); status.channel = SND_PCM_CHANNEL_PLAYBACK; if (snd_pcm_plugin_status(pcm_handle, &status) < 0) { show_dialog_message("underrun: playback channel status error\n"); goto fail5; } if (status.status == SND_PCM_STATUS_READY || status.status == SND_PCM_STATUS_UNDERRUN) { if (snd_pcm_plugin_prepare(pcm_handle, SND_PCM_CHANNEL_PLAYBACK) < 0) { show_dialog_message("underrun: playback channel prepare error\n"); goto fail5; } } if (written < 0) written = 0; written += snd_pcm_plugin_write(pcm_handle, sample_buffer + written, bytes_read - written); } total_written += written; } } success: bytes_read = snd_pcm_plugin_flush(pcm_handle, SND_PCM_CHANNEL_PLAYBACK); final_return_code = 0; /* * there are return codes to these close calls, but we would do the same * thing regardless of error or success so we do not check the return codes. */ fail5: snd_mixer_close(mixer_handle); fail4: snd_pcm_close(pcm_handle); fail3: free(sample_buffer); sample_buffer = NULL; fail2: fclose(file); fail1: while (!exit_application) { /* * Something went wrong so there is probably an error message and * we don't want to exit right away because we want the user to see * the message in the dialog. * * Using a negative timeout (-1) in the call to bps_get_event(...) * ensures that we don't busy wait by blocking until an event is * available. */ bps_event_t *event = NULL; bps_get_event(&event, -1); if (event) { /* * If it is a NAVIGATOR_EXIT event then we are done so stop * processing events, clean up and exit */ if (bps_event_get_domain(event) == navigator_get_domain()) { if (NAVIGATOR_EXIT == bps_event_get_code(event)) { exit_application = 1; } } } } /* * Destroy the dialog, if it exists and cleanup screen resources. */ destroy_dialog(); cleanup_screen(); bps_shutdown(); return final_return_code; }
void get_current() { int c,lc,i=0; raw(); noecho(); keypad(stdscr, TRUE); while ((c=getch())) { if (c == '\t') // Tab { if (showing) tab_hits_down(); else { clrtobot(); if (current_length > 1) { hunt_current(); show_hits(); tab_hits_down(); } } } else if (c == '\n' && lc == '\n') break; // two-returns to quit else if (c == 27) { exiting=1;break;break; } // ESC quit else if (c == 'J' || c == 258) // J | d-arrow down hit list tab_hits_down(); else if (c == 'K' || c == 353 || c == 259) // K | <shift-TAB> | u-arrow up hit list tab_hits_up(); else if (c == 32) // SPACE to reset search { memset(current,'\0',MAX_LINE); current_length = 0; clear_matches(); setup_screen(); mvprintw(LINES - 2, 0, "!: %s", items); move(cursor_row,cursor_col+3); refresh(); i=0; } else if (c == 127 || c == 8) // DELETE or BACKSPACE { if (current_length > 0 ) { i--; current_length--; current[i] = '\0'; clrtobot(); mvprintw(LINES - 2, 0, "!: %s", items); backspace(); move(cursor_row,cursor_col); getsyx(cursor_row,cursor_col); if (showing && current_length > 1) { hunt_current(); show_hits(); tab_hits_down(); } } } else if (c=='\n') // SELECT hightlighted hit or typed word { if (showing && sel_match>-1) strcat(items,tags[matches[sel_match].index]); else strcat(items,current); memset(current,'\0',MAX_LINE); current_length=i=0; setup_screen(); showing=FALSE; strcat(items," "); mvprintw(LINES - 2, 0, "!: %s", items); move(cursor_row,cursor_col+3); refresh(); } else // regular key-typed { addch(c); current[i]=c; ++i; ++current_length; refresh(); getsyx(cursor_row,cursor_col); if (showing && (current_length > 1)) { noraw(); delch(); raw(); refresh(); hunt_current(); show_hits(); tab_hits_down(); } else showing=FALSE; } lc = c; if (diags) diag(c); } current[i] = '\0'; }
void Configuration::toggleFullscreen() { fullscreen = !fullscreen; fullscreen = setup_screen(fullscreen); }
static int config(uint32_t width, uint32_t height, uint32_t d_width, uint32_t d_height, uint32_t flags, char *title, uint32_t format) { screenwidth = fb_vinfo.xres; screenheight = fb_vinfo.yres; screenstride = fb_finfo.line_length; aspect_save_screenres(fb_vinfo.xres,fb_vinfo.yres); in_width = width; in_height = height; in_format = format; aspect_save_orig(width,height); aspect_save_prescale(d_width,d_height); /* Setup the screen for rendering to */ screendepth = fb_vinfo.bits_per_pixel / 8; switch(in_format) { case IMGFMT_YUY2: in_depth = 2; in_s3_format = 1; alpha_func = vo_draw_alpha_yuy2; break; case IMGFMT_BGR15: in_depth = 2; in_s3_format = 3; alpha_func = vo_draw_alpha_rgb16; break; case IMGFMT_BGR16: in_depth = 2; in_s3_format = 5; alpha_func = vo_draw_alpha_rgb16; break; case IMGFMT_BGR24: in_depth = 3; in_s3_format = 6; alpha_func = vo_draw_alpha_rgb24; break; case IMGFMT_BGR32: in_depth = 4; in_s3_format = 7; alpha_func = vo_draw_alpha_rgb32; break; default: mp_msg(MSGT_VO, MSGL_FATAL, "s3fb: Eik! Something's wrong with control().\n"); return -1; } offset = in_width * in_depth * in_height; if (vo_doublebuffering) page = offset; else page = 0; if(screenheight * screenstride + page + offset > fb_finfo.smem_len) { mp_msg(MSGT_VO, MSGL_FATAL, "s3fb: Not enough video memory to play this movie. Try at a lower resolution\n"); return -1; } setup_screen(flags & VOFLAG_FULLSCREEN); if (vo_doublebuffering) inpage = inpage0 + page; mp_msg(MSGT_VO, MSGL_INFO, "s3fb: screen is %dx%d at %d bpp, in is %dx%d at %d bpp, norm is %dx%d\n", screenwidth, screenheight, screendepth * 8, in_width, in_height, in_depth * 8, d_width, d_height); return 0; }
static int config(uint32_t width, uint32_t height, uint32_t d_width, uint32_t d_height, uint32_t flags, char *title, uint32_t format) { screenwidth = fb_vinfo.xres; screenheight = fb_vinfo.yres; aspect_save_screenres(fb_vinfo.xres,fb_vinfo.yres); in_width = width; in_height = height; in_format = format; aspect_save_orig(width,height); r_width = d_width; r_height = d_height; aspect_save_prescale(d_width,d_height); /* Setup the screen for rendering to */ switch(fb_vinfo.bits_per_pixel) { case 16: screendepth = 2; vid_voodoo_format = VOODOO_BLT_FORMAT_16; alpha_func_double = vo_draw_alpha_rgb16; break; case 24: screendepth = 3; vid_voodoo_format = VOODOO_BLT_FORMAT_24; alpha_func_double = vo_draw_alpha_rgb24; break; case 32: screendepth = 4; vid_voodoo_format = VOODOO_BLT_FORMAT_32; alpha_func_double = vo_draw_alpha_rgb32; break; default: mp_msg(MSGT_VO, MSGL_ERR, MSGTR_LIBVO_TDFXFB_BppOutputIsNotSupported, fb_vinfo.bits_per_pixel); return -1; } vid_voodoo_format |= screenwidth * screendepth; /* Some defaults here */ in_voodoo_format = VOODOO_BLT_FORMAT_YUYV; in_depth = 2; alpha_func = vo_draw_alpha_yuy2; switch(in_format) { case IMGFMT_YV12: case IMGFMT_I420: case IMGFMT_IYUV: case IMGFMT_YUY2: break; case IMGFMT_UYVY: in_voodoo_format = VOODOO_BLT_FORMAT_UYVY; break; case IMGFMT_BGR16: in_voodoo_format = VOODOO_BLT_FORMAT_16; alpha_func = vo_draw_alpha_rgb16; break; case IMGFMT_BGR24: in_depth = 3; in_voodoo_format = VOODOO_BLT_FORMAT_24; alpha_func = vo_draw_alpha_rgb24; break; case IMGFMT_BGR32: in_depth = 4; in_voodoo_format = VOODOO_BLT_FORMAT_32; alpha_func = vo_draw_alpha_rgb32; break; default: mp_msg(MSGT_VO,MSGL_ERR, MSGTR_LIBVO_TDFXFB_SomethingIsWrongWithControl); return -1; } in_voodoo_format |= in_width * in_depth; /* Linux lives in the first frame */ if(vo_doublebuffering) { vidpageoffset = screenwidth * screenheight * screendepth; hidpageoffset = vidpageoffset + screenwidth * screenheight * screendepth; } else vidpageoffset = hidpageoffset = 0; /* Console background */ inpageoffset = hidpageoffset + screenwidth * screenheight * screendepth; if(inpageoffset + in_width * in_depth * in_height > fb_finfo.smem_len) { mp_msg(MSGT_VO,MSGL_ERR, MSGTR_LIBVO_TDFXFB_NotEnoughVideoMemoryToPlay); return -1; } vidpage = (void *)memBase1 + (unsigned long)vidpageoffset; hidpage = (void *)memBase1 + (unsigned long)hidpageoffset; inpage = (void *)memBase1 + (unsigned long)inpageoffset; setup_screen(flags & VOFLAG_FULLSCREEN); memset(inpage, 0, in_width * in_height * in_depth); mp_msg(MSGT_VO,MSGL_INFO, MSGTR_LIBVO_TDFXFB_ScreenIs, screenwidth, screenheight, screendepth * 8, in_width, in_height, in_depth * 8, d_width, d_height); return 0; }
int main( int argc, char **argv ) { const char *mmrname = NULL; const char *ctxtname = "testplayer"; const char *audioout = NULL; const char *inputtype = "track"; char cwd[PATH_MAX]; char inputurl[PATH_MAX]; int rc; int final_return_code = EXIT_FAILURE; int exit_application = 0; mmr_connection_t *connection = NULL; mmr_context_t *ctxt = NULL; /* * Before we can listen for events from the BlackBerry(R) 10 OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); if (setup_screen() != EXIT_SUCCESS) { printf("Unable to set up the screen. Exiting."); return 0; } /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry(R) 10 OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * For this sample, we request Navigator events so we can track when * the system is terminating the application (NAVIGATOR_EXIT event). * This allows us to clean up application resources. */ navigator_request_events(0); dialog_request_events(0); /* * Create and display the dialog. */ create_dialog(); getcwd(cwd, PATH_MAX); rc = snprintf(inputurl, PATH_MAX, "file://%s%s", cwd, WAV_RELATIVE_PATH); if (rc > PATH_MAX - 1) { show_dialog_message("File name and path too long"); goto fail; } mode_t mode = S_IRUSR | S_IXUSR; int audio_oid; // output ID strm_dict_t *aoparams = NULL; // output parameters audioout = DEFAULT_AUDIO_OUT; if ( ( connection = mmr_connect( mmrname ) ) == NULL ) { snprintf(msg, MSG_SIZE, "mmr_connect: %s", strerror(errno)); show_dialog_message(msg); } else if ( ( ctxt = mmr_context_create( connection, ctxtname, 0, mode ) ) == NULL ) { snprintf(msg, MSG_SIZE, "%s: %s", ctxtname, strerror(errno)); show_dialog_message(msg); } else if ( audioout && ( audio_oid = mmr_output_attach( ctxt, audioout, "audio" ) ) < 0 ) { mmrerror( ctxt, audioout ); } else if ( aoparams && mmr_output_parameters( ctxt, audio_oid, aoparams ) ) { mmrerror( ctxt, "output parameters (audio)" ); } else if ( mmr_input_attach( ctxt, inputurl, inputtype ) < 0 ) { mmrerror( ctxt, inputurl ); } else if ( mmr_play( ctxt ) < 0 ) { mmrerror( ctxt, "mmr_play" ); } else if (BPS_SUCCESS != bps_add_sigevent_handler( &mmr_sigevent, mmr_sigevent_handler, ctxt ) ) { snprintf( msg, MSG_SIZE, "bps_add_sigevent_handler() failure %s", strerror( errno ) ); show_dialog_message( msg ); } else if ( drain_and_arm_mmr_events ( ctxt ) ) { snprintf( msg, MSG_SIZE, "drain_and_arm_mmr_events() failure %s", strerror( errno ) ); show_dialog_message( msg ); } else { show_dialog_message( "Playing Audio\n" ); final_return_code = EXIT_SUCCESS; } fail: /* * Process Navigator events until we receive a NAVIGATOR_EXIT event. */ while (!exit_application) { /* * Using a negative timeout (-1) in the call to bps_get_event(...) * ensures that we don't busy wait by blocking until an event is * available. */ bps_event_t *event = NULL; bps_get_event(&event, -1); if (event) { /* * If it is a NAVIGATOR_EXIT event then set the exit_application * flag so the application will stop processing events, clean up * and exit */ if (bps_event_get_domain(event) == navigator_get_domain()) { if (NAVIGATOR_EXIT == bps_event_get_code(event)) { if (final_return_code == EXIT_SUCCESS) { mmr_stop( ctxt ); // Not really necessary -- mmr_input_detach() would take care of this mmr_input_detach( ctxt ); // Not really necessary -- mmr_context_destroy() would take care of this mmr_context_destroy( ctxt ); // Not really necessary -- mmr_disconnect() would take care of this mmr_disconnect( connection ); // Not really necessary -- exiting would take care of this } exit_application = 1; } } else if (bps_event_get_domain(event) == dialog_get_domain()) { if (DIALOG_RESPONSE == bps_event_get_code(event)) { handle_dialog_response_events(event); } } } } /* * Destroy the dialog, if it exists and cleanup screen resources. */ destroy_dialog(); cleanup_screen(); /* * Clean up the BPS infrastructure and exit */ bps_shutdown(); return final_return_code; }
int main(int argc, const char * argv[]) { size_t i; if (argc==1) // no arguments { show_basics(); return 0; } for (i = 1; i < argc; i++) // parse arguments { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'f':strcpy(infile,argv[++i]); break; case 'o':strcpy(outfile,argv[++i]); break; case 'd':diags=TRUE; break; } } } if (strlen(infile)>0) // read file for tags { num_tags=flen(infile); get_file(); } else // read string from stdin for tags { i=0; char *s,*t,*nt; t = strdup(argv[argc-1]); // string of tags, space-delimted nt = strdup(argv[argc-1]); num_tags = num_splits(nt); tags = malloc(sizeof(*tags) * num_tags); s=strtok(t," "); // ashen while (s != NULL) { tags[i] = strdup(s); s = strtok (NULL, " "); ++i; } num_tags=i; } matches = malloc(num_tags * sizeof(struct match)); setup_screen(); get_current(); items[strlen(items)-1]='\0'; // remove trailing space-separation char endwin(); if (!exiting) { if (strlen(outfile)>0) put_file(); else printf("%s\n",items); } // be kind and free up allocations for(i = 0; i < num_tags; i++) free(tags[i]); // free tags free(tags); free(matches); return 0; }
// This is Main, there are many others like it but this is the main one... int main() { setup_screen(); Megamaniac(); cleanup_screen(); return 0; }
/** * A sample application that demonstrates the BlackBerry(R) 10 Native SDK APIs * for geolocation. */ int main(int argc, char *argv[]) { bool exit_application = false; /* * Before we can listen for events from the BlackBerry(R) 10 OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); /* * Initialize the screen so that the window group Id is properly set, to allow * the dialogs to be displayed. */ if (setup_screen() != EXIT_SUCCESS) { fprintf(stderr, "Unable to initialize screen."); exit(-1); } /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry(R) 10 OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * * For this sample, we request Navigator events so that we can track when * the system is terminating the application (NAVIGATOR_EXIT event). * * We request dialog events so we can be notified when the dialog service * responds to our requests/queries. * * We request geolocation events so that we can be notified of our current * geolocation. */ if (BPS_SUCCESS != navigator_request_events(0)) { fprintf(stderr, "Error requesting navigator events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != dialog_request_events(0)) { fprintf(stderr, "Error requesting dialog events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != geolocation_request_events(0)) { fprintf(stderr, "Error requesting geolocation events: %s", strerror(errno)); exit(-1); } /* * Get geolocation events once a second, which is the most often that they * are capable of being reported. */ geolocation_set_period(1); /* * Create and display the dialog that will show the geolocation data. */ create_dialog(); show_dialog_message("Geolocation getting first fix"); /* * Process Geolocation, Dialog and Navigator events until we receive a * NAVIGATOR_EXIT event. */ while (!exit_application) { /* * Using a negative timeout (-1) in the call to bps_get_event(...) * ensures that we don't busy wait by blocking until an event is * available. */ bps_event_t *event = NULL; bps_get_event(&event, -1); if (event) { /* * If it is a geolocation event, determine the response code and * handle the event accordingly. */ if (bps_event_get_domain(event) == geolocation_get_domain()) { handle_geolocation_response(event); } /* * If it is a dialog event, determine the response code and handle * the event accordingly. */ else if (bps_event_get_domain(event) == dialog_get_domain()) { /* We have no buttons so we don't need to do anything. */ ; } /* * If it is a NAVIGATOR_EXIT event then set the exit_application * flag so the application will stop processing events, clean up and * exit. */ else if (bps_event_get_domain(event) == navigator_get_domain()) { exit_application = handle_navigator_event(event); } } } /* * Stop geolocation events. */ geolocation_stop_events(0); /* * Destroy the dialog, if it exists. */ destroy_dialog(); /* * Clean up the bps infrastructure and exit */ bps_shutdown(); cleanup_screen(); return 0; }
/** * A sample application demonstrates the BlackBerry Native APIs for accelerometer. * The sample initializes and reads the accelerometer periodically until a * NAVIGATOR_EXIT event is received. * The application also listens for window state changes from the navigator so that * it can stop reading the accelerometer when the application is no longer visible. */ int main(int argc, char *argv[]) { if (setup_screen() != EXIT_SUCCESS) { printf("Unable to set up the screen. Exiting."); return 0; } /* * The accelerometer forces */ double force_x, force_y, force_z; /* * Before we can listen for events from the BlackBerry Tablet OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry Tablet OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * For this sample, we request Navigator events so we can track when * the system is terminating the application (NAVIGATOR_EXIT event). This allows * us to clean up application resources. */ navigator_request_events(0); /* * Before initializing the accelerometer service we must ensure the device * supports it */ if (!accelerometer_is_supported()) { /* * If the device does not support accelerometer then notify the user, * clean up and exit */ printf("Accelerometer not supported by device!"); bps_shutdown(); return EXIT_FAILURE; } /* * Initialize the accelerometer by setting the rates at which the * accelerometer values will be updated from hardware */ accelerometer_set_update_frequency(FREQ_40_HZ); /* * Process Navigator events and take accelerometer readings periodically * until we receive a NAVIGATOR_EXIT event. */ int exit_application = 0; int paused = 0; while (!exit_application) { /* * By setting the bps_get_event timeout to ACCELEROMETER_MAX_POLL_INTERVAL, * we assign the maximum time (in millis) that we will wait before * unblocking so we can take an accelerometer reading. */ bps_event_t *event = NULL; bps_get_event(&event, ACCELEROMETER_MAX_POLL_INTERVAL); if (event) { if (bps_event_get_domain(event) == navigator_get_domain()) { /* * If it is a NAVIGATOR_EXIT event then set the * exit_application flag so the application will stop * processing events, clean up and exit. * * If it is a NAVIGATOR_WINDOW_STATE event, and the window * state is NAVIGATOR_WINDOW_INVISIBLE, set paused to true so * that we stop collecting accelerometer data. Otherwise, if * we're currently paused, then set paused back to false to * resume collecting accelerometer data. */ unsigned int event_code = bps_event_get_code(event); if (NAVIGATOR_EXIT == event_code) { exit_application = 1; } else if (NAVIGATOR_WINDOW_STATE == event_code) { if (navigator_event_get_window_state(event) == NAVIGATOR_WINDOW_FULLSCREEN) { /* * The application is now full screen. * Resume reading the accelerometer. */ paused = 0; printf("Resuming accelerometer reads.\n"); } else if (!paused){ /* * The application has become thumbnailed or invisible. * If it is not already paused, then pause it. * Otherwise, ignore the window state change. */ paused = 1; printf("Resuming accelerometer reads.\n"); } } } /* * Remember to destroy any delivered events as we need to trigger * the release of any event resources when we are done processing * it. */ bps_event_destroy(event); } else { /* * We've woken up. See if we are in the paused state. If not, * take an accelerometer reading */ if (!paused) { accelerometer_read_forces(&force_x, &force_y, &force_z); display_accelerometer_reading( ACCELEROMETER_CALCULATE_PITCH(force_x, force_y, force_z), ACCELEROMETER_CALCULATE_ROLL(force_x, force_y, force_z)); } } } /* * Clean up screen resources */ screen_destroy_window(screen_win); screen_destroy_context(screen_ctx); /* * Clean up the BPS infrastructure and exit */ bps_shutdown(); return 0; }
// Main function int main(int argc, char **argv) { int battimeout = 0; char fpstxt[16]; // Open debug files PokeDebugFOut = fopen("dbg_stdout.txt", "w"); PokeDebugFErr = fopen("dbg_stderr.txt", "w"); // Init video PokeDPrint(POKEMSG_OUT, "%s\n\n", AppName); PokeMini_InitDirs(argv[0], NULL); CommandLineInit(); CommandLine.low_battery = 2; // PSP can report battery status CommandLineConfFile("pokemini.cfg", "pokemini_psp.cfg", CustomConf); JoystickSetup("PSP", 0, 30000, PSP_KeysNames, 16, PSP_KeysMapping); // PSP Init and set screen PSP_Init(); setup_screen(); // Create emulator and load test roms PokeDPrint(POKEMSG_OUT, "Starting emulator...\n"); PokeMini_Create(POKEMINI_GENSOUND | POKEMINI_AUTOBATT, 0); // Setup palette and LCD mode PokeMini_VideoPalette_Init(PokeMini_RGB16, 1); PokeMini_VideoPalette_Index(CommandLine.palette, CommandLine.custompal, CommandLine.lcdcontrast, CommandLine.lcdbright); PokeMini_ApplyChanges(); // Load stuff PokeMini_UseDefaultCallbacks(); if (!PokeMini_LoadFromCommandLines("Using FreeBIOS", "EEPROM data will be discarded!")) { UI_Status = UI_STATUS_MENU; } // Enable sound & init UI PokeDPrint(POKEMSG_OUT, "Running emulator...\n"); UIMenu_Init(); enablesound(CommandLine.sound); sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); // Emulator's loop u64 tickcurr; u64 fpsticknext,fpstickres = (u64)sceRtcGetTickResolution(); u64 frmticknext, frmtickres = (u64)sceRtcGetTickResolution() / 36; sceRtcGetCurrentTick(&tickcurr); fpsticknext = tickcurr + fpstickres; frmticknext = tickcurr + frmtickres; int fps = 72, fpscnt = 0; strcpy(fpstxt, ""); while (emurunning) { // Emulate 2 frames PokeMini_EmulateFrame(); PokeMini_EmulateFrame(); if (RequireSoundSync) { while (MinxAudio_SyncWithAudio()) sceKernelDelayThread(1000); } else { do { sceRtcGetCurrentTick(&tickcurr); sceKernelDelayThread(1000); } while (tickcurr < frmticknext); frmticknext = tickcurr + frmtickres; // Aprox 36 times per sec } // Screen rendering PSP_ClearDraw(); if (PokeMini_Rumbling) { PokeMini_VideoBlit((uint16_t *)PSP_DrawVideo + pm_offset + PokeMini_GenRumbleOffset(512), 512); } else { PokeMini_VideoBlit((uint16_t *)PSP_DrawVideo + pm_offset, 512); } LCDDirty = 0; // Display FPS counter if (clc_displayfps) { sceRtcGetCurrentTick(&tickcurr); if (tickcurr >= fpsticknext) { fpsticknext = tickcurr + fpstickres; fps = fpscnt; fpscnt = 0; sprintf(fpstxt, "%i FPS", fps); } else fpscnt++; UIDraw_String_16((uint16_t *)PSP_DrawVideo, 512, 4, 4, 10, fpstxt, UI_Font1_Pal16); } // Handle keys HandleKeys(); // Menu if (UI_Status == UI_STATUS_MENU) menuloop(); // Wait VSync & Render (72 Hz) PSP_Flip(); // Check battery if (battimeout <= 0) { PokeMini_LowPower(scePowerIsLowBattery()); battimeout = 600; } else battimeout--; } // Stop sound & free UI enablesound(0); UIMenu_Destroy(); // Save Stuff PokeMini_SaveFromCommandLines(1); // Terminate... PokeDPrint(POKEMSG_OUT, "Shutdown emulator...\n"); PokeMini_VideoPalette_Free(); PokeMini_Destroy(); // Close debug files fclose(PokeDebugFOut); fclose(PokeDebugFErr); // PSP Quit PSP_Quit(); return 0; }
int main(int ac, char *av[]) { int f_usage = 0, f_list = 0, f_showscore = 0; int f_printpath = 0; const char *file = NULL; char *name, *ptr, *seed; struct sigaction sa; gid_t gid; #ifdef BSD struct itimerval itv; #endif open_score_file(); /* revoke privs */ gid = getgid(); setresgid(gid, gid, gid); start_time = time(0); makenoise = 1; seed = NULL; name = *av++; while (*av) { #ifndef SAVEDASH if (**av == '-') ++*av; else break; #endif ptr = *av++; while (*ptr) { switch (*ptr) { case '?': case 'u': f_usage++; break; case 'l': f_list++; break; case 's': case 't': f_showscore++; break; case 'p': f_printpath++; break; case 'q': makenoise = 0; break; case 'r': seed = *av; av++; break; case 'f': case 'g': file = *av; av++; break; default: warnx("unknown option '%c'", *ptr); f_usage++; break; } ptr++; } } if (seed != NULL) srandom(atol(seed)); else srandomdev(); if (f_usage) fprintf(stderr, "usage: %s [-lpqstu?] [-f game] [-g game] [-r seed]\n", name); if (f_showscore) log_score(1); if (f_list) list_games(); if (f_printpath) { size_t len; char buf[256]; strlcpy(buf, _PATH_GAMES, sizeof buf); len = strlen(buf); if (len != 0 && buf[len - 1] == '/') buf[len - 1] = '\0'; puts(buf); } if (f_usage || f_showscore || f_list || f_printpath) exit(0); if (file == NULL) file = default_game(); else file = okay_game(file); if (file == NULL || read_file(file) < 0) exit(1); setup_screen(sp); addplane(); signal(SIGINT, quit); signal(SIGQUIT, quit); #ifdef BSD signal(SIGTSTP, SIG_IGN); signal(SIGSTOP, SIG_IGN); #endif signal(SIGHUP, log_score_quit); signal(SIGTERM, log_score_quit); tcgetattr(fileno(stdin), &tty_start); tty_new = tty_start; tty_new.c_lflag &= ~(ICANON|ECHO); tty_new.c_iflag |= ICRNL; tty_new.c_cc[VMIN] = 1; tty_new.c_cc[VTIME] = 0; tcsetattr(fileno(stdin), TCSADRAIN, &tty_new); memset(&sa, 0, sizeof sa); sa.sa_handler = update; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGALRM); sigaddset(&sa.sa_mask, SIGINT); sa.sa_flags = 0; sigaction(SIGALRM, &sa, (struct sigaction *)0); #ifdef BSD itv.it_value.tv_sec = 0; itv.it_value.tv_usec = 1; itv.it_interval.tv_sec = sp->update_secs; itv.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(sp->update_secs); #endif for (;;) { if (getcommand() != 1) planewin(); else { #ifdef BSD itv.it_value.tv_sec = 0; itv.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(0); #endif update(0); #ifdef BSD itv.it_value.tv_sec = sp->update_secs; itv.it_value.tv_usec = 0; itv.it_interval.tv_sec = sp->update_secs; itv.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(sp->update_secs); #endif } } }
int main( int argc, char *argv[] ) { cufsetup( argc, argv ); setup_screen( ); fed( ); return 0; }
int main(int argc, char** argv) { FILE* oy; uint8_t flags = 1;//1 - EOF, 2 - reported error, 3 - img type uint8_t* imgsrc; if((oy = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Error opening file %s.\n", argv[1]); return EXIT_FAILURE; } int byte; int cnt = 4; const uint8_t magic_rev[4] = "EMEM"; //it's backwards. while((byte = fgetc(oy)) != EOF) { //magic if(byte!=magic_rev[--cnt]) { fprintf(stderr, "Invalid magic.\n"); flags = 2; break; } if(!cnt) { flags = 0; break; } } if(!(flags&3)) { //type byte = fgetc(oy); if(byte == EOF) { flags |= 1; } else if(byte>1) { fprintf(stderr, "Invalid image type \"%i\".\nExpected 0 - B/W or 1-RGB.\n", byte); flags |= 2; } else { flags |= byte<<2; } } if(!(flags&3)) { cnt = 450; if(flags&4) cnt = 10800; flags |= 1; imgsrc = calloc(cnt, sizeof(uint8_t)); int fcnt = 0; while((byte = fgetc(oy)) != EOF) { //data imgsrc[fcnt++] = (uint8_t)byte; if(fcnt==cnt) { flags &= ~1; if(fgetc(oy) != EOF) { fprintf(stderr, "Expected EOF, got data.\n"); free(imgsrc); flags |= 2; } break; } } } if(flags&1) { fprintf(stderr, "Unexpected EOF.\n"); } fclose(oy); if(flags&3) { return EXIT_FAILURE; } setup_screen(); struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int s = w.ws_col>w.ws_row*2?w.ws_row*2:w.ws_col; int sx = (w.ws_col-s)/2; int sy = (w.ws_row-s/2)/2; int rt = 360; if(flags&4) cnt = s*s*3; else cnt = (s*s)/8+!!((s*s)%8); uint8_t* rotout = calloc(cnt, sizeof(uint8_t)); if(flags&4) { resample8(s, s, &imgsrc); while(!kbhit()) { puts("\e[f"); rot8(--rt, s, s, imgsrc, rotout); rep8(sx, sy, s, s, rotout); usleep(50000); if(!rt) rt=360; } }
/** * A sample application that demonstrates the BlackBerry Native APIs for * managing locale. The sample queries for the current locale and then listens * for locale update events. */ int main(int argc, char *argv[]) { /* * Before we can listen for events from the BlackBerry Tablet OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); if (setup_screen() != EXIT_SUCCESS) { printf("Unable to set up the screen. Exiting."); return 0; } /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry Tablet OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * For this sample, we request Navigator events so that we can track when * the system is terminating the application (NAVIGATOR_EXIT event) as well * as Locale events so we can be notified when the locale is updated */ navigator_request_events(0); locale_request_events(0); dialog_request_events(0); /* * Create and display the dialog. */ create_dialog(); /* * Retrieve and display the current Locale using the locale_get(...) API */ char* country = NULL; char* language = NULL; locale_get(&language, &country); display_locale(language, country); bps_free((char*)language); bps_free((char*)country); /* * Process Locale and Navigator events until we receive a NAVIGATOR_EXIT event. */ int exit_application = 0; while (!exit_application) { /* * Using a negative timeout (-1) in the call to bps_get_event(...) * ensures that we don't busy wait by blocking until an event is * available. */ bps_event_t *event = NULL; bps_get_event(&event, -1); if (event) { if (bps_event_get_domain(event) == locale_get_domain()) { /* * If it is a LOCALE_INFO event then display the updated locale * information */ if (LOCALE_INFO == bps_event_get_code(event)) { /* * The locale_event_get_language and locale_event_get_country * calls return pointers to data within the event. When * the event is destroyed below via the call to * bps_event_destroy(event), the returned pointers would * reference deallocated memory. * * To avoid potentially having pointers to dereferenced * memory, we'll use local variables to store the pointers * into the event data. This way, the pointers will go * out of scope and thus cannot be used after the event * is freed. */ const char* language = locale_event_get_language(event); const char* country = locale_event_get_country(event); display_locale(language, country); } } /* * If it is a NAVIGATOR_EXIT event then set the exit_application * flag so the application will stop processing events, clean up * and exit */ if (bps_event_get_domain(event) == navigator_get_domain()) { if (NAVIGATOR_EXIT == bps_event_get_code(event)) { exit_application = 1; } } } } /* * Destroy the dialog, if it exists and cleanup screen resources. */ destroy_dialog(); cleanup_screen(); /* * Clean up the BPS infrastructure and exit */ bps_shutdown(); return 0; }
int main(int argc, char *argv[]) { int rc; int exit_application = 0; bps_initialize(); // Create and set up the app window. if (EXIT_FAILURE == setup_screen()) return EXIT_FAILURE; bbads_set_log_verbosity(2); // Display Banner on screen load_ad(screen_window, WINDOW_GROUP_NAME); screen_request_events(screen_context); navigator_request_events(0); /** * Handle keyboard events and stop playback upon user request. */ for (;;) { bps_event_t *event = 0; if (BPS_SUCCESS != bps_get_event(&event, -1)) { fprintf(stderr, "ERROR: Could not get BPS event!\n"); return EXIT_FAILURE; } if (event) { if (navigator_get_domain() == bps_event_get_domain(event)) { int code = bps_event_get_code(event); if (NAVIGATOR_EXIT == code) { if (BBADS_EOK != bbads_banner_destroy(ad_banner)) { fprintf(stderr, "cannot destroy banner"); } else { fprintf(stderr, "banner destroy"); } exit_application = 1; } } else if (bbads_get_domain() == bps_event_get_domain(event)) { bbads_banner_t* event_banner; bbads_event_get_banner(event, &event_banner); bbads_banner_event_type_t event_type = (bbads_banner_event_type_t)bps_event_get_code(event); banner_event_handler(event_banner, event_type); } else if (screen_get_domain() == bps_event_get_domain(event)) { int screen_val; char buf[1024]; int pos[2]; screen_event_t screen_event = screen_event_get_event(event); screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &screen_val); screen_get_event_property_cv(screen_event, SCREEN_PROPERTY_ID_STRING, sizeof(buf), buf); screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_POSITION, pos); switch (screen_val) { case SCREEN_EVENT_CREATE: fprintf(stderr, "create\n"); if (BBADS_EOK != bbads_banner_is_visible(ad_banner, &ad_is_visible)) { fprintf(stderr, "cannot get banner visibility"); } if (!ad_is_visible) { if (BBADS_EOK != bbads_banner_set_window_visible(ad_banner)) fprintf(stderr, "bbads_banner_set_window_visible has errors\n"); if (BBADS_EOK != bbads_banner_display(ad_banner, screen_context, event)) fprintf(stderr, "create cannot display banner\n"); } break; } if (exit_application) break; } } } screen_stop_events(screen_context); bps_shutdown(); if (screen_destroy_window(screen_window) != 0) return EXIT_FAILURE; if (screen_destroy_context(screen_context) != 0) return EXIT_FAILURE; screen_context = 0; screen_window = 0; return EXIT_SUCCESS; }
/** * The main entry point. */ int main(int argc, char *argv[]) { pthread_t accel_thread; bool exit_application = false; int rc; /* * Before we can listen for events from the BlackBerry Tablet OS platform * services, we need to initialize the BPS infrastructure */ bps_initialize(); /* * Initialize the screen so that the window group Id is properly set, * to allow the dialogs to be displayed. */ if (setup_screen() != EXIT_SUCCESS) { fprintf(stderr, "Unable to initialize screen."); exit(-1); } /* * Once the BPS infrastructure has been initialized we can register for * events from the various BlackBerry Tablet OS platform services. The * Navigator service manages and delivers application life cycle and * visibility events. * * We register a custom event domain so that we can communicate with the * the accelerometer thread. We will need to tell it to quit once we get * the NAVIGATOR_EXIT. * * We request Navigator events so that we can track when the system is * terminating the application (NAVIGATOR_EXIT event). * */ local_event_domain = bps_register_domain(); if (local_event_domain == -1) { fprintf(stderr, "Error registering custom event domain: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != navigator_request_events(0)) { fprintf(stderr, "Error requesting navigator events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != dialog_request_events(0)) { fprintf(stderr, "Error requesting dialog events: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != geolocation_request_events(0)) { fprintf(stderr, "Error requesting geolocation events: %s", strerror(errno)); exit(-1); } geolocation_set_period(1); /* * Create and display the dialogs that will show the data. */ create_top_dialog(); show_top_dialog_message("Geolocation getting first fix"); /* * Before initializing the accelerometer service we must ensure the device * supports it. */ if (!sensor_is_supported(SENSOR_TYPE_ACCELEROMETER)) { /** * If the device does not support accelerometer then notify the user, * clean up and exit */ snprintf(msg, MSG_SIZE, "Accelerometer not supported by device!"); show_top_dialog_message(msg); /* * Destroy the dialog, if it exists and cleanup screen resources. */ destroy_top_dialog(); cleanup_screen(); bps_shutdown(); return EXIT_FAILURE; } /* * Create the accelerometer event thread. */ rc = pthread_create(&accel_thread, NULL, accel_main, NULL); if (rc != 0) { fprintf(stderr, "Error in pthread_create: %s", strerror(errno)); exit(-1); } while (!exit_application) { /* * Using a negative timeout (-1) in the call to bps_get_event(...) * ensures that we don't busy wait by blocking until an event is * available. */ bps_event_t *event = NULL; bps_get_event(&event, -1); if (event) { if (bps_event_get_domain(event) == geolocation_get_domain()) { handle_geolocation_response(event); } else if (bps_event_get_domain(event) == navigator_get_domain()) { exit_application = handle_navigator_event(event); } } } geolocation_stop_events(0); /* * Avoid a possible race condition where accel_chid has not yet * been assigned a valid channel ID. */ pthread_mutex_lock(&chidMutex); while (accel_chid == -1) { pthread_cond_wait(&chidCond, &chidMutex); } pthread_mutex_unlock(&chidMutex); bps_event_t *stop_request_event = NULL; if (BPS_SUCCESS != bps_event_create(&stop_request_event, local_event_domain, STOP_REQUEST, NULL, NULL)) { fprintf(stderr, "Unable to create event: %s", strerror(errno)); exit(-1); } if (BPS_SUCCESS != bps_channel_push_event(accel_chid, stop_request_event)) { fprintf(stderr, "Unable to push event: %s", strerror(errno)); } pthread_join(accel_thread, NULL); /* * Destroy the dialog, if it exists. */ destroy_top_dialog(); bps_shutdown(); cleanup_screen(); return 0; }
int main(int argc, char *argv[]) { if (!SetCommandLineOptions(argc, argv)) { return -1; } cmdline_opt = GetCommandLineOptions(); if (cmdline_opt.daemon) { std::cout << "raspivoice daemon started." << std::endl; daemon_startup(); } pthread_mutex_init(&rvopt_mutex, NULL); rvopt = cmdline_opt; //Setup keyboard: KeyboardInput keyboardInput; keyboardInput.Verbose = cmdline_opt.verbose; bool use_ncurses = true; if (cmdline_opt.verbose || cmdline_opt.daemon) { use_ncurses = false; } if (cmdline_opt.use_rotary_encoder) { keyboardInput.SetInputType(KeyboardInput::InputType::RotaryEncoder); } else if (cmdline_opt.grab_keyboard != "") { if (!keyboardInput.SetInputType(KeyboardInput::InputType::Keyboard, cmdline_opt.grab_keyboard)) { std::cerr << "Cannot grab keyboard device: " << cmdline_opt.grab_keyboard << "." << std::endl; return -1; } } else if (use_ncurses) { keyboardInput.SetInputType(KeyboardInput::InputType::NCurses); } else if (!cmdline_opt.daemon) { keyboardInput.SetInputType(KeyboardInput::InputType::Terminal); } //Start Program in worker thread: //Warning: Do not read or write rvopt or quit_flag without locking after this. pthread_t thr; AudioData::Init(); if (pthread_create(&thr, NULL, run_worker_thread, NULL)) { std::cerr << "Error setting up thread." << std::endl; return -1; } //Setup UI: if (use_ncurses) { //Show interactive screen: if (setup_screen()) { printw("%s", keyboardInput.GetInteractiveCommandList().c_str()); refresh(); main_loop(keyboardInput); close_screen(); } } else if ((cmdline_opt.verbose) && (!cmdline_opt.daemon)) { std::cout << "Verbose mode on, curses UI disabled." << std::endl; std::cout << keyboardInput.GetInteractiveCommandList(); main_loop(keyboardInput); } else { main_loop(keyboardInput); } if (cmdline_opt.grab_keyboard != "") { keyboardInput.ReleaseKeyboard(); } //Wait for worker thread: pthread_join(thr, nullptr); //Check for exception from worker thread: if (exc_ptr != nullptr) { try { std::rethrow_exception(exc_ptr); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return(-1); } } return(0); }