int get_input(double *val) { BOOLEAN inbounds = TRUE; char input_str[MAX_FIELD] = ""; int return_val; mouse_stat mouse_tel; // mouse telemetry record bell(); set_keyboard_color(BLACK, GREEN); input_monitor(); // loop until they hit ESC or they type in a decent value do { return_val = map_string( 66, 18, WHITE, BLUE, BLACK, LIGHTGRAY, MAX_FIELD, &mouse_tel, input_str, 0 ); // THF patch if (sscanf(input_str, "%lf", val) == 0) { err_message("Incorrect input. Please try again."); inbounds = FALSE; } else { if(*val < 100000.0 && *val > -10000.0) { inbounds = TRUE; } else { inbounds = FALSE; err_message("Input out of bounds."); } } } while((return_val != EscKey) && (inbounds == FALSE)); set_keyboard_color(BLACK, LIGHTGRAY); clear_monitor(); return return_val; }
int ta_distance_map (int argc, char *argv [], config_t *config) { int load_trajectory_ret_code; unsigned int dna_nsegments, nbodies; char *trajectory_file_name, *system; trajectory traj; (void) argv; /* check if user gave the right number of parameters in input */ if (argc != 4) { err_message ("Incorrect number of parameters\n"); print_usage_analyze (DNA_ODE_NAME); return 1; } /* read the values that we will use from the configuration file */ trajectory_file_name = mycfg_read_string (config, "trajectory_file_name"); dna_nsegments = mycfg_read_int (config, "dna_nsegments"); system = mycfg_read_string (config, "system"); nbodies = system_nbodies (system, dna_nsegments); /* open trajectory file and skip to the frame that we want to analyze */ load_trajectory_ret_code = load_trajectory (nbodies, trajectory_file_name, &traj, calculate_distance_map, &dna_nsegments); /* check if success */ if (load_trajectory_ret_code==LOAD_TRAJECTORY_FAIL) { err_message ("Trajectory loading failed. Exiting\n"); return load_trajectory_ret_code; } /* free memory, close files, and exit */ free_trajectory (&traj); return 0; }
/* ---------------------------------------------------------- * FUNCTION : init_pid_file * DESCRIPTION : This function will generate a file * : containing the application's PID. * INPUT : 0 - PID filename * RETURN : None! * ---------------------------------------------------------- */ void init_pid_file (bstring pid_file, bstring user, bstring group) { int pid; FILE *fp; struct group *this_group; struct passwd *this_user; printf("%s\n",bdata(gc.pid_file)); /* Default PID File */ if (gc.pid_file->slen <= 0) gc.pid_file = bfromcstr("/var/run/pads.pid"); /* Create PID File */ if ((fp = fopen(bdata(gc.pid_file), "w")) != NULL) { pid = (int) getpid(); fprintf(fp, "%d\n", pid); fclose(fp); } else { err_message("Unable to create PID file (%s).\n", bdata(gc.pid_file)); } /* Change PID File's Ownership */ if (user == NULL || group == NULL) return; if ((this_group = getgrnam(bdata(group))) == NULL) err_message("'%s' group does not appear to exist.", bdata(group)); if ((this_user = getpwnam(bdata(user))) == NULL) err_message("'%s' user does not appear to exist.", bdata(user)); if ((chown(bdata(pid_file), this_user->pw_uid, this_group->gr_gid)) != 0) err_message("Unable to change PID file's ownership."); }
static int load_image(Image *p, Stream *st) { GIF_info *g_info; int c; g_info = GIFReadSignature(st, &c); if (c != 0) { if (c == NOENOUGHMEM) err_message("gif loader: No enough memory for g_info.\n"); return (c == NOTGIFFILE) ? LOAD_NOT : LOAD_ERROR; } if (g_info->revision != 87 && g_info->revision != 89) { err_message("gif loader: GIF87a or GIF89a only...sorry\n"); return LOAD_ERROR; } if (GIFReadScreenDescriptor(st, g_info) != SUCCESS) { err_message("No enough memory for sd.\n"); return LOAD_ERROR; } if (g_info->sd->aspect_ratio) { double ratio = (double)((g_info->sd->aspect_ratio + 15) / 64); if ((int)ratio != 1) warning("Aspect ratio = %f ... ignored\n", ratio); } do { c = GIFParseNextBlock(st, g_info); if (g_info->npics > 1) { GIFDestroyData(g_info); return LOAD_NOT; } } while (c == PARSE_OK); if (g_info->comment != NULL) p->comment = strdup(g_info->comment); if (c == PARSE_ERROR) err_message("gif loader: Parse error: %s at 0x%lX.\n", g_info->err, stream_tell(st)); gif_convert(p, g_info, g_info->top); /* TODO: Use Screen g_info->sd->width, g_info->sd->height */ GIFDestroyData(g_info); return LOAD_OK; }
func_error_t aitown_compress_autopen (aitown_compress_open_t * original_data) { DBG_ASSERT (original_data->compress_mng != NULL); aitown_compress_open_t data = *original_data; func_error_t ret = FUNC_OK; for (;;) { // parse the config file struct_ini_t sini; ret = aitown_compress_shrink_ini (&data, &sini); if (ret != FUNC_OK) { break; } // get general section and compress_driver key struct_ini_sect_t * sect_general = struct_ini_find_section_0 (&sini, "general"); if (sect_general == NULL) { err_message ("GENERAL section not found in config file"); break; } // get the driver to use struct_ini_value_t * compress_driver_val = struct_ini_find_value_0 (sect_general, "compress_driver"); if ((compress_driver_val == NULL) || (compress_driver_val->value == NULL)) { err_message ("GENERAL/compress_driver key not found in config file"); break; } // the driver must be loaded aitown_compress_driver_t * compress_driver; if (aitown_compress_mng_driver_find ( data.compress_mng, compress_driver_val->value, &compress_driver)) { err_message ("No compress driver named <%s> is loaded", data.driver); ret = FUNC_BAD_INPUT; break; } // call the driver load function with this information data.cfg = &sini; ret = compress_driver->open (&data); break; } original_data->out = data.out; return ret; }
void loop_epoll(server_t *server) { int epollfd = epoll_create1(0); if (epollfd == -1) err_exit("epoll_create1"); add_to_epoll(epollfd, server->listen_fd); struct epoll_event *events = calloc(LOOP_EPOLL_MAXEVENTS, sizeof(struct epoll_event)); while (!server->quit) { int n = epoll_wait(epollfd, events, LOOP_EPOLL_MAXEVENTS, -1); int i; for (i = 0; i < n; i++) { if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { err_message("epoll error, closing %d\n", events[i].data.fd); close(events[i].data.fd); continue; } else if (server->listen_fd == events[i].data.fd) { /* incoming connections. */ struct sockaddr addr; socklen_t in_len = sizeof addr; int newfd = accept(server->listen_fd, &addr, &in_len); printf("Accepted connection on descriptor %d ", newfd); add_to_epoll(epollfd, newfd); } else { /* incoming data */ command_t command = get_next_command(events[i].data.fd); process_command(server, &command); } } } free(events); close(server->listen_fd); }
static int setup(VideoDecoder *vdec, Movie *m, Image *p, int w, int h) { struct videodecoder_divx *vdm = (struct videodecoder_divx *)vdec->opaque; DEC_INIT dec_init; DivXBitmapInfoHeader bih; int inst, quality; if (memory_alloc(image_rendered_image(p), image_bpl(p) * image_height(p)) == NULL) { err_message("No enough memory for image body (%d bytes).\n", image_bpl(p) * image_height(p)); return 0; } memset(&dec_init, 0, sizeof(dec_init)); dec_init.codec_version = vdm->input_format; dec_init.smooth_playback = 0; decore(&vdm->dec_handle, DEC_OPT_INIT, &dec_init, NULL); inst = DEC_ADJ_POSTPROCESSING | DEC_ADJ_SET; quality = 0; // 0-60 decore(vdm->dec_handle, DEC_OPT_ADJUST, &inst, &quality); bih.biCompression = m->out_fourcc; bih.biBitCount = m->out_bitcount; bih.biSize = sizeof(DivXBitmapInfoHeader); bih.biWidth = m->width; bih.biHeight = m->height; decore(vdm->dec_handle, DEC_OPT_SETOUT, &bih, NULL); return 1; }
/* ---------------------------------------------------------- * FUNCTION : copy_argv * DESCRIPTION : This function will flatten argv into a * : single string. This function was taken * : from the tcpdump source code. Hopefully * : someday I will get around to rewriting it. * INPUT : 0 - argv * ---------------------------------------------------------- */ char *copy_argv(register char **argv) { register char **p; register u_int len = 0; char *buf; char *src, *dst; p = argv; if (*p == 0) return 0; while (*p) len += strlen(*p++) + 1; buf = (char *)malloc(len); if (buf == NULL) { err_message("copy_argv: malloc"); } p = argv; dst = buf; while ((src = *p++) != NULL) { while ((*dst++ = *src++) != '\0') ; dst[-1] = ' '; } dst[-1] = '\0'; return buf; }
func_error_t dejavu_level_II_mng_init ( dejavu_level_II_mng_t *mng, aitown_db_mng_t * db_mng, aitown_cfg_sect_t * cfg_sect) { func_error_t ret = FUNC_OK; for (;;) { // initialise // memset (mng, 0, sizeof(dejavu_level_II_mng_t)); // open the database that has color-ID associations // we're receiving the section hosting [dejavu] section but // the databases are hosted one level higher // we're inconsistent, here; we should either have al database // names hardcoded or all extracted from relevant section // i.e. dejavu/database ret = aitown_db_open (db_mng, "dejavu_level1", &mng->db); if (ret != FUNC_OK) { err_message ("DejaVu sensor: can't open database"); return ret; } break; } return ret; }
/* ---------------------------------------------------------- * FUNCTION : init_configuration * DESCRIPTION : This function will read in and process a * : specified configuration file. * INPUT : 0 - Config File * RETURN : None! * ---------------------------------------------------------- */ void init_configuration (bstring filename) { FILE *fp; bstring filedata; struct bstrList *lines; int i; verbose_message("config - Processing '%s'.", bdata(filename)); if ((fp = fopen(bdata(filename), "r")) == NULL) { err_message("Unable to open configuration file - %s", bdata(filename)); } /* Read file into 'filedata' and process it accordingly. */ filedata = bread ((bNread) fread, fp); if ((lines = bsplit(filedata, '\n')) != NULL) { for (i = 0; i < lines->qty; i++) { parse_line(lines->entry[i]); } } /* Clean Up */ bdestroy(filedata); bstrListDestroy(lines); fclose(fp); }
func_error_t aitown_compress_cfgopen (aitown_compress_open_t * original_data) { DBG_ASSERT (original_data->compress_mng != NULL); aitown_compress_open_t data = *original_data; func_error_t ret = FUNC_OK; for (;;) { // the driver must be loaded aitown_compress_driver_t * compress_driver; if (aitown_compress_mng_driver_find ( data.compress_mng, data.driver, &compress_driver)) { err_message ("No compress driver named <%s> is loaded", data.driver); ret = FUNC_BAD_INPUT; break; } // call the driver load function with this information ret = compress_driver->open (&data); break; } original_data->out = data.out; return ret; }
/* rotates a body by a certain angle around one of its axes */ void body_rotate_around_axis (dBodyID b, t_real angle, unsigned int axis_id) { t_vector u, v, t, rotation_axis; t_vector new_u, new_v, new_t; /* get old axes */ body_axis (u, b, 0); body_axis (v, b, 1); body_axis (t, b, 2); if (axis_id==0) dCopyVector3 (rotation_axis, u); else if (axis_id==1) dCopyVector3 (rotation_axis, v); else if (axis_id==2) dCopyVector3 (rotation_axis, t); else { err_message ("Invalid axis ID\n"); exit (EXIT_FAILURE); } /* rotate axes */ vector_rotate_around_axis (new_u, u, angle, rotation_axis); vector_rotate_around_axis (new_v, v, angle, rotation_axis); vector_rotate_around_axis (new_t, t, angle, rotation_axis); /* set the new axes to the body */ body_set_axes (b, new_u, new_v, new_t); }
int InitGUI (int argc, const char* agr[]) { int step = 1; __mg_quiting_stage = _MG_QUITING_STAGE_RUNNING; #ifndef __NOUNIX__ tcgetattr (0, &savedtermio); #endif if (!mg_InitFixStr ()) { err_message (step, "Can not initialize Fixed String heap!\n"); return step; } step++; if (!mg_InitMisc ()) { err_message (step, "Can not initialize miscellous things!"); return step; } step++; /* Init GAL engine. */ switch (mg_InitGAL ()) { case ERR_CONFIG_FILE: err_message (step, "Reading configuration failure!"); return step; case ERR_NO_ENGINE: err_message (step, "No graphics engine defined!"); return step; case ERR_NO_MATCH: err_message (step, "Can not get graphics engine information!"); return step; case ERR_GFX_ENGINE: err_message (step, "Can not initialize graphics engine!"); return step; } step++; atexit (mg_TerminateGAL); /* Init Master Screen DC here */ if (!mg_InitScreenDC (__gal_screen)) { err_message (step, "Can not initialize screen DC!"); return step; } step++; atexit (mg_TerminateScreenDC); g_rcScr.left = 0; g_rcScr.top = 0; g_rcScr.right = GetGDCapability (HDC_SCREEN_SYS, GDCAP_MAXX) + 1; g_rcScr.bottom = GetGDCapability (HDC_SCREEN_SYS, GDCAP_MAXY) + 1; mg_TerminateMgEtc (); return 0; }
static func_error_t aitown_compress_shrink_ini ( aitown_compress_open_t * data, struct_ini_t *sini) { func_error_t ret = FUNC_OK; for (;;) { // there must be a driver name size_t drv_len = strlen (data->driver); if (drv_len == 0) { err_message ("A driver name must be provided for any compress"); ret = FUNC_BAD_INPUT; break; } // the path to config file char computed_name[MAX_PATH]; int tolerant; const char * cfg_path; if (data->cfg_file == NULL) { computed_name[0] = 0; get_user_config_folder (computed_name, MAX_PATH-drv_len-1, "aitown_compress"); size_t cpth = strlen (computed_name); memcpy (&computed_name[cpth], data->driver, drv_len+1); tolerant = 1; cfg_path = computed_name; } else { cfg_path = data->cfg_file; tolerant = 0; } // parse it int sini_err = struct_ini_init_and_parse (sini, cfg_path); if ((0 != sini_err) && (!tolerant)) { err_message ("Failed to parse configuration file (error code: %d)", sini_err); ret = FUNC_BAD_INPUT; break; } break; } return ret; }
/* recurrence relationship for average: * mean(n+1) = mean(n) + (data(n+1)-mean(n))/(n+1). * CAREFUL: here "n" is exactly as in the formula above, that is * the number of data points that are already in the vector. */ int average_recurrence (size_t n, double average_old, double new_data, double *average_new) { if (n>0) { *average_new = average_old + (new_data-average_old)/(n+1); return MYLIB_SUCCESS; } else { err_message ("Called %s function with n = 0\n", __FUNCTION__); return MYLIB_FAIL; } }
static VideoDecoderStatus decode(VideoDecoder *vdec, Movie *m, Image *p, DemuxedPacket *dp, unsigned int len, unsigned int *used_r) { struct videodecoder_divx *vdm = (struct videodecoder_divx *)vdec->opaque; unsigned char *buf = dp->data; int res; if (len == 0) return VD_NEED_MORE_DATA; *used_r = len; vdm->dec_frame.length = len; vdm->dec_frame.bitstream = buf; vdm->dec_frame.bmp = memory_ptr(image_rendered_image(p)); vdm->dec_frame.render_flag = vdm->to_skip > 0 ? 0 : 1; vdm->dec_frame.stride = 0; pthread_mutex_lock(&vdec->update_mutex); if ((res = decore(vdm->dec_handle, DEC_OPT_FRAME, &vdm->dec_frame, NULL)) != DEC_OK) { if (res == DEC_BAD_FORMAT) { err_message("OPT_FRAME returns DEC_BAD_FORMAT\n"); } else { err_message("OPT_FRAME returns %d\n", res); } pthread_mutex_unlock(&vdec->update_mutex); return VD_ERROR; } m->current_frame++; if (vdm->to_skip > 0) { vdm->to_skip--; pthread_mutex_unlock(&vdec->update_mutex); return VD_OK; } vdec->ts_base = dp->ts_base; vdec->pts = m->current_frame * 1000 / rational_to_double(m->framerate); vdec->to_render++; while (m->status == _PLAY && vdec->to_render > 0) pthread_cond_wait(&vdec->update_cond, &vdec->update_mutex); pthread_mutex_unlock(&vdec->update_mutex); return VD_OK; }
//! send an error reply to the sender and log to stdout static index_error send_error (void *server, const char * message) { dbg_message (__func__); // prepare message structure AiTownIndexReply msg = AI_TOWN_INDEX_REPLY__INIT; msg.type = AI_TOWN_INDEX_MESSAGE_TYPE__AITMT_INDEX_ERROR; msg.version = INDEX_CURRENT_PROTOCOL_VERSION; msg.error_message = (char*)message; // and send it err_message(message); return send_reply (&msg, server); }
/* returns the joint second anchoring point */ void joint_anchor2 (t_real *anchor, dJointID j) { dVector3 joint_position; int joint_type; joint_type = dJointGetType (j); if (joint_type == dJointTypeBall) { dJointGetBallAnchor2 (j, joint_position); } else { err_message ("Unrecognized joint type\n"); exit (EXIT_FAILURE); } vector_set (anchor, joint_position [0], joint_position [1], joint_position [2]); }
/* recurrence relationship for average: * var(n+1) = (n-1)/n * var(n) + (data(n+1)-mean(n))^2/(n+1). * CAREFUL: here "n" is exactly as in the formula above, that is * the number of data points that are already in the vector. */ int variance_recurrence ( size_t n, double variance_old, double average_old, double new_data, double *variance_new) { if (n>1) { *variance_new = ((double) (n-1))/((double) (n))*variance_old + (new_data-average_old)*(new_data-average_old)/(n+1); return MYLIB_SUCCESS; } else { err_message ("Called %s function with n <= 1\n", __FUNCTION__); return MYLIB_FAIL; } }
/* ---------------------------------------------------------- * FUNCTION : drop_privs * DESCRIPTION : This function will change the user and * : group of the application. * INPUT : 0 - New User * : 1 - New Group * RETURN : None! * ---------------------------------------------------------- */ void drop_privs (bstring newuser, bstring newgroup) { struct group *this_group; struct passwd *this_user; /* Only change root's privileges. */ if (!(getuid() == 0 || geteuid() == 0 || getgid() == 0 || getegid() == 0)) return; if (newuser == NULL || newgroup == NULL) return; if ((this_group = getgrnam(bdata(newgroup))) == NULL) err_message("'%s' group does not appear to exist.", bdata(newgroup)); if ((this_user = getpwnam(bdata(newuser))) == NULL) err_message("'%s' user does not appear to exist.", bdata(newuser)); /* Set Group */ #if !defined(LINUX) if ((setgid(this_group->gr_gid)) == -1) err_message("Unable to set Group ID!"); if ((setegid(this_group->gr_gid)) == -1) err_message("Unable to set Group ID!"); #else if ((setregid(this_group->gr_gid, this_group->gr_gid)) == -1) err_message("Unable to set Group ID!"); #endif /* Set User */ #if !defined(LINUX) if ((setuid(this_user->pw_uid)) == -1) err_message("Unable to set User ID!"); if ((seteuid(this_user->pw_uid)) == -1) err_message("Unable to set User ID!"); #else if ((setreuid(this_user->pw_uid, this_user->pw_uid)) == -1) err_message("Unable to set User ID!"); #endif }
/* average and standard deviation of a vector */ size_t average (size_t N, double *data, double *av) { double sum; double n = (double) N; /* cast to double */ /* check that we have at least two values for the determination of standard deviation */ if (N==0) { err_message ("Insufficient data to perform average\n"); return MYLIB_FAIL; } /* sum */ calculate_sum (N, data, &sum); /* calculate average and standard deviation */ *av = _AVERAGE (n,sum); return MYLIB_SUCCESS; }
/* average and standard deviation of a vector */ size_t average_variance (size_t N, double *data, double *av, double *var) { double sum, sum2; double n = (double) N; /* cast to double */ /* check that we have at least two values for the determination of standard deviation */ if (N <= 1) { err_message ("Insufficient data to perform average and variance calculation\n"); return MYLIB_FAIL; } /* calculate sum and square sum */ calculate_sum_sum2 (N, data, &sum, &sum2); /* calculate average and standard deviation */ *av = _AVERAGE (n,sum); /* calculate variance */ *var = _VARIANCE (n,*av,sum2); return MYLIB_SUCCESS; }
func_error_t aitown_compress_open (aitown_compress_open_t * original_data) { DBG_ASSERT (original_data->compress_mng != NULL); aitown_compress_open_t data = *original_data; func_error_t ret = FUNC_OK; for (;;) { // parse the config file struct_ini_t sini; ret = aitown_compress_shrink_ini (&data, &sini); if (ret != FUNC_OK) { break; } // the driver must be loaded aitown_compress_driver_t * compress_driver; if (aitown_compress_mng_driver_find ( data.compress_mng, data.driver, &compress_driver)) { err_message ("No compress driver named <%s> is loaded", data.driver); ret = FUNC_BAD_INPUT; break; } // call the driver load function with this information data.cfg = &sini; ret = compress_driver->open (&data); if (ret != FUNC_OK) { break; } // save the driver aitown_compress_t * outcompress = *original_data->out; outcompress->driver = compress_driver; break; } return ret; }
//! send a message from server to client static index_error send_reply (AiTownIndexReply * input_msg, void *server) { dbg_message (__func__); // serialize in a buffer void *buff; size_t sz = AiTownIndexReply__pack (input_msg, &buff); if ( sz == 0 ) { return FUNC_MEMORY_ERROR; } // Create a new message, allocating space for message content zmq_msg_t msg; int rc = zmq_msg_init_data( &msg, buff, sz, zmq_buffer_free, NULL); INDEX_ASSERT (rc == 0); // Send the message to the socket rc = zmq_msg_send (&msg, server, 0); if (rc != (int)sz) { err_message( "Failed to send message to client"); } return FUNC_OK; }
/* ---------------------------------------------------------- * FUNCTION : daemonize * DESCRIPTION : This function will place the application in * : the background. * INPUT : None! * RETURN : None! * ---------------------------------------------------------- */ void daemonize () { pid_t pid; printf("[-] Daemonizing...\n"); pid = fork(); if (pid > 0) { /* Parent */ exit(0); } else if (pid < 0) { /* Error */ err_message("fork"); exit(0); } else { /* Child */ setsid(); close(0); close(1); close(2); } }
func_error_t aitown_db_driver_add ( aitown_db_mng_t * db_mng, aitown_db_driver_t * db_driver ) { func_error_t ret = FUNC_OK; for (;;) { // make sure it implements required callbacks if ( (db_driver->open == NULL) || (db_driver->close == NULL) || (db_driver->read == NULL) || (db_driver->write == NULL) || (db_driver->free_chunk == NULL) || (db_driver->name == NULL) ) { err_message ("Driver %s does not meet minimum requirements", db_driver->name); break; } // make sure parameters are ok if ((db_mng == NULL) || (db_driver == NULL)) { ret = FUNC_BAD_INPUT; break; } // add if not already there aitown_db_driver_t * found; if (!sglib_aitown_db_driver_t_add_if_not_member ( &db_mng->first_driver, db_driver, &found)) { ret = FUNC_BAD_INPUT; break; } break; } return ret; }
int InitGUI (int argc, const char* agr[]) { int step = 1; __mg_quiting_stage = _MG_QUITING_STAGE_RUNNING; #ifdef _MGRM_PROCESSES const char* name; if ((name = strrchr (agr [0], '/')) == NULL) name = agr [0]; else name ++; if (!strcmp (name, "mginit")) mgIsServer = TRUE; #endif #ifdef HAVE_SETLOCALE setlocale (LC_ALL, "C"); #endif /* Save original termio */ #ifdef _MGRM_PROCESSES if (mgIsServer) #endif //#ifndef WIN32 #ifndef __NOUNIX__ tcgetattr (0, &savedtermio); #endif /*Initialize default window process*/ __mg_def_proc[0] = PreDefMainWinProc; __mg_def_proc[1] = PreDefDialogProc; __mg_def_proc[2] = PreDefControlProc; if (!mg_InitFixStr ()) { err_message (step, "Can not initialize Fixed String heap!\n"); return step; } step++; if (!mg_InitMisc ()) { err_message (step, "Can not initialize miscellous things!"); return step; } step++; #ifdef _MGRM_PROCESSES if (mgIsServer && !kernel_IsOnlyMe ()) { err_message (step, "There is already an instance of 'mginit'!"); return step; } step++; #endif #ifdef _MGRM_PROCESSES if (!mgIsServer) { if (!client_ClientStartup ()) { err_message (step, "Can not start client (Please run mginit first)!"); return step; } step++; if ((mgSharedRes = kernel_AttachSharedResource ()) == NULL) { err_message (step, "Can not attach shared resource (Please run mginit first)!"); return step; } atexit (kernel_UnattachSharedResource); } #endif /* Init GAL engine. */ switch (mg_InitGAL ()) { case ERR_CONFIG_FILE: err_message (step, "Reading configuration failure!"); return step; case ERR_NO_ENGINE: err_message (step, "No graphics engine defined!"); return step; case ERR_NO_MATCH: err_message (step, "Can not get graphics engine information!"); return step; case ERR_GFX_ENGINE: err_message (step, "Can not initialize graphics engine!"); return step; } step++; atexit (mg_TerminateGAL); /* install signal handlers */ #ifdef _MGRM_PROCESSES if (mgIsServer) #endif InstallSEGVHandler (); /** initialize icon bitmap resource.*/ if (mg_InitSystemRes () == FALSE) { fprintf (stderr, "KERNEL>IniGUI: init system res error!\n"); return step; } step++; /* DK[11/29/10]: For fix bug 4440, avoid double free. */ /* atexit (mg_TerminateSystemRes); */ if (!mg_InitGDI ()) { err_message (step, "Initialization of GDI resource failure!\n"); return step; } step++; atexit (mg_TerminateGDI); /* Init Master Screen DC here */ if (!mg_InitScreenDC (__gal_screen)) { err_message (step, "Can not initialize screen DC!"); return step; } step++; atexit (mg_TerminateScreenDC); g_rcScr.left = 0; g_rcScr.top = 0; g_rcScr.right = GetGDCapability (HDC_SCREEN_SYS, GDCAP_MAXX) + 1; g_rcScr.bottom = GetGDCapability (HDC_SCREEN_SYS, GDCAP_MAXY) + 1; #ifdef _MGRM_PROCESSES if (mgIsServer) { /* Load shared resource and create shared memory. */ if ((mgSharedRes = kernel_LoadSharedResource ()) == NULL) { err_message (step, "Can not load shared resource!"); return step; } atexit (kernel_UnloadSharedResource); SHAREDRES_TERMIOS = savedtermio; } step++; #endif if (!mg_InitLFManager ()) { err_message (step, "Can not initialize LFManager!\n"); return step; } step++; atexit (mg_TerminateLFManager); #ifdef _MGRM_PROCESSES if (mgIsServer) #endif { license_create(); splash_draw_framework(); splash_delay(); } /* Initialize resource */ if (!InitResource ()) { err_message (step, "Can not initialize resource!"); return step; } step++; #ifdef _MGRM_STANDALONE /* Init IAL engine.. */ if (!mg_InitLWEvent ()) { err_message (step, "Can not initialize low level event!"); return step; } step++; atexit (mg_TerminateLWEvent); SetDskIdleHandler (salone_IdleHandler4StandAlone); if (!salone_StandAloneStartup ()) { fprintf (stderr, "KERNEL>InitGUI: Can not start MiniGUI-StandAlone version.\n"); return step; } #else if (mgIsServer) { /* Init IAL engine.. */ if (!mg_InitLWEvent ()) { err_message (step, "Can not initialize low level event!"); return step; } step++; atexit (mg_TerminateLWEvent); SetDskIdleHandler (server_IdleHandler4Server); } else { SetDskIdleHandler (client_IdleHandler4Client); } #endif SetKeyboardLayout ("default"); mg_TerminateMgEtc (); return 0; }
DEFINE_LOADER_PLUGIN_LOAD(p, st, vw #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif , c #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif , priv #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif ) { jas_image_t *ji; jas_stream_t *js; unsigned char *d; char *buf = NULL; int k, cmp[3]; unsigned int i, j; int tlx, tly; int vs, hs; //debug_message("JasPer: load() called\n"); #ifdef IDENTIFY_BEFORE_LOAD { LoaderStatus status; if ((status = identify(p, st, vw, c, priv)) != LOAD_OK) return status; stream_rewind(st); } #endif /* Read whole stream into buffer... */ { char *tmp; int size = 0, len; int bufsize = 65536; for (;;) { if ((tmp = realloc(buf, bufsize)) == NULL) { free(buf); return LOAD_ERROR; } buf = tmp; len = stream_read(st, (unsigned char *)(buf + size), bufsize - size); size += len; if (len < bufsize - size) break; bufsize += 65536; } if ((js = jas_stream_memopen(buf, size)) == NULL) { free(buf); return LOAD_ERROR; } } /* loading... */ if ((ji = jas_image_decode(js, -1, 0)) == NULL) { err_message_fnc("jas_image_decode() failed.\n"); goto error_clear; } /* colorspace conversion */ { jas_cmprof_t *jc; jas_image_t *new_ji; if ((jc = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == NULL) goto error_destroy_free; if ((new_ji = jas_image_chclrspc(ji, jc, JAS_CMXFORM_INTENT_PER)) == NULL) goto error_destroy_free; jas_image_destroy(ji); ji = new_ji; } jas_stream_close(js); free(buf); debug_message("JasPer: jas_image_decode() OK: (%ld,%ld)\n", jas_image_cmptwidth(ji, 0), jas_image_cmptheight(ji, 0)); /* convert to enfle format */ p->bits_per_pixel = 24; p->type = _RGB24; p->depth = 24; cmp[0] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); cmp[1] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); cmp[2] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); /* dimension */ image_width(p) = jas_image_cmptwidth(ji, cmp[0]); image_height(p) = jas_image_cmptheight(ji, cmp[0]); image_left(p) = 0; image_top(p) = 0; image_bpl(p) = image_width(p) * 3; tlx = jas_image_cmpttlx(ji, cmp[0]); tly = jas_image_cmpttly(ji, cmp[0]); vs = jas_image_cmptvstep(ji, cmp[0]); hs = jas_image_cmpthstep(ji, cmp[0]); debug_message("JasPer: tlx %d tly %d vs %d hs %d ncomponents %d\n", tlx, tly, vs, hs, jas_image_numcmpts(ji)); /* memory allocation */ if ((d = memory_alloc(image_image(p), image_bpl(p) * image_height(p))) == NULL) { err_message("No enough memory (%d bytes)\n", image_bpl(p) * image_height(p)); goto error_destroy_free; } for (i = 0; i < image_height(p); i++) { for (j = 0; j < image_width(p); j++) { for (k = 0; k < 3; k++) *d++ = jas_image_readcmptsample(ji, cmp[k], j, i); } } jas_image_destroy(ji); return LOAD_OK; error_destroy_free: jas_image_destroy(ji); error_clear: return LOAD_ERROR; }
int InitGUI (void) { int step = 1; // Save original termio #ifndef _STAND_ALONE if (mgIsServer) #endif tcgetattr (0, &savedtermio); if (!InitMisc ()) { err_message (step, "Can not initialize miscellous things!"); return step; } step++; #ifndef _STAND_ALONE if (mgIsServer && !IsOnlyMe ()) { err_message (step, "There is already an instance of 'mginit'!"); return step; } step++; #endif // Init GAL engine. switch (InitGAL ()) { case ERR_CONFIG_FILE: err_message (step, "Reading configuration failure!"); return step; case ERR_NO_ENGINE: err_message (step, "No graphics engine defined!"); return step; case ERR_NO_MATCH: err_message (step, "Can not get graphics engine information!"); return step; case ERR_GFX_ENGINE: err_message (step, "Can not initialize graphics engine!"); return step; } step++; atexit (TerminateGAL); /* install signal handlers */ #ifndef _STAND_ALONE if (mgIsServer) #endif InstallSEGVHandler (); if (!InitGDI ()) { err_message (step, "MiniGUI: Initialization of GDI resource failure!\n"); return step; } step++; atexit (TerminateGDI); /* Init Screen DC here */ if (!InitScreenDC ()) { err_message (step, "Can not initialize screen DC!"); return step; } step++; atexit (TerminateScreenDC); g_rcScr.left = 0; g_rcScr.top = 0; g_rcScr.right = GetGDCapability (HDC_SCREEN, GDCAP_MAXX) + 1; g_rcScr.bottom = GetGDCapability (HDC_SCREEN, GDCAP_MAXY) + 1; if (!InitWindowElementColors ()) { err_message (step, "Can not initialize colors of window element!"); return step; } step++; #ifndef _STAND_ALONE if (mgIsServer) { // Load shared resource and create shared memory. if ((mgSharedRes = LoadSharedResource ()) == NULL) { err_message (step, "Can not load shared resource!"); return step; } atexit (UnloadSharedResource); SHAREDRES_TERMIOS = savedtermio; } else { if ((mgSharedRes = AttachSharedResource ()) == NULL) { err_message (step, "Can not attach shared resource!"); return step; } atexit (UnattachSharedResource); } step++; #endif // Initialize resource if (!InitResource ()) { err_message (step, "Can not initialize resource!"); return step; } step++; #ifdef _STAND_ALONE // Init IAL engine.. if (!InitLWEvent ()) { err_message (step, "Can not initialize low level event!"); return step; } step++; atexit (TerminateLWEvent); __mg_dsk_msgs.OnIdle = IdleHandler4StandAlone; if (!StandAloneStartup ()) { fprintf (stderr, "Can not start MiniGUI-Lite StandAlone version.\n"); return step; } #else if (mgIsServer) { // Init IAL engine.. if (!InitLWEvent ()) { err_message (step, "Can not initialize low level event!"); return step; } step++; atexit (TerminateLWEvent); __mg_dsk_msgs.OnIdle = IdleHandler4Server; if (!ServerStartup ()) { fprintf (stderr, "Can not start the server of MiniGUI-Lite: mginit.\n"); return step; } } else { if (!ClientStartup ()) { err_message (step, "Can not start client!"); return step; } step++; __mg_dsk_msgs.OnIdle = IdleHandler4Client; } #endif SetKeyboardLayout ("default"); TerminateMgEtc (); return 0; }
void record_event(EventCode code, Sprite *by, Background *floor, Sprite *subject, boolean type_of_subject_fixed, int key, AddToWorkingSet add_to_working_set, boolean notebook_page_really_selected, int label_index #if TT_POST3187 ,Sprite *original_subject #endif ) { #if TT_DEBUG_ON if (tt_debug_mode == 5050) { tt_error_file() << timeGetTime() << " "; Event *event = new Event(code,NULL); event->debug(NULL); delete event; }; #endif // until I generate instructions programmer actions aren't recorded if (tt_log_version_number >= 22) { if (by == NULL || tt_recording_off || (by->kind_of() != ROBOT && by->kind_of() != ROBOT_IN_TRAINING) || tt_shutting_down) return; } else { if (by == NULL || tt_recording_off || by->kind_of() == PROGRAMMER || tt_shutting_down) return; }; // third condition prior to 050400 was by->kind_of() == PROGRAMMER but by might be a bird for example boolean body_cubby; if (by->kind_of() == ROBOT) { body_cubby = (subject == ((Robot *) by)->pointer_to_working_cubby()); } else if (floor != NULL || tt_log_version_number < 22) { // condition added 050400 body_cubby = (subject == floor->pointer_to_body_cubby()); } else { body_cubby = FALSE; }; // doesn't count that its main cubby if put somewhere // if (body_cubby) { // body_cubby = (subject->pointer_to_leader() == NULL || // subject->pointer_to_leader()->kind_of() == ROBOT_IN_TRAINING); // }; const boolean notebook = (tt_toolbox != NULL && subject == tt_toolbox_notebook); // following screws up if main cubby put into something and then taken out // also bad to have just 1 optimization like this // restored for notebook since it is shared and shouldn't be moved by robots if (code == RELEASE_ITEM && notebook) { // ((body_cubby && subject->pointer_to_leader() == NULL) || notebook)) { // could be more clever and if anything is released right // after being picked up it is ignored // picked up and released main cubby or notebook // (or vacuumed up and restored) // robot shouldn't be doing this so ok to assume floor if (tt_events != NULL) { Event *last_event = tt_events->last()->first(); if (last_event->event_code() == GRASP_ITEM || last_event->event_code() == VACUUM_APPLY) { // test new on 120305 since can be keyboard event, for example floor->remove_last_n_events(1); // must have been a grasp_item (or apply_vacuum) return; }; }; // else should be OK since there are no events to remove, right? }; if (code == RELEASE_ITEM_ON && by->kind_of() == ROBOT_IN_TRAINING) { if (subject->kind_of() == NEST && subject->infinite_stack()) { // returning a nest with egg back to stack but already // generated a hatch_bird message floor->remove_last_n_events(1); ((Robot *) by)->remove_last_working_set_item(); // taken care of by :now_part_of_somthing() // } else { // Happens in event.cpp so needs to happen here as well // ((Robot *) by)->remove_tool_from_working_set(subject); }; }; Path *path = NULL; Event *new_item_event = NULL; if (body_cubby || notebook) { add_to_working_set = DONT_ADD_TO_WORKING_SET; }; if (code == NEW_ITEM || code == HATCH_BIRD || code == RELEASE_ITEM || code == VACUUM_APPLY_RESTORE) { if (subject != NULL && !body_cubby && !(tt_toolbox != NULL && toolbox_tool(subject))) { // either defining a body so add to this // or by is a robot so add to its // or by is programmer so ignore switch (by->kind_of()) { case ROBOT_IN_TRAINING: // if (!by->still_running()) { if (add_to_working_set != DONT_ADD_TO_WORKING_SET) { int index = ((Robot *) by)->add_to_working_set(subject,(add_to_working_set == ADD_TO_WORKING_SET_IF_NEW)); if (type_of_subject_fixed) { path = new Path(index,new Path(subject->fine_kind_of())); } else if (code == VACUUM_APPLY_RESTORE) { path = new Path(index,new Path(NONE_GIVEN)); subject = NULL; }; // } else if (code == HATCH_BIRD) { // path = new Path(index,new Path(BIRD)); // } else { // path = new Path(index,new Path(NONE_GIVEN)); }; break; // }; // otherwise fall thru to the following case ROBOT: if (add_to_working_set != DONT_ADD_TO_WORKING_SET) { ((Robot *) by)->add_to_working_set(subject,(add_to_working_set == ADD_TO_WORKING_SET_IF_NEW)); }; break; }; // floor->add_to_some_working_set(subject,by); if (code != GRASP_ITEM && code != GRASP_NEST && code != VACUUM_APPLY_RESTORE && notebook_page_really_selected) { subject->set_available_for_indexing(TRUE); }; }; // following commented out so path is recorded for generating Java properly // if (code == VACUUM_APPLY_RESTORE) subject = NULL; if (path != NULL) { new_item_event = new Event(NEW_ITEM,path,0); if (code != VACUUM_APPLY_RESTORE) { if (tt_events == NULL) { tt_events = new Events(new_item_event,tt_events); } else { tt_events->insert_at_end(new_item_event); }; new_item_event = NULL; }; // else add it after this event }; // following just are used to update working set // can combine them to one?? except for descriptions? if (code == NEW_ITEM || code == HATCH_BIRD) return; }; if (by->kind_of() != ROBOT_IN_TRAINING) { if (code == NEW_MAIN_CUBBY) { floor->set_body_cubby((Cubby *) subject, by); }; return; // already knows the path }; if (subject != NULL && code == GRASP_ITEM) { if (subject->kind_of() == NEST) { code = GRASP_NEST; // the whole thing not the top of its stack } else if (tt_toolbox != NULL) { // used to do switch (subject->kind_of()) but copies of tools break if (subject == tt_toolbox_copier) { code = GRASP_COPIER; } else if (subject == tt_toolbox_vacuum) { code = GRASP_VACUUM; } else if (subject == tt_toolbox_expander) { code = GRASP_EXPANDER; } else if (subject == tt_toolbox) { return; // no semantic meaning }; } else { // e.g. puzzle game switch (subject->kind_of()) { case COPIER: code = GRASP_COPIER; break; case VACUUM: code = GRASP_VACUUM; break; case EXPANDER: code = GRASP_EXPANDER; break; }; }; }; if (subject != NULL && subject->kind_of() == NEST) { // don't wait for subject to receieve something to apply tool switch (code) { case COPIER_APPLY: code = COPIER_APPLY_NEST; break; case VACUUM_APPLY: code = VACUUM_APPLY_NEST; break; case APPLY_GRASPED_ITEM: code = APPLY_GRASPED_NEST; break; }; }; if (subject != NULL && code == RELEASE_ITEM) { subject->set_available_for_indexing(TRUE); // switch (subject->kind_of()) { if (tt_toolbox != NULL) { if (subject == tt_toolbox_copier) { code = RELEASE_COPIER; } else if (subject == tt_toolbox_vacuum) { code = RELEASE_VACUUM; } else if (subject == tt_toolbox_expander) { code = RELEASE_EXPANDER; } else if (subject == tt_toolbox) { // was subject == tt_toolbox_expander || return; }; } else { // puzzle game switch (subject->kind_of()) { case COPIER: code = RELEASE_COPIER; break; case VACUUM: code = RELEASE_VACUUM; break; case EXPANDER: code = RELEASE_EXPANDER; break; }; }; }; // safe cast? path = ((Floor *) floor)->compute_path(subject,code,(Robot *) by,notebook_page_really_selected #if TT_POST3187 ,original_subject #endif ); #if TT_CAREFUL if (path == NULL && subject != tt_toolbox) { // ignore actions on Toolbox... #if TT_DEBUG_ON #if TT_NEW_IO output_string_stream err_message; #else string buffer = new char[10000]; output_string_stream err_message(buffer,10000); #endif err_message << "Warning: Robot is confused and couldn't find "; subject->describe(err_message,INDEFINITE_ARTICLE); err_message << "."; err_message.put('\0'); say_error(err_message.STR,TRUE); #if !TT_NEW_IO delete [] buffer; #endif log(event_string(code)); #endif return; // working_set->insert_at_end_if_not_member(subject); // path = compute_path(subject); }; #endif // if (code == RELEASE_ITEM_ON && by->kind_of() == ROBOT_IN_TRAINING && // subject->kind_of() != PROGRAM_PAD && subject->is_container()) { // notebooks use this as well as cubbies //// && subject->pointer_to_leader() != NULL) { // // is now part of something and should be accessed via that container // ((Robot *) by)->remove_tool_from_working_set(subject); // }; //on 5/27 re-wrote the above to match the similar situation in event.cpp // handled by now_released_on // if (code == RELEASE_ITEM_ON && by->kind_of() == ROBOT_IN_TRAINING && // // except when dropping a cubby on a number since both are around afterwards // !(item_underneath != NULL && item_underneath->kind_of() == INTEGER && // subject->kind_of() == CUBBY)) { // ((Robot *) by)->remove_tool_from_working_set(subject); // }; if (code == LABEL_CHARACTER) { path->add_to_end(new Path(label_index)); }; if (code == NEW_MAIN_CUBBY) { // do this after computing the path floor->set_body_cubby((Cubby *) subject, by); }; if ((code == GRASP_ITEM || code == GRASP_NEST) && !notebook_page_really_selected) { subject->set_available_for_indexing(FALSE); // does this ever get restored?? }; Event *event = new Event(code,path,key); if (tt_events == NULL) { tt_events = new Events(event,tt_events); } else { tt_events->insert_at_end(event); }; if (new_item_event != NULL) { tt_events->insert_at_end(new_item_event); }; if (by->kind_of() == ROBOT_IN_TRAINING && code != SELECT_STACK_ITEM) { if (subject != ((Robot *) by)->pointer_to_initial_tool()) { ((Robot *) by)->decrement_training_counter(); }; }; };