示例#1
0
文件: lock.c 项目: ArakniD/libDRM
static void server()
{
	int drmfd, tempfd, ret;
	unsigned int client_time, unlock_time;

	drmfd = drm_open_any_master();

	test_lock_unlock(drmfd);
	test_unlock_unlocked(drmfd);
	test_unlock_unowned(drmfd);
	test_open_close_locked(drmfd);

	/* Perform the authentication sequence with the client. */
	server_auth(drmfd);

	/* Now, test that the client attempting to lock while the server
	 * holds the lock works correctly.
	 */
	ret = drmGetLock(drmfd, lock1, 0);
	assert(ret == 0);
	send_event(1, SERVER_LOCKED);
	/* Wait a while for the client to do its thing */
	sleep(1);
	ret = drmUnlock(drmfd, lock1);
	assert(ret == 0);
	unlock_time = get_millis();

	wait_event(1, CLIENT_LOCKED);
	ret = read(commfd[1], &client_time, sizeof(client_time));
	if (ret == -1)
		err(1, "Failure to read client magic");

	if (client_time < unlock_time)
		errx(1, "Client took lock before server released it");

	close(drmfd);
}
示例#2
0
int update_player_states(play_para_t *para, int force)
{
    callback_t *cb = &para->update_state;
    update_state_fun_t fn;
    para->state.last_sta = para->state.status;
    para->state.status = get_player_state(para);

    if (check_time_interrupt(&cb->callback_old_time, cb->update_interval) || force) {
        player_info_t state;
        MEMCPY(&state, &para->state, sizeof(state));
        //if(force == 1)
        log_print("**[update_state]pid:%d status=%s(tttlast:%s) err=0x%x curtime=%d (ms:%d) fulltime=%d lsttime=%d\n",
                  para->player_id,
                  player_status2str(state.status),
                  player_status2str(state.last_sta),
                  (-state.error_no),
                  state.current_time,
                  state.current_ms,
                  state.full_time,
                  state.last_time);		
        log_print("**[update_state]abuflevel=%.08f vbublevel=%.08f abufrp=%x vbufrp=%x read_end=%d\n",
                  state.audio_bufferlevel,
                  state.video_bufferlevel,
                  para->abuffer.buffer_rp,
                  para->vbuffer.buffer_rp,
                  para->playctrl_info.read_end_flag);
        fn = cb->update_statue_callback;

        if (fn) {
            fn(para->player_id, &state);
        }
        send_event(para, PLAYER_EVENTS_PLAYER_INFO, &state, 0);
        para->state.error_no = 0;
        player_hwbuflevel_update(para);
    }
	return 0;
}
示例#3
0
/**
 * The /bs assign command.
 * @param u The user who issued the command
 * @param MOD_CONT to continue processing other modules, MOD_STOP to stop processing.
 **/
int do_assign(User * u)
{
    char *chan = strtok(NULL, " ");
    char *nick = strtok(NULL, " ");
    BotInfo *bi;
    ChannelInfo *ci;

    if (readonly)
        notice_lang(s_BotServ, u, BOT_ASSIGN_READONLY);
    else if (!chan || !nick)
        syntax_error(s_BotServ, u, "ASSIGN", BOT_ASSIGN_SYNTAX);
    else if (!(bi = findbot(nick)))
        notice_lang(s_BotServ, u, BOT_DOES_NOT_EXIST, nick);
    else if (bi->flags & BI_PRIVATE && !is_oper(u))
        notice_lang(s_BotServ, u, PERMISSION_DENIED);
    else if (!(ci = cs_findchan(chan)))
        notice_lang(s_BotServ, u, CHAN_X_NOT_REGISTERED, chan);
    else if (ci->flags & CI_VERBOTEN)
        notice_lang(s_BotServ, u, CHAN_X_FORBIDDEN, chan);
    else if ((ci->bi) && (stricmp(ci->bi->nick, nick) == 0))
        notice_lang(s_BotServ, u, BOT_ASSIGN_ALREADY, ci->bi->nick, chan);
    else if ((ci->botflags & BS_NOBOT)
             || (!check_access(u, ci, CA_ASSIGN) && !is_services_admin(u)))
        notice_lang(s_BotServ, u, PERMISSION_DENIED);
    else {
        if (ci->bi)
            unassign(u, ci);
        ci->bi = bi;
        bi->chancount++;
        if (ci->c && ci->c->usercount >= BSMinUsers) {
            bot_join(ci);
        }
        notice_lang(s_BotServ, u, BOT_ASSIGN_ASSIGNED, bi->nick, ci->name);
        send_event(EVENT_BOT_ASSIGN, 2, ci->name, bi->nick);
    }
    return MOD_CONT;
}
示例#4
0
int
ipc_event_send(int pid, int event, unsigned int timeout) {
    struct proc_struct *proc;
    if ((proc = find_proc(pid)) == NULL || proc->state == PROC_ZOMBIE) {
        return -E_INVAL;
    }
    if (proc == current || proc == idleproc || proc == initproc || proc == kswapd) {
        return -E_INVAL;
    }
    if (proc->wait_state == WT_EVENT_RECV) {
        wakeup_proc(proc);
    }
    current->event_box.event = event;

    unsigned long saved_ticks;
    timer_t __timer, *timer = ipc_timer_init(timeout, &saved_ticks, &__timer);

    uint32_t flags;
    if ((flags = send_event(proc, timer)) == 0) {
        return 0;
    }
    assert(flags == WT_INTERRUPTED);
    return ipc_check_timeout(timeout, saved_ticks);
}
示例#5
0
文件: object.c 项目: johnh530/electro
void send_set_vert(int i, int j, float v[3], float n[3], float u[2])
{
    struct object_vert *p = get_object_vert(i, j);

    p->v[0] = v[0];
    p->v[1] = v[1];
    p->v[2] = v[2];

    p->n[0] = n[0];
    p->n[1] = n[1];
    p->n[2] = n[2];

    p->u[0] = u[0];
    p->u[1] = u[1];

    send_event(EVENT_SET_VERT);
    send_index(i);
    send_index(j);
    send_array(p->v, 3, sizeof (float));
    send_array(p->n, 3, sizeof (float));
    send_array(p->u, 2, sizeof (float));

    fini_object(i);
}
示例#6
0
文件: camera.c 项目: johnh530/electro
int send_create_camera(int t)
{
    int i;

    if ((i = new_camera()) >= 0)
    {
        struct camera *c = get_camera(i);

        c->count = 1;
        c->type  = t;
        c->n     = (t == CAMERA_ORTHO) ? -1000.0f :    0.1f;
        c->f     = (t == CAMERA_ORTHO) ?  1000.0f : 1000.0f;

        c->frame = 0;
        c->depth = 0;
        c->image = 0;

        c->view_basis[0][0] = 1.0f;
        c->view_basis[0][1] = 0.0f;
        c->view_basis[0][2] = 0.0f;
        c->view_basis[1][0] = 0.0f;
        c->view_basis[1][1] = 1.0f;
        c->view_basis[1][2] = 0.0f;
        c->view_basis[2][0] = 0.0f;
        c->view_basis[2][1] = 0.0f;
        c->view_basis[2][2] = 1.0f;

        send_event(EVENT_CREATE_CAMERA);
        send_index(t);
        send_float(c->n);
        send_float(c->f);

        return send_create_entity(TYPE_CAMERA, i);
    }
    return -1;
}
示例#7
0
/**
 * The /ns identify command.
 * @param u The user who issued the command
 * @param MOD_CONT to continue processing other modules, MOD_STOP to stop processing.
 **/
int do_identify(User * u)
{
    char *pass = strtok(NULL, " ");
    NickAlias *na;
    NickRequest *nr;
    int res;
    char tsbuf[16];
    char modes[512];
    int len;

    if (!pass) {
        syntax_error(s_NickServ, u, "IDENTIFY", NICK_IDENTIFY_SYNTAX);
    } else if (!(na = u->na)) {
        if ((nr = findrequestnick(u->nick))) {
            notice_lang(s_NickServ, u, NICK_IS_PREREG);
        } else {
            notice_lang(s_NickServ, u, NICK_NOT_REGISTERED);
        }
    } else if (na->status & NS_VERBOTEN) {
        notice_lang(s_NickServ, u, NICK_X_FORBIDDEN, na->nick);
    } else if (na->nc->flags & NI_SUSPENDED) {
        notice_lang(s_NickServ, u, NICK_X_SUSPENDED, na->nick);
    } else if (nick_identified(u)) {
        notice_lang(s_NickServ, u, NICK_ALREADY_IDENTIFIED);
    } else if (!(res = enc_check_password(pass, na->nc->pass))) {
        alog("%s: Failed IDENTIFY for %s!%s@%s", s_NickServ, u->nick,
             u->username, u->host);
        notice_lang(s_NickServ, u, PASSWORD_INCORRECT);
        bad_password(u);
    } else if (res == -1) {
        notice_lang(s_NickServ, u, NICK_IDENTIFY_FAILED);
    } else {
        if (!(na->status & NS_IDENTIFIED) && !(na->status & NS_RECOGNIZED)) {
            if (na->last_usermask)
                free(na->last_usermask);
            na->last_usermask =
                scalloc(strlen(common_get_vident(u)) +
                        strlen(common_get_vhost(u)) + 2, 1);
            sprintf(na->last_usermask, "%s@%s", common_get_vident(u),
                    common_get_vhost(u));
            if (na->last_realname)
                free(na->last_realname);
            na->last_realname = sstrdup(u->realname);
        }

        na->status |= NS_IDENTIFIED;
        na->last_seen = time(NULL);
        snprintf(tsbuf, sizeof(tsbuf), "%lu",
                 (unsigned long int) u->timestamp);

        if (ircd->modeonreg) {
            len = strlen(ircd->modeonreg);
	    strncpy(modes,ircd->modeonreg,512);
	    if(ircd->rootmodeonid && is_services_root(u)) { 
                strncat(modes,ircd->rootmodeonid,512-len);
	    } else if(ircd->adminmodeonid && is_services_admin(u)) {
                strncat(modes,ircd->adminmodeonid,512-len);
	    } else if(ircd->opermodeonid && is_services_oper(u)) {
                strncat(modes,ircd->opermodeonid,512-len);
	    }
            if (ircd->tsonmode) {
                common_svsmode(u, modes, tsbuf);
            } else {
                common_svsmode(u, modes, "");
            }
        }
        send_event(EVENT_NICK_IDENTIFY, 1, u->nick);
        alog("%s: %s!%s@%s identified for nick %s", s_NickServ, u->nick,
             u->username, u->host, u->nick);
        notice_lang(s_NickServ, u, NICK_IDENTIFY_SUCCEEDED);
        if (ircd->vhost) {
            do_on_id(u);
        }
        if (NSModeOnID) {
            do_setmodes(u);
        }

        if (NSForceEmail && u->na && !u->na->nc->email) {
            notice_lang(s_NickServ, u, NICK_IDENTIFY_EMAIL_REQUIRED);
            notice_help(s_NickServ, u, NICK_IDENTIFY_EMAIL_HOWTO);
        }

        if (!(na->status & NS_RECOGNIZED))
            check_memos(u);

        /* Enable nick tracking if enabled */
        if (NSNickTracking)
            nsStartNickTracking(u);

        /* Clear any timers */
        if (na->nc->flags & NI_KILLPROTECT) {
            del_ns_timeout(na, TO_COLLIDE);
        }

    }
    return MOD_CONT;
}
示例#8
0
void delete_user(User * user)
{
    struct u_chanlist *c, *c2;
    struct u_chaninfolist *ci, *ci2;
    char *realname;

    if (LogUsers) {
        realname = normalizeBuffer(user->realname);
        if (ircd->vhost) {
            alog("LOGUSERS: %s (%s@%s => %s) (%s) left the network (%s).",
                 user->nick, user->username, user->host,
                 (user->vhost ? user->vhost : "(none)"),
                 realname, user->server->name);
        } else {
            alog("LOGUSERS: %s (%s@%s) (%s) left the network (%s).",
                 user->nick, user->username, user->host,
                 realname, user->server->name);
        }
        free(realname);
    }
    send_event(EVENT_USER_LOGOFF, 1, user->nick);

    if (debug >= 2)
        alog("debug: delete_user() called");
    usercnt--;
    if (is_oper(user))
        opcnt--;
    if (debug >= 2)
        alog("debug: delete_user(): free user data");
    free(user->username);
    free(user->host);
    if (user->chost)
        free(user->chost);
    if (user->vhost)
        free(user->vhost);
    if (user->vident)
        free(user->vident);
    if (user->uid) {
        free(user->uid);
    }
    Anope_Free(user->realname);
    Anope_Free(user->hostip);
    if (debug >= 2) {
        alog("debug: delete_user(): remove from channels");
    }
    c = user->chans;
    while (c) {
        c2 = c->next;
        chan_deluser(user, c->chan);
        free(c);
        c = c2;
    }
    /* This called only here now */
    cancel_user(user);
    if (user->na)
        user->na->u = NULL;
    if (debug >= 2)
        alog("debug: delete_user(): free founder data");
    ci = user->founder_chans;
    while (ci) {
        ci2 = ci->next;
        free(ci);
        ci = ci2;
    }

    if (user->nickTrack)
        free(user->nickTrack);

    moduleCleanStruct(&user->moduleData);

    if (debug >= 2)
        alog("debug: delete_user(): delete from list");
    if (user->prev)
        user->prev->next = user->next;
    else
        userlist[HASH(user->nick)] = user->next;
    if (user->next)
        user->next->prev = user->prev;
    if (debug >= 2)
        alog("debug: delete_user(): free user structure");
    free(user);
    if (debug >= 2)
        alog("debug: delete_user() done");
}
示例#9
0
int do_addnick(User * u)
{
    NickAlias *na, *target;
    NickCore *nc;
    char *nick = strtok(NULL, " ");
    char *pass = strtok(NULL, " ");
    int i;
    char tsbuf[16];
    char modes[512];
    int len;

    if (NSEmailReg && (findrequestnick(u->nick))) {
        notice_lang(s_NickServ, u, NS_REQUESTED);
        return MOD_CONT;
    }

    if (readonly) {
        notice_lang(s_NickServ, u, NS_ADDNICK_DISABLED);
        return MOD_CONT;
    }
    if (checkDefCon(DEFCON_NO_NEW_NICKS)) {
        notice_lang(s_NickServ, u, OPER_DEFCON_DENIED);
        return MOD_CONT;
    }

    if (RestrictOperNicks) {
        for (i = 0; i < RootNumber; i++) {
            if (stristr(u->nick, ServicesRoots[i]) && !is_oper(u)) {
                notice_lang(s_NickServ, u, NICK_CANNOT_BE_REGISTERED,
                            u->nick);
                return MOD_CONT;
            }
        }
        for (i = 0; i < servadmins.count && (nc = servadmins.list[i]); i++) {
            if (stristr(u->nick, nc->display) && !is_oper(u)) {
                notice_lang(s_NickServ, u, NICK_CANNOT_BE_REGISTERED,
                            u->nick);
                return MOD_CONT;
            }
        }
        for (i = 0; i < servopers.count && (nc = servopers.list[i]); i++) {
            if (stristr(u->nick, nc->display) && !is_oper(u)) {
                notice_lang(s_NickServ, u, NICK_CANNOT_BE_REGISTERED,
                            u->nick);
                return MOD_CONT;
            }
        }
    }

    if (!nick || !pass) {
        syntax_error(s_NickServ, u, "ADDNICK", NS_ADDNICK_SYNTAX);
    } else if (!(target = findnick(nick))) {
        notice_lang(s_NickServ, u, NICK_X_NOT_REGISTERED, nick);
    } else if (time(NULL) < u->lastnickreg + NSRegDelay) {
        notice_lang(s_NickServ, u, NS_ADDNICK_PLEASE_WAIT, NSRegDelay);
    } else if (u->na && (u->na->status & NS_VERBOTEN)) {
        alog("%s: %s@%s tried to use ADDNICK from forbidden nick %s.",
             s_NickServ, u->username, u->host, u->nick);
        notice_lang(s_NickServ, u, NICK_X_FORBIDDEN, u->nick);
    } else if (u->na && (u->na->nc->flags & NI_SUSPENDED)) {
        alog("%s: %s!%s@%s tried to use ADDNICK from suspended nick %s.",
             s_NickServ, u->nick, u->username, u->host, target->nick);
        notice_lang(s_NickServ, u, NICK_X_SUSPENDED, u->nick);
    } else if (u->na && NSNoGroupChange) {
        notice_lang(s_NickServ, u, NS_ADDNICK_CHANGE_DISABLED, s_NickServ);
    } else if (u->na && !nick_identified(u)) {
        notice_lang(s_NickServ, u, NICK_IDENTIFY_REQUIRED, s_NickServ);
    } else if (target && (target->nc->flags & NI_SUSPENDED)) {
        alog("%s: %s!%s@%s tried to use GROUP from SUSPENDED nick %s",
             s_NickServ, u->nick, u->username, u->host, target->nick);
        notice_lang(s_NickServ, u, NICK_X_SUSPENDED, target->nick);
    } else if (target->status & NS_VERBOTEN) {
        notice_lang(s_NickServ, u, NICK_X_FORBIDDEN, nick);
    } else if (u->na && target->nc == u->na->nc) {
        notice_lang(s_NickServ, u, NS_ADDNICK_SAME, target->nick);
    } else if (NSMaxAliases && (target->nc->aliases.count >= NSMaxAliases)
               && !nick_is_services_admin(target->nc)) {
        notice_lang(s_NickServ, u, NS_ADDNICK_TOO_MANY, target->nick,
                    s_NickServ, s_NickServ);
    } else if (enc_check_password(pass, target->nc->pass) != 1) {
        alog("%s: Failed ADDNICK for %s!%s@%s (invalid password).",
             s_NickServ, u->nick, u->username, u->host);
        notice_lang(s_NickServ, u, PASSWORD_INCORRECT);
        bad_password(u);
    } else {
        /* If the nick is already registered, drop it.
         * If not, check that it is valid.
         */
        if (u->na) {
            delnick(u->na);
        } else {
            int prefixlen = strlen(NSGuestNickPrefix);
            int nicklen = strlen(u->nick);

            if (nicklen <= prefixlen + 7 && nicklen >= prefixlen + 1
                && stristr(u->nick, NSGuestNickPrefix) == u->nick
                && strspn(u->nick + prefixlen,
                          "1234567890") == nicklen - prefixlen) {
                notice_lang(s_NickServ, u, NICK_CANNOT_BE_REGISTERED,
                            u->nick);
                return MOD_CONT;
            }
        }
        na = makealias(u->nick, target->nc);

        if (na) {
            na->last_usermask =
                scalloc(strlen(common_get_vident(u)) +
                        strlen(common_get_vhost(u)) + 2, 1);
            sprintf(na->last_usermask, "%s@%s", common_get_vident(u),
                    common_get_vhost(u));
            na->last_realname = sstrdup(u->realname);
            na->time_registered = na->last_seen = time(NULL);
            na->status = (int16) (NS_IDENTIFIED | NS_RECOGNIZED);

            if (!(na->nc->flags & NI_SERVICES_ROOT)) {
                for (i = 0; i < RootNumber; i++) {
                    if (!stricmp(ServicesRoots[i], u->nick)) {
                        na->nc->flags |= NI_SERVICES_ROOT;
                        break;
                    }
                }
            }

            u->na = na;
            na->u = u;

#ifdef USE_RDB
            /* Is this really needed? Since this is a new alias it will get
             * its unique id on the next update, since it was previously
             * deleted by delnick. Must observe...
             */
            if (rdb_open()) {
                rdb_save_ns_alias(na);
                rdb_close();
            }
#endif
            send_event(EVENT_GROUP, 1, u->nick);
            alog("%s: %s!%s@%s makes %s join group of %s (%s) (e-mail: %s)", s_NickServ, u->nick, u->username, u->host, u->nick, target->nick, target->nc->display, (target->nc->email ? target->nc->email : "none"));
            notice_lang(s_NickServ, u, NS_ADDNICK_SUCCESS, target->nick);

            u->lastnickreg = time(NULL);
            snprintf(tsbuf, sizeof(tsbuf), "%lu",
                     (unsigned long int) u->timestamp);
            if (ircd->modeonreg) {
                len = strlen(ircd->modeonreg);
                strncpy(modes,ircd->modeonreg,512);
	       if(ircd->rootmodeonid && is_services_root(u)) { 
                    strncat(modes,ircd->rootmodeonid,512-len);
	        } else if(ircd->adminmodeonid && is_services_admin(u)) {
                    strncat(modes,ircd->adminmodeonid,512-len);
	        } else if(ircd->opermodeonid && is_services_oper(u)) {
                    strncat(modes,ircd->opermodeonid,512-len);
                }
                if (ircd->tsonmode) {
                    common_svsmode(u, modes, tsbuf);
                } else {
                    common_svsmode(u, modes, NULL);
                }
            }

            check_memos(u);
        } else {
            alog("%s: makealias(%s) failed", s_NickServ, u->nick);
            notice_lang(s_NickServ, u, NS_ADDNICK_FAILED);
        }
    }
    return MOD_CONT;
}
示例#10
0
文件: callbacks.c 项目: phddoom/uzbl
gboolean
download_cb(WebKitWebView *web_view, WebKitDownload *download, gpointer user_data) {
    (void) web_view; (void) user_data;

    /* get the URI being downloaded */
    const gchar *uri = webkit_download_get_uri(download);

    /* get the destination path, if specified.
     * this is only intended to be set when this function is trigger by an
     * explicit download using uzbl's 'download' action. */
    const gchar *destination = user_data;

    if (uzbl.state.verbose)
        printf("Download requested -> %s\n", uri);

    if (!uzbl.behave.download_handler) {
        webkit_download_cancel(download);
        return FALSE; /* reject downloads when there's no download handler */
    }

    /* get a reasonable suggestion for a filename */
    const gchar *suggested_filename;
#ifdef USE_WEBKIT2
    WebKitURIResponse *response;
    g_object_get(download, "network-response", &response, NULL);
#if WEBKIT_CHECK_VERSION (1, 9, 90)
    g_object_get(response, "suggested-filename", &suggested_filename, NULL);
#else
    suggested_filename = webkit_uri_response_get_suggested_filename(respose);
#endif
#elif WEBKIT_CHECK_VERSION (1, 9, 6)
    WebKitNetworkResponse *response;
    g_object_get(download, "network-response", &response, NULL);
    g_object_get(response, "suggested-filename", &suggested_filename, NULL);
#else
    g_object_get(download, "suggested-filename", &suggested_filename, NULL);
#endif

    /* get the mimetype of the download */
    const gchar *content_type = NULL;
    WebKitNetworkResponse *r  = webkit_download_get_network_response(download);
    /* downloads can be initiated from the context menu, in that case there is
       no network response yet and trying to get one would crash. */
    if(WEBKIT_IS_NETWORK_RESPONSE(r)) {
        SoupMessage        *m = webkit_network_response_get_message(r);
        SoupMessageHeaders *h = NULL;
        g_object_get(m, "response-headers", &h, NULL);
        if(h) /* some versions of libsoup don't have "response-headers" here */
            content_type = soup_message_headers_get_one(h, "Content-Type");
    }

    if(!content_type)
        content_type = "application/octet-stream";

    /* get the filesize of the download, as given by the server.
       (this may be inaccurate, there's nothing we can do about that.)  */
    unsigned int total_size = webkit_download_get_total_size(download);

    GArray *a = g_array_new (TRUE, FALSE, sizeof(gchar*));
    const CommandInfo *c = parse_command_parts(uzbl.behave.download_handler, a);
    if(!c) {
        webkit_download_cancel(download);
        g_array_free(a, TRUE);
        return FALSE;
    }

    g_array_append_val(a, uri);
    g_array_append_val(a, suggested_filename);
    g_array_append_val(a, content_type);
    gchar *total_size_s = g_strdup_printf("%d", total_size);
    g_array_append_val(a, total_size_s);

    if(destination)
        g_array_append_val(a, destination);

    GString *result = g_string_new ("");
    run_parsed_command(c, a, result);

    g_free(total_size_s);
    g_array_free(a, TRUE);

    /* no response, cancel the download */
    if(result->len == 0) {
        webkit_download_cancel(download);
        return FALSE;
    }

    /* we got a response, it's the path we should download the file to */
    gchar *destination_path = result->str;
    g_string_free(result, FALSE);

    /* presumably people don't need newlines in their filenames. */
    char *p = strchr(destination_path, '\n');
    if ( p != NULL ) *p = '\0';

    /* set up progress callbacks */
    g_signal_connect(download, "notify::status",   G_CALLBACK(download_status_cb),   NULL);
    g_signal_connect(download, "notify::progress", G_CALLBACK(download_progress_cb), NULL);

    /* convert relative path to absolute path */
    if(destination_path[0] != '/') {
        gchar *rel_path = destination_path;
        gchar *cwd = g_get_current_dir();
        destination_path = g_strconcat(cwd, "/", destination_path, NULL);
        g_free(cwd);
        g_free(rel_path);
    }

    send_event(DOWNLOAD_STARTED, NULL, TYPE_STR, destination_path, NULL);

    /* convert absolute path to file:// URI */
    gchar *destination_uri = g_strconcat("file://", destination_path, NULL);
    g_free(destination_path);

    webkit_download_set_destination_uri(download, destination_uri);
    g_free(destination_uri);

    return TRUE;
}
示例#11
0
void
playdata(u_char *buf, u_int tot, char *name)
{
	long long delta_nsec = 0;
	u_int delta_ticks;
	int format, ntrks, divfmt, ticks, t, besttrk = 0;
	u_int len, mlen;
	u_char *p, *end, byte, meta;
	struct track *tracks;
	u_long bestcur, now;
	struct track *tp;

	end = buf + tot;
	if (verbose)
		printf("Playing %s (%d bytes) ... \n", name, tot);

	if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
		warnx("Not a MIDI file, missing header");
		return;
	}
	if (GET32(buf + MARK_LEN) != HEADER_LEN) {
		warnx("Not a MIDI file, bad header");
		return;
	}
	format = GET16(buf + MARK_LEN + SIZE_LEN);
	ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
	divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
	ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
	p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
	if ((divfmt & 0x80) == 0)
		ticks |= divfmt << 8;
	else
		errx(1, "Absolute time codes not implemented yet");
	if (verbose > 1)
		printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
		       format, ntrks, divfmt, ticks);
	if (format != 0 && format != 1) {
		warnx("Cannnot play MIDI file of type %d", format);
		return;
	}
	if (ntrks == 0)
		return;
	tracks = calloc(ntrks, sizeof(struct track));
	if (tracks == NULL)
		err(1, "malloc() tracks failed");
	for (t = 0; t < ntrks; ) {
		if (p >= end - MARK_LEN - SIZE_LEN) {
			warnx("Cannot find track %d", t);
			goto ret;
		}
		len = GET32(p + MARK_LEN);
		if (len > end - (p + MARK_LEN + SIZE_LEN)) {
			warnx("Crazy track length");
			goto ret;
		}
		if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
			tracks[t].start = p + MARK_LEN + SIZE_LEN;
			tracks[t].end = tracks[t].start + len;
			tracks[t].curtime = getvar(&tracks[t]);
			t++;
		}
		p += MARK_LEN + SIZE_LEN + len;
	}

	/* 
	 * Play MIDI events by selecting the track with the lowest
	 * curtime.  Execute the event, update the curtime and repeat.
	 */

	now = 0;
	delta_nsec = 0;
	if (clock_gettime(CLOCK_MONOTONIC, &ts_last) < 0)
		err(1, "clock_gettime");
	for (;;) {
		/* Locate lowest curtime */
		bestcur = ULONG_MAX;
		for (t = 0; t < ntrks; t++) {
			if (tracks[t].curtime < bestcur) {
				bestcur = tracks[t].curtime;
				besttrk = t;
			}
		}
		if (bestcur == ULONG_MAX)
			break;
		if (verbose > 1) {
			printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
			fflush(stdout);
		}
		while (now < bestcur) {
			pause();
			if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
				err(1, "clock_gettime");
			delta_nsec += 1000000000L * (ts.tv_sec - ts_last.tv_sec);
			delta_nsec += ts.tv_nsec - ts_last.tv_nsec;
			ts_last = ts;
			if (delta_nsec <= 0)
				continue;
			delta_ticks = delta_nsec * ticks / (1000LL * tempo);
			delta_nsec -= 1000LL * delta_ticks * tempo / ticks;
			now += delta_ticks;
		}
		tp = &tracks[besttrk];
		byte = *tp->start++;
		if (byte == MIDI_META) {
			meta = *tp->start++;
			mlen = getvar(tp);
			if (verbose > 1)
				printf("META %02x (%d)\n", meta, mlen);
			dometa(meta, tp->start, mlen);
			tp->start += mlen;
		} else {
			if (MIDI_IS_STATUS(byte))
				tp->status = byte;
			else
				tp->start--;
			if (MIDI_IS_COMMON(tp->status)) {
				mlen = MIDI_LENGTH(tp->status);
				send_event(tp->status, tp->start, mlen);
			} else if (tp->status == MIDI_SYSEX_START) {
				mlen = getvar(tp);
				send_event(MIDI_SYSEX_START, tp->start, mlen);
			} else if (tp->status == MIDI_SYSEX_STOP) {
				mlen = getvar(tp);
				/* Sorry, can't do this yet */;
			} else {
				if (verbose)
					printf("MIDI event 0x%02x ignored\n",
					       tp->status);
			}
			tp->start += mlen;
		}
		if (tp->start >= tp->end)
			tp->curtime = ULONG_MAX;
		else
			tp->curtime += getvar(tp);
	}
 ret:
	free(tracks);
}
示例#12
0
//
// USAGE: trixiekeys {input_device_path | input_device_name} [output_device_name]
//
int main(int argc, char* argv[]) {
    struct uinput_user_dev odev_data;
    struct input_event ev;
    char hdev_name[256] = "Unknown";
    char udev_name[256] = "TrixieKeys keyboard";
    char hdev_path[256];
    char udev_path[256] = "/dev/uinput";
    char devdir_path[256] = "/dev/input/";

    /*
    char* event_types[EV_CNT] = { NULL };
    #define ADD_EVENT_TYPE(x) (event_types[x] = #x)
    ADD_EVENT_TYPE(EV_SYN);
    ADD_EVENT_TYPE(EV_SYN);
    ADD_EVENT_TYPE(EV_KEY);
    ADD_EVENT_TYPE(EV_REL);
    ADD_EVENT_TYPE(EV_ABS);
    ADD_EVENT_TYPE(EV_MSC);
    ADD_EVENT_TYPE(EV_SW);
    ADD_EVENT_TYPE(EV_LED);
    ADD_EVENT_TYPE(EV_SND);
    ADD_EVENT_TYPE(EV_REP);
    ADD_EVENT_TYPE(EV_FF);
    ADD_EVENT_TYPE(EV_PWR);
    ADD_EVENT_TYPE(EV_FF_STATUS);
    ADD_EVENT_TYPE(EV_MAX);
    #undef ADD_EVENT_TYPE
    #define EVENT_TYPE(x) (((x) >= 0 && (x) < ARR_LEN(event_types) && event_types[(x)]) ? event_types[(x)] : "EV_UNKNOWN")
    */

	signal(SIGTERM, sighandler);
    signal(SIGINT, sighandler);

    if (argc < 2 || argc > 3) {
        die("USAGE: trixiekeys {input_device_path | input_device_name} [output_device_name]");
    }

    if (argc == 3) {
        strncpy(udev_name, argv[2], sizeof(udev_name)-1);
    }

    // 1. modprobe uinput

    if (0 != system("modprobe uinput")) {
        die("Couldn't modprobe uinput module.");
    }

    // 2. find the input device

    if (argv[1][0] == '/') {
        strncpy(hdev_path, argv[1], sizeof(hdev_path)-1);
    } else if (!find_dev_by_name(devdir_path, argv[1], hdev_path, sizeof(hdev_path)-1)) {
        die("Couldn't find a device with the specified name");
    }

    // 3. grab hardware device

    hdev_fd = open(hdev_path, O_RDWR);// | O_NDELAY);
    if (hdev_fd < 0) {
        die("Couldn't open source event device.");
    }

    ioctl(hdev_fd, EVIOCGNAME(sizeof(hdev_name)), hdev_name);
    printf("Reading From : %s (%s)\n", hdev_path, hdev_name);

    if (0 != ioctl(hdev_fd, EVIOCGRAB, 1)) {
        die("Coudn't get exclusive access to the hardware device.");
    }

    // 4. setup uinput device

    udev_fd = open(udev_path, O_RDWR);// | O_NDELAY);
    if (udev_fd < 0) {
        die("Couldn't open uinput device.");
    }

    memset(&odev_data, 0, sizeof(odev_data));
    strncpy(odev_data.name, udev_name, UINPUT_MAX_NAME_SIZE);
    odev_data.id.version = 4;
    odev_data.id.bustype = BUS_USB;

    ioctl(udev_fd, UI_SET_EVBIT, EV_MSC);
    ioctl(udev_fd, UI_SET_MSCBIT, MSC_SCAN);

    ioctl(udev_fd, UI_SET_EVBIT, EV_KEY);
    for (int i = 0; i < KEY_CNT; i++) {
        ioctl(udev_fd, UI_SET_KEYBIT, i);
    }
    ioctl(udev_fd, UI_SET_EVBIT, EV_LED);
    for (int i = 0; i < LED_CNT; i++) {
        ioctl(udev_fd, UI_SET_LEDBIT, i);
    }

    write(udev_fd, &odev_data, sizeof(odev_data));

    if (0 != ioctl(udev_fd, UI_DEV_CREATE)) {
        die("Couldn't create UINPUT device.");
    }

    // 5. obtain user's config

    permanent_map = current_map = get_map();

    // 6. become daemon

	daemon(0, 1);

    // 7. create fd_set to select from input devices

    fd_set read_fd_set;
    const int nfds = (hdev_fd > udev_fd ? hdev_fd : udev_fd) + 1;
    FD_ZERO(&read_fd_set);
    FD_SET(hdev_fd, &read_fd_set);
    FD_SET(udev_fd, &read_fd_set);

    // 8. enter main loop

    int skip_next_syn = 0;
    while (!want_to_exit) {
        if (select(nfds, &read_fd_set, NULL, NULL, NULL) < 0) {
            die("Couldn't read nor wait for event\n");
        }
        

        // just pass LED commands that come to our keyboard
        if (FD_ISSET(udev_fd, &read_fd_set)) {
            
            read_event(udev_fd, &ev);

            //printf("U: %s %7d %3hd %30ld\n", EVENT_TYPE(ev.type), ev.value, ev.code, ev.time.tv_usec);

            if (ev.type == EV_LED) {
                write_event(hdev_fd, &ev);
            }

        }

        if (FD_ISSET(hdev_fd, &read_fd_set)) {
            
            read_event(hdev_fd, &ev);

            //printf("H: %s %7d %3hd %30ld\n", EVENT_TYPE(ev.type), ev.value, ev.code, ev.time.tv_usec);

            switch (ev.type) {

                case EV_KEY:
                    skip_next_syn = 1;
                    process_event(&ev);
                    break;

                case EV_SYN:
                    if (!skip_next_syn) {
                        send_event(ev.type, ev.value, ev.code, 0);
                    }
                    skip_next_syn = 0;
                    break;

                case EV_LED:
                    skip_next_syn = 0;
                    break;

                default:
                    send_event(ev.type, ev.value, ev.code, 0);
                    skip_next_syn = 0;
                    break;

            }

        }

        FD_ZERO(&read_fd_set);
        FD_SET(hdev_fd, &read_fd_set);
        FD_SET(udev_fd, &read_fd_set);

    }

    printf("Exiting.\n");
    ioctl(hdev_fd, EVIOCGRAB, 0);

    close(hdev_fd);
    close(udev_fd);

    return 0;
}
示例#13
0
void process_event(const struct input_event * iev) {
    key_data *k;
    switch (iev->value) {
        case VAL_PRESS:
            if (candidate) {
                modifier = candidate;
                candidate = 0;
                if (press_map[modifier]->shift_map) {
                    current_map = press_map[modifier]->shift_map;
                }
                if (press_map[modifier]->mod_code) {
                    SEND(press_map[modifier]->mod_code);
                }
            }
            k = &current_map[iev->code];
            press_map[iev->code] = k;
            flush_buffer();
            if ((k->shift_map || k->mod_code) && !modifier) {
#ifdef DEBUG
                printf("MODIFIER CANDIDATE: %d %d\n", k->mod_code, k->shift_map != NULL);
#endif
                candidate = iev->code;
            } else {
                if (k->lock_map) {
                    // do nothing
                    //permanent_map = k->lock_map; will be done on release
                } else if (k->key_code) {
                    SEND(k->key_code);
                } else if (k->key_codes) {
                    int *p = k->key_codes;
                    while (*p) {
                        SEND(*p);
                        p++;
                    }
                }
            }
            break;
        case VAL_RELEASE:
            k = press_map[iev->code];
            if (!k) {
                SEND( - iev->code); // key was pressed before we started
            } else if (iev->code == modifier) {
                modifier = 0;
                current_map = permanent_map;
                if (k->mod_code) {
                    SEND( - k->mod_code);
                }
                flush_buffer();
            } else if (iev->code == candidate) {
                candidate = 0;
                if (k->key_code) {
                    SEND(k->key_code);
                    flush_buffer();
                    SEND( - k->key_code);
                } else {
                    flush_buffer();
                }
            } else if (candidate) {
                if (k->key_code) {
                    event_buf[event_buf_len++] = -k->key_code;
                }
            } else {
                if (k->lock_map) {
                    current_map = permanent_map = k->lock_map;
                } else if (k->key_code) {
                    SEND( - k->key_code);
                }
            }
            press_map[iev->code] = NULL;
            break;

        case VAL_REPEAT:
            k = press_map[iev->code];
            if (!k) {
                // key was pressed before we started
                send_event(EV_KEY, VAL_REPEAT, iev->code, 1);
            } else if (!candidate && k->key_code) {
                send_event(EV_KEY, VAL_REPEAT, k->key_code, 1);
            } // else: drop event
            break;
        default:
#ifdef DEBUG
            printf("Unknown event to process\n");
#endif
            break;

    }
}
void on_axis_change(robot_event *ev) {
    
	static int max = 0; //maximum value protection (for normalizing the motors)
	static int mot1 = 0, mot2 = 0, mot3 = 0, mot4 = 0; //Motor values (for mechanum steering)
	static unsigned char xAxis = 127, yAxis = 127, rAxis = 127; //x (lateral) y(forward) and r (rotational) axis values
	static int xNew = 0, yNew = 0, rNew =0; // 0 centered axis values
	
	robot_event new_ev;
	unsigned char axis = ev->index;
	unsigned char value = ev->value;
	if(value == 255) value = 254;
	if(value == 0) value = 1;
	 
	send_event(ev);
                                                                     //for turbo hack
	if(axis == CON_XAXIS || axis == CON_YAXIS || axis == CON_RAXIS || axis == 255) {
        if(axis == CON_YAXIS)
            yAxis = value;
        if(axis == CON_XAXIS)
            xAxis = value;
        if(axis == CON_RAXIS)
            rAxis = value;
        xNew = (int)xAxis - 127;
        yNew = (int)yAxis - 127;
        rNew = (int)rAxis - 127;
        mot1 = -(yNew - xNew + rNew);
        mot2 = (yNew + xNew + rNew);
        mot3 = -(yNew - xNew - rNew);
        mot4 = (-yNew - xNew + rNew);
        if(abs(mot1) >  127 || abs(mot2) > 127 || abs(mot3) > 127 || abs(mot4) > 127) {
            max = 0;
            if(abs(mot1)>max)
                max = abs(mot1);
            if(abs(mot2)>max)
                max = abs(mot2);
            if(abs(mot3)>max)
                max = abs(mot3);
            if(abs(mot4)>max)
                max = abs(mot4);
            mot1=(int)((float)mot1/max*127);
            mot2=(int)((float)mot2/max*127);
            mot3=(int)((float)mot3/max*127);
            mot4=(int)((float)mot4/max*127);
        }
		mot1 = (mot1*2)/(4 - turbo);
		mot2 = (mot2*2)/(4 - turbo);
		mot3 = (mot3*2)/(4 - turbo);
		mot4 = (mot4*2)/(4 - turbo);
		
		
		// send four axes out
        new_ev.command = ROBOT_EVENT_MOTOR;

        new_ev.index = 0; 
        new_ev.value = mot1 + 127;
		send_event(&new_ev);

        new_ev.index = 1; 
        new_ev.value = mot2 + 127;
		send_event(&new_ev);

        new_ev.index = 2; 
        new_ev.value = mot3 + 127;
		send_event(&new_ev);

        new_ev.index = 3; 
        new_ev.value = mot4 + 127;
		send_event(&new_ev);
	}
}
示例#15
0
/*
 * int get_action_worker(int context, struct button_mapping *user_mappings,
   int timeout)
   This function searches the button list for the given context for the just
   pressed button.
   If there is a match it returns the value from the list.
   If there is no match..
        the last item in the list "points" to the next context in a chain
        so the "chain" is followed until the button is found.
        putting ACTION_NONE will get CONTEXT_STD which is always the last list checked.

   Timeout can be TIMEOUT_NOBLOCK to return immediatly
                  TIMEOUT_BLOCK   to wait for a button press
   Any number >0   to wait that many ticks for a press
 */
static int get_action_worker(int context, int timeout,
                             const struct button_mapping* (*get_context_map)(int) )
{
    const struct button_mapping *items = NULL;
    int button;
    int i=0;
    int ret = ACTION_UNKNOWN;
    static int last_context = CONTEXT_STD;
    
    send_event(GUI_EVENT_ACTIONUPDATE, NULL);

    if (timeout == TIMEOUT_NOBLOCK)
        button = button_get(false);
    else if  (timeout == TIMEOUT_BLOCK)
        button = button_get(true);
    else
        button = button_get_w_tmo(timeout);

#if defined(HAVE_GUI_BOOST) && defined(HAVE_ADJUSTABLE_CPU_FREQ)
    static struct timeout gui_unboost;
    /* Boost the CPU in case of wheel scrolling activity in the defined contexts. 
     * Call unboost with a timeout of GUI_BOOST_TIMEOUT. */
    if ((button&(BUTTON_SCROLL_BACK|BUTTON_SCROLL_FWD)) && 
        (context == CONTEXT_STD      || context == CONTEXT_LIST ||
         context == CONTEXT_MAINMENU || context == CONTEXT_TREE))
    {
        gui_boost(true);
        timeout_register(&gui_unboost, gui_unboost_callback, GUI_BOOST_TIMEOUT, 0);
    }
#endif

    /* Data from sys events can be pulled with button_get_data
     * multimedia button presses don't go through the action system */
    if (button == BUTTON_NONE || button & (SYS_EVENT|BUTTON_MULTIMEDIA))
        return button;
    /* Don't send any buttons through untill we see the release event */
    if (wait_for_release)
    {
        if (button&BUTTON_REL)
        {
            /* remember the button for the below button eating on context
             * change */
            last_button = button;
            wait_for_release = false;
        }
        return ACTION_NONE;
    }
        

#if CONFIG_CODEC == SWCODEC
    /* Produce keyclick */
    keyclick_click(button);
#endif

    if ((context != last_context) && ((last_button & BUTTON_REL) == 0)
#ifdef HAVE_SCROLLWHEEL
        /* Scrollwheel doesn't generate release events  */
        && !(last_button & (BUTTON_SCROLL_BACK | BUTTON_SCROLL_FWD))
#endif
        )
    {
        if (button & BUTTON_REL)
        {
            last_button = button;
            last_action = ACTION_NONE;
        }
        /* eat all buttons until the previous button was |BUTTON_REL
           (also eat the |BUTTON_REL button) */
        return ACTION_NONE; /* "safest" return value */
    }
    last_context = context;
#ifndef HAS_BUTTON_HOLD
    screen_has_lock = ((context & ALLOW_SOFTLOCK) == ALLOW_SOFTLOCK);
    if (screen_has_lock && keys_locked)
    {
        if (button == unlock_combo)
        {
            last_button = BUTTON_NONE;
            keys_locked = false;
            splash(HZ/2, str(LANG_KEYLOCK_OFF));
            return ACTION_REDRAW;
        }
        else
#if (BUTTON_REMOTE != 0)
            if ((button & BUTTON_REMOTE) == 0)
#endif
        {
            if ((button & BUTTON_REL))
                splash(HZ/2, str(LANG_KEYLOCK_ON));
            return ACTION_REDRAW;
        }
    }
    context &= ~ALLOW_SOFTLOCK;
#endif /* HAS_BUTTON_HOLD */

#ifdef HAVE_TOUCHSCREEN
    if (button & BUTTON_TOUCHSCREEN)
    {
        repeated = false;
        short_press = false;
        if (last_button & BUTTON_TOUCHSCREEN)
        {
            if ((button & BUTTON_REL) &&
                ((last_button & BUTTON_REPEAT)==0))
            {
                short_press = true;
            }
            else if (button & BUTTON_REPEAT)
                repeated = true;
        }
        last_button = button;
        return ACTION_TOUCHSCREEN;
    }
#endif

#if defined(HAVE_LCD_BITMAP) && !defined(BOOTLOADER)
    button = button_flip_horizontally(context, button);
#endif

    /*   logf("%x,%x",last_button,button); */
    while (1)
    {
        /*     logf("context = %x",context); */
#if (BUTTON_REMOTE != 0)
        if (button & BUTTON_REMOTE)
            context |= CONTEXT_REMOTE;
#endif
        if ((context & CONTEXT_PLUGIN) && get_context_map)
            items = get_context_map(context);
        else
            items = get_context_mapping(context);

        if (items == NULL)
            break;

        ret = do_button_check(items,button,last_button,&i);

        if (ret == ACTION_UNKNOWN)
        {
            context = get_next_context(items,i);

            if (context != (int)CONTEXT_STOPSEARCHING)
            {
                i = 0;
                continue;
            }
        }

        /* Action was found or STOPSEARCHING was specified */
        break;
    }
    /* DEBUGF("ret = %x\n",ret); */
#ifndef HAS_BUTTON_HOLD
    if (screen_has_lock && (ret == ACTION_STD_KEYLOCK))
    {
        unlock_combo = button;
        keys_locked = true;
        splash(HZ/2, str(LANG_KEYLOCK_ON));

        button_clear_queue();
        return ACTION_REDRAW;
    }
#endif
    if ((current_tick - last_action_tick < REPEAT_WINDOW_TICKS)
         && (ret == last_action))
        repeated = true;
    else
        repeated = false;

    last_button = button;
    last_action = ret;
    last_data   = button_get_data();
    last_action_tick = current_tick;
    return ret;
}
示例#16
0
int main(int argc, char **argv)
{
  int res;

  try {
    socket.bind ("tcp://*:14444");
    s_sendmore (socket, "event");
        s_send (socket, "{type:\"up\"}");
  }
  catch (zmq::error_t e) {
    cerr << "Cannot bind to socket: " <<e.what() << endl;
    return -1;
  }

  //  printf("Kinect camera test\n");
  //
  //  int i;
  //  for (i=0; i<2048; i++) {
  //    float v = i/2048.0;
  //    v = powf(v, 3)* 6;
  //    t_gamma[i] = v*6*256;
  //  }
  //
  //  g_argc = argc;
  //  g_argv = argv;
  //
  //  //setup Freenect...
  //  if (freenect_init(&f_ctx, NULL) < 0) {
  //    printf("freenect_init() failed\n");
  //    return 1;
  //  }
  //
  //  freenect_set_log_level(f_ctx, FREENECT_LOG_ERROR);
  //
  //  int nr_devices = freenect_num_devices (f_ctx);
  //  printf ("Number of devices found: %d\n", nr_devices);
  //
  //  int user_device_number = 0;
  //  if (argc > 1)
  //    user_device_number = atoi(argv[1]);
  //
  //  if (nr_devices < 1)
  //    return 1;
  //
  //  if (freenect_open_device(f_ctx, &f_dev, user_device_number) < 0) {
  //    printf("Could not open device\n");
  //    return 1;
  //  }
  //
  //  freenect_set_tilt_degs(f_dev,freenect_angle);
  //  freenect_set_led(f_dev,LED_RED);
  //  freenect_set_depth_callback(f_dev, depth_cb);
  //  freenect_set_video_callback(f_dev, rgb_cb);
  //  freenect_set_video_format(f_dev, FREENECT_VIDEO_RGB);
  //  freenect_set_depth_format(f_dev, FREENECT_DEPTH_11BIT);
  //
  //  freenect_start_depth(f_dev);
  //  freenect_start_video(f_dev);

  initFreenect();

  //start the freenect thread to poll for events
  res = pthread_create(&ocv_thread, NULL, freenect_threadfunc, NULL);
  if (res) {
    printf("pthread_create failed\n");
    return 1;
  }

  Mat depthf;

  Mat frameMat(rgbMat);
  Mat blobMaskOutput(frameMat.size(),CV_8UC1),
  outC(frameMat.size(),CV_8UC3);
  Mat prevImg(frameMat.size(),CV_8UC1),
  nextImg(frameMat.size(),CV_8UC1),
  prevDepth(depthMat.size(),CV_8UC1);
  vector<Point2f> prevPts,nextPts;
  vector<uchar> statusv;
  vector<float> errv;
  Rect cursor(frameMat.cols/2,frameMat.rows/2,10,10);
  bool update_bg_model = true;
  int fr = 1;
  int register_ctr = 0,register_secondbloc_ctr = 0;
  bool registered = false;

  Point2i appear(-1,-1); double appearTS = -1;

  Point2i midBlob(-1,-1);
  Point2i lastMove(-1,-1);

  int hcr_ctr = -1;
  vector<int> hc_stack(20); int hc_stack_ptr = 0;

  while (!die) {
    fr++;

    //    imshow("rgb", rgbMat);
    pthread_mutex_lock(&buf_mutex);

    //Linear interpolation
    {
      Mat _tmp = (depthMat - 400.0);          //minimum observed value is ~440. so shift a bit
      _tmp.setTo(Scalar(2048), depthMat > ((!registered) ? 700.0 : 750.0));   //cut off at 600 to create a "box" where the user interacts
      _tmp.convertTo(depthf, CV_8UC1, 255.0/1648.0);  //values are 0-2048 (11bit), account for -400 = 1648
    }

    {
      Mat _tmp;
      depthMat.convertTo(_tmp, CV_8UC1, 255.0/2048.0);
      cvtColor(_tmp, outC, CV_GRAY2BGR);
    }

    pthread_mutex_unlock(&buf_mutex);

    //    { //saving the frames to files for debug
    //      stringstream ss; ss << "depth_"<<fr<<".png";
    //      imwrite(ss.str(), depthf);
    //    }

    //Logarithm interpolation - try it!, It should be more "sensitive" for closer depths
    //    {
    //      Mat tmp,tmp1;
    //      depthMat.convertTo(tmp, CV_32FC1);
    //      log(tmp,tmp1);
    //      tmp1.convertTo(depthf, CV_8UC1, 255.0/7.6246189861593985);
    //    }
    //    imshow("depth",depthf);


    Mat blobMaskInput = depthf < 255; //anything not white is "real" depth
    vector<Point> ctr,ctr2;


    Scalar blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob); //find contours in the foreground, choose biggest
    imshow("first", blobMaskOutput);
    /////// blb :
    //blb[0] = x, blb[1] = y, blb[2] = 1st blob size, blb[3] = 2nd blob size.

    //    uint mode_counters[3] = {0};

    if(blb[0]>=0 && blb[2] > 500) { //1st blob detected, and is big enough
      //cvtColor(depthf, outC, CV_GRAY2BGR);

      //closest point to the camera
      Point minLoc; double minval,maxval;
      minMaxLoc(depthf, &minval, &maxval, &minLoc, NULL, blobMaskInput);
      circle(outC, minLoc, 5, Scalar(0,255,0), 3);

      Scalar mn,stdv;
      meanStdDev(depthf,mn,stdv,blobMaskInput);

      //cout << "min: " << minval << ", max: " << maxval << ", mean: " << mn[0] << endl;

      blobMaskInput = depthf < (mn[0] + stdv[0]*.5);

      blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob);

      imshow("second", blobMaskOutput);

      if(blb[0] >= 0 && blb[2] > 300) {
        //draw contour
        Scalar color(0,0,255);
        for (int idx=0; idx<ctr.size()-1; idx++)
          line(outC, ctr[idx], ctr[idx+1], color, 1);
        line(outC, ctr[ctr.size()-1], ctr[0], color, 1);

        if(ctr2.size() > 0) {
          Scalar color2(255,0,255);
          for (int idx=0; idx<ctr2.size()-1; idx++)
            line(outC, ctr2[idx], ctr2[idx+1], color2, 2);
          line(outC, ctr2[ctr2.size()-1], ctr2[0], color2, 2);
        }

        //draw "major axis"
        //      Vec4f _line;
        Mat curve(ctr);
        //      fitLine(curve, _line, CV_DIST_L2, 0, 0.01, 0.01);
        //      line(outC, Point(blb[0]-_line[0]*70,blb[1]-_line[1]*70),
        //            Point(blb[0]+_line[0]*70,blb[1]+_line[1]*70),
        //            Scalar(255,255,0), 1);

        //blob center
        circle(outC, Point(blb[0],blb[1]), 50, Scalar(255,0,0), 3);


        //      cout << "min depth " << minval << endl;

        register_ctr = MIN((register_ctr + 1),60);

        if(blb[3] > 5000)
          register_secondbloc_ctr = MIN((register_secondbloc_ctr + 1),60);

        if (register_ctr > 30 && !registered) {
          registered = true;
          appear.x = -1;
          update_bg_model = false;
          lastMove.x = blb[0]; lastMove.y = blb[1];

          cout << "blob size " << blb[2] << endl;

          if(register_secondbloc_ctr < 30) {
            if(blb[2] > 10000) {
              cout << "register panner" << endl;
              send_event("Register", "\"mode\":\"openhand\"");
            } else {
              cout << "register pointer" << endl;
              send_event("Register", "\"mode\":\"theforce\"");
            }
          } else {
            cout << "register tab swithcer" << endl;
            send_event("Register", "\"mode\":\"twohands\"");
          }
        }

        if(registered) {
          stringstream ss;
          ss  << "\"x\":"  << (int)floor(blb[0]*100.0/640.0)
            << ",\"y\":" << (int)floor(blb[1]*100.0/480.0)
            << ",\"z\":" << (int)(mn[0] * 2.0);
          //cout << "move: " << ss.str() << endl;
          send_event("Move", ss.str());

          //---------------------- fist detection ---------------------
          //calc laplacian of curve
          vector<Point> approxCurve;  //approximate curve
          approxPolyDP(curve, approxCurve, 10.0, true);
          Mat approxCurveM(approxCurve);

          Mat curve_lap;
          calc_laplacian(approxCurveM, curve_lap);  //calc laplacian

          hcr_ctr = 0;
          for (int i=0; i<approxCurve.size(); i++) {
            double n = norm(((Point2d*)(curve_lap.data))[i]);
            if (n > 10.0) {
              //high curvature point
              circle(outC, approxCurve[i], 3, Scalar(50,155,255), 2);
              hcr_ctr++;
            }
          }

          hc_stack.at(hc_stack_ptr) = hcr_ctr;
          hc_stack_ptr = (hc_stack_ptr + 1) % hc_stack.size();

          Scalar _avg = mean(Mat(hc_stack));
          if (abs(_avg[0] - (double)hcr_ctr) > 5.0) { //a big change in curvature = hand fisted/opened?
            cout << "Hand click!" << endl;
            send_event("HandClick", "");
          }

          if (mode_state == MODE_NONE) {

          }

          //        imshow("out",out);
          //doHist(depthf,out);

          { //some debug on screen..
            stringstream ss; ss << "high curve pts " << hcr_ctr << ", avg " << _avg[0];
            putText(outC, ss.str(), Point(50,50), CV_FONT_HERSHEY_PLAIN, 2.0,Scalar(0,0,255), 2);
          }
        } else {
          //not registered, look for gestures
          if(appear.x<0) {
            //first appearence of blob
            appear = midBlob;
            //          update_bg_model = false;
            appearTS = getTickCount();
            cout << "appear ("<<appearTS<<") " << appear.x << "," << appear.y << endl;
          } else {
            //blob was seen before, how much time passed
            double timediff = ((double)getTickCount()-appearTS)/getTickFrequency();
            if (timediff > .2 && timediff < 1.0) {
              //enough time passed from appearence
              line(outC, appear, Point(blb[0],blb[1]), Scalar(0,0,255), 3);
              if (appear.x - blb[0] > 100) {
                cout << "right"<<endl; appear.x = -1;
                send_event("SwipeRight", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.x - blb[0] < -100) {
                cout << "left" <<endl; appear.x = -1;
                send_event("SwipeLeft", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.y - blb[1] > 100) {
                cout << "up" << endl; appear.x = -1;
                send_event("SwipeUp", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.y - blb[1] < -100) {
                cout << "down" << endl; appear.x = -1;
                send_event("SwipeDown", "");
                update_bg_model = true;
                register_ctr = 0;
              }
            }
            if(timediff >= 1.0) {
              cout << "a ghost..."<<endl;
              update_bg_model = true;
              //a second passed from appearence - reset 1st appear
              appear.x = -1;
              appearTS = -1;
              midBlob.x = midBlob.y = -1;
            }
          }
        }
        send_image(outC);
      }
    } else {
      send_image(depthf);
      register_ctr = MAX((register_ctr - 1),0);
      register_secondbloc_ctr = MAX((register_secondbloc_ctr - 1),0);
    }
    imshow("blob",outC);

    if (register_ctr <= 15 && registered) {
      midBlob.x = midBlob.y = -1;
      registered = false;
      mode_state = MODE_NONE;
      update_bg_model = true;
      cout << "unregister" << endl;
      send_event("Unregister", "");
    }

        char k = cvWaitKey(5);
        if( k == 27 ) break;
        if( k == ' ' )
            update_bg_model = !update_bg_model;
    if (k=='s') {
      cout << "send test event" << endl;
      send_event("TestEvent", "");
    }
  }

  printf("-- done!\n");

  pthread_join(ocv_thread, NULL);
  pthread_exit(NULL);
  return 0;
}
示例#17
0
void key_send(__u16 code, __s32 value)
{
    send_event(uinput_fd, EV_KEY, code, value);
    send_event(uinput_fd, EV_SYN, SYN_REPORT, 0);
}
示例#18
0
文件: inspector.c 项目: minozake/uzbl
/* TODO: Add variables and code to make use of these functions */
gboolean
inspector_close_window_cb (WebKitWebInspector* inspector){
    (void) inspector;
    send_event(WEBINSPECTOR, NULL, TYPE_NAME, "close", NULL);
    return TRUE;
}
示例#19
0
void MidiDriver_ALSA::send(uint32 b) {
	if (!_isOpen) {
		warning("MidiDriver_ALSA: Got event while not open");
		return;
	}

	unsigned int midiCmd[4];
	ev.type = SND_SEQ_EVENT_OSS;

	midiCmd[3] = (b & 0xFF000000) >> 24;
	midiCmd[2] = (b & 0x00FF0000) >> 16;
	midiCmd[1] = (b & 0x0000FF00) >> 8;
	midiCmd[0] = (b & 0x000000FF);
	ev.data.raw32.d[0] = midiCmd[0];
	ev.data.raw32.d[1] = midiCmd[1];
	ev.data.raw32.d[2] = midiCmd[2];

	unsigned char chanID = midiCmd[0] & 0x0F;
	switch (midiCmd[0] & 0xF0) {
	case 0x80:
		snd_seq_ev_set_noteoff(&ev, chanID, midiCmd[1], midiCmd[2]);
		send_event(1);
		break;
	case 0x90:
		snd_seq_ev_set_noteon(&ev, chanID, midiCmd[1], midiCmd[2]);
		send_event(1);
		break;
	case 0xA0:
		snd_seq_ev_set_keypress(&ev, chanID, midiCmd[1], midiCmd[2]);
		send_event(1);
		break;
	case 0xB0:
		/* is it this simple ? Wow... */
		snd_seq_ev_set_controller(&ev, chanID, midiCmd[1], midiCmd[2]);

		// We save the volume of the first MIDI channel here to utilize it in
		// our workaround for broken USB-MIDI cables.
		if (chanID == 0 && midiCmd[1] == 0x07)
			_channel0Volume = midiCmd[2];

		send_event(1);
		break;
	case 0xC0:
		snd_seq_ev_set_pgmchange(&ev, chanID, midiCmd[1]);
		send_event(0);

		// Send a volume change command to work around a firmware bug in common
		// USB-MIDI cables. If the first MIDI command in a USB packet is a
		// Cx or Dx command, the second command in the packet is dropped
		// somewhere.
		send(0x07B0 | (_channel0Volume << 16));
		break;
	case 0xD0:
		snd_seq_ev_set_chanpress(&ev, chanID, midiCmd[1]);
		send_event(1);

		// Send a volume change command to work around a firmware bug in common
		// USB-MIDI cables. If the first MIDI command in a USB packet is a
		// Cx or Dx command, the second command in the packet is dropped
		// somewhere.
		send(0x07B0 | (_channel0Volume << 16));
		break;
	case 0xE0: {
		// long theBend = ((((long)midiCmd[1] + (long)(midiCmd[2] << 7))) - 0x2000) / 4;
		// snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
		long theBend = ((long)midiCmd[1] + (long)(midiCmd[2] << 7)) - 0x2000;
		snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
		send_event(1);
		} break;

	default:
		warning("Unknown MIDI Command: %08x", (int)b);
		/* I don't know if this works but, well... */
		send_event(1);
		break;
	}
}
示例#20
0
文件: init.c 项目: WattTech/rtems
static void request(test_context *ctx, task_id id, request_id req)
{
  send_event(ctx, id, req);
  sync_with_helper(ctx);
}
示例#21
0
文件: callbacks.c 项目: phddoom/uzbl
void
close_web_view_cb(WebKitWebView *webview, gpointer user_data) {
    (void) webview; (void) user_data;
    send_event (CLOSE_WINDOW, NULL, NULL);
}
示例#22
0
static int keyboard(int fd)
{
	char buf[128];
	ssize_t ret, i;

	ret = read(STDIN_FILENO, buf, sizeof(buf));
	if (ret == 0) {
		fprintf(stderr, "Read HUP on stdin\n");
		return -EFAULT;
	} else if (ret < 0) {
		fprintf(stderr, "Cannot read stdin: %m\n");
		return -errno;
	}

	for (i = 0; i < ret; ++i) {
		switch (buf[i]) {
		case '1':
			btn1_down = !btn1_down;
			ret = send_event(fd);
			if (ret)
				return ret;
			break;
		case '2':
			btn2_down = !btn2_down;
			ret = send_event(fd);
			if (ret)
				return ret;
			break;
		case '3':
			btn3_down = !btn3_down;
			ret = send_event(fd);
			if (ret)
				return ret;
			break;
		case 'a':
			abs_hor = -20;
			ret = send_event(fd);
			abs_hor = 0;
			if (ret)
				return ret;
			break;
		case 'd':
			abs_hor = 20;
			ret = send_event(fd);
			abs_hor = 0;
			if (ret)
				return ret;
			break;
		case 'w':
			abs_ver = -20;
			ret = send_event(fd);
			abs_ver = 0;
			if (ret)
				return ret;
			break;
		case 's':
			abs_ver = 20;
			ret = send_event(fd);
			abs_ver = 0;
			if (ret)
				return ret;
			break;
		case 'r':
			wheel = 1;
			ret = send_event(fd);
			wheel = 0;
			if (ret)
				return ret;
			break;
		case 'f':
			wheel = -1;
			ret = send_event(fd);
			wheel = 0;
			if (ret)
				return ret;
			break;
		case 'q':
			return -ECANCELED;
		default:
			fprintf(stderr, "Invalid input: %c\n", buf[i]);
		}
	}

	return 0;
}
示例#23
0
文件: callbacks.c 项目: phddoom/uzbl
void
progress_change_cb (WebKitWebView* web_view, GParamSpec param_spec) {
    (void) param_spec;
    int progress = webkit_web_view_get_progress(web_view) * 100;
    send_event(LOAD_PROGRESS, NULL, TYPE_INT, progress, NULL);
}
示例#24
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	snd_seq_event_t ev;
	struct input_event iev;
	snd_seq_addr_t addr;

	fprintf( stderr, "lsmi-mouse" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Initializing mouse interface...\n" );

	if ( -1 == ( fd = open( device, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		exit(1);
	}

	init_mouse();

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME  );
	port = open_output_port( seq );

	if ( sub_name )
	{
		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}
	
	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	set_traps();

	fprintf( stderr, "Waiting for packets...\n" );

	for ( ;; )
	{
		int i;

		read( fd, &iev, sizeof( iev ) );

		if ( iev.type != EV_KEY )
			continue;

		switch ( iev.code )
		{
			case BTN_LEFT:		i = 0; break;
			case BTN_MIDDLE:	i = 1; break;
			case BTN_RIGHT:		i = 2; break;
				break;
			default:
				continue;
				break;
		}

		snd_seq_ev_clear( &ev );

		switch ( ev.type = map[i].ev_type )
		{
			case SND_SEQ_EVENT_CONTROLLER:

				snd_seq_ev_set_controller( &ev, map[i].channel,
												map[i].number,
												iev.value == DOWN ? 127 : 0 );
				break;

			case SND_SEQ_EVENT_NOTEON:
				
				snd_seq_ev_set_noteon( &ev, map[i].channel,
											map[i].number,
											iev.value == DOWN ? 127 : 0 );
				break;

			default:
				fprintf( stderr,
						 "Internal error: invalid mapping!\n" );
				continue;
				break;
		}

		send_event( &ev );
	}
}
示例#25
0
void gui_usb_screen_run(bool early_usb)
{
    (void) early_usb;
    struct usb_screen_vps_t usb_screen_vps_ar[NB_SCREENS];
#if defined HAVE_TOUCHSCREEN
    enum touchscreen_mode old_mode = touchscreen_get_mode();

    /* TODO: Paint buttons on screens OR switch to point mode and use
     * touchscreen as a touchpad to move the host's mouse cursor */
    touchscreen_set_mode(TOUCHSCREEN_BUTTON);
#endif

    push_current_activity(ACTIVITY_USBSCREEN);

#ifdef USB_ENABLE_HID
    usb_hid = global_settings.usb_hid;
    usb_keypad_mode = global_settings.usb_keypad_mode;
#endif

    FOR_NB_SCREENS(i)
    {
        struct screen *screen = &screens[i];

        screen->set_viewport(NULL);
#ifdef HAVE_LCD_CHARCELLS
        /* Quick fix. Viewports should really be enabled proper for charcell */
        viewport_set_defaults(&usb_screen_vps_ar[i].parent, i);
#else
        usb_screen_fix_viewports(screen, &usb_screen_vps_ar[i]);
#endif
    }

    /* update the UI before disabling fonts, this maximizes the propability
     * that font cache lookups succeed during USB */
    send_event(GUI_EVENT_ACTIONUPDATE, NULL);
#ifdef HAVE_LCD_BITMAP
    if(!early_usb)
    {
        /* The font system leaves the .fnt fd's open, so we need for force close them all */
        font_disable_all();
    }
#endif

    usb_acknowledge(SYS_USB_CONNECTED_ACK);

    while (1)
    {
        usb_screens_draw(usb_screen_vps_ar);
#ifdef SIMULATOR
        if (button_get_w_tmo(HZ/2))
            break;
        send_event(GUI_EVENT_ACTIONUPDATE, NULL);
#else
        if (handle_usb_events())
            break;
#endif /* SIMULATOR */
    }

    FOR_NB_SCREENS(i)
    {
        const struct viewport* vp = NULL;

#if defined(HAVE_LCD_BITMAP) && defined(USB_ENABLE_HID)
        vp = usb_hid ? &usb_screen_vps_ar[i].title : NULL;
#elif !defined(HAVE_LCD_BITMAP)
        vp = &usb_screen_vps_ar[i].parent;
#endif
        if (vp)
            screens[i].scroll_stop_viewport(vp);
    }
#ifdef USB_ENABLE_HID
    if (global_settings.usb_keypad_mode != usb_keypad_mode)
    {
        global_settings.usb_keypad_mode = usb_keypad_mode;
        settings_save();
    }
#endif

#ifdef HAVE_TOUCHSCREEN
    touchscreen_set_mode(old_mode);
#endif

#ifdef HAVE_LCD_CHARCELLS
    status_set_usb(false);
#endif /* HAVE_LCD_CHARCELLS */

#ifdef HAVE_LCD_BITMAP
    if(!early_usb)
    {
        font_enable_all();
        /* Not pretty, reload all settings so fonts are loaded again correctly */
        settings_apply(true);
        /* Reload playlist */
        playlist_resume();
    }
#endif

    FOR_NB_SCREENS(i)
    {
        screens[i].backlight_on();
        viewportmanager_theme_undo(i, false);
    }

    pop_current_activity();
}
示例#26
0
文件: main.c 项目: maggu2810/cwiid
void process_classic_mesg(struct cwiid_classic_mesg *mesg)
{
	static uint16_t prev_buttons = 0;
	uint16_t pressed, released;
	__s32 axis_value;
	int i;

	/* Classic Button/Key Events */
	pressed = mesg->buttons & ~prev_buttons;
	released = ~mesg->buttons & prev_buttons;
	for (i=0; i < CONF_CC_BTN_COUNT; i++) {
		if (conf.classic_bmap[i].active) {
			if (pressed & conf.classic_bmap[i].mask) {
				send_event(&conf, EV_KEY, conf.classic_bmap[i].action, 1);
			}
			else if (released & conf.classic_bmap[i].mask) {
				send_event(&conf, EV_KEY, conf.classic_bmap[i].action, 0);
			}
		}
	}
	prev_buttons = mesg->buttons;

	/* Classic.Dpad.X */
	if (conf.amap[CONF_CC_AXIS_DPAD_X].active) {
		axis_value = 0;
		if (mesg->buttons & CWIID_CLASSIC_BTN_LEFT) {
			axis_value = -1;
		}
		else if (mesg->buttons & CWIID_CLASSIC_BTN_RIGHT) {
			axis_value = 1;
		}
		if (conf.amap[CONF_CC_AXIS_DPAD_X].flags & CONF_INVERT) {
			axis_value *= -1;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_DPAD_X].axis_type,
		           conf.amap[CONF_CC_AXIS_DPAD_X].action, axis_value);
	}

	/* Classic.Dpad.Y */
	if (conf.amap[CONF_CC_AXIS_DPAD_Y].active) {
		axis_value = 0;
		if (mesg->buttons & CWIID_CLASSIC_BTN_DOWN) {
			axis_value = -1;
		}
		else if (mesg->buttons & CWIID_CLASSIC_BTN_UP) {
			axis_value = 1;
		}
		if (conf.amap[CONF_CC_AXIS_DPAD_Y].flags & CONF_INVERT) {
			axis_value *= -1;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_DPAD_Y].axis_type,
		           conf.amap[CONF_CC_AXIS_DPAD_Y].action, axis_value);
	}

	/* Classic.LStick.X */
	if (conf.amap[CONF_CC_AXIS_L_STICK_X].active) {
		axis_value = mesg->l_stick[CWIID_X];
		if (conf.amap[CONF_CC_AXIS_L_STICK_X].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_L_STICK_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_L_STICK_X].axis_type,
		           conf.amap[CONF_CC_AXIS_L_STICK_X].action, axis_value);
	}

	/* Classic.LStick.Y */
	if (conf.amap[CONF_CC_AXIS_L_STICK_Y].active) {
		axis_value = mesg->l_stick[CWIID_Y];
		if (conf.amap[CONF_CC_AXIS_L_STICK_Y].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_L_STICK_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_L_STICK_Y].axis_type,
		           conf.amap[CONF_CC_AXIS_L_STICK_Y].action, axis_value);
	}

	/* Classic.RStick.X */
	if (conf.amap[CONF_CC_AXIS_R_STICK_X].active) {
		axis_value = mesg->r_stick[CWIID_X];
		if (conf.amap[CONF_CC_AXIS_R_STICK_X].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_R_STICK_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_R_STICK_X].axis_type,
		           conf.amap[CONF_CC_AXIS_R_STICK_X].action, axis_value);
	}

	/* Classic.RStick.Y */
	if (conf.amap[CONF_CC_AXIS_R_STICK_Y].active) {
		axis_value = mesg->r_stick[CWIID_Y];
		if (conf.amap[CONF_CC_AXIS_R_STICK_Y].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_R_STICK_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_R_STICK_Y].axis_type,
		           conf.amap[CONF_CC_AXIS_R_STICK_Y].action, axis_value);
	}

	/* Classic.LAnalog */
	if (conf.amap[CONF_CC_AXIS_L].active) {
		axis_value = mesg->l;
		if (conf.amap[CONF_CC_AXIS_L].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_LR_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_L].axis_type,
		           conf.amap[CONF_CC_AXIS_L].action, axis_value);
	}

	/* Classic.RAnalog */
	if (conf.amap[CONF_CC_AXIS_R].active) {
		axis_value = mesg->r;
		if (conf.amap[CONF_CC_AXIS_R].flags & CONF_INVERT) {
			axis_value = CWIID_CLASSIC_LR_MAX - axis_value;
		}
		send_event(&conf, conf.amap[CONF_CC_AXIS_R].axis_type,
		           conf.amap[CONF_CC_AXIS_R].action, axis_value);
	}
}
示例#27
0
/**
 * Adds a new user to anopes internal userlist.
 *
 * If the SVID passed is 2, the user will not be marked registered or requested to ID.
 * This is an addition to accomodate IRCds where we cannot determine this based on the NICK 
 * or UID command. Some IRCd's keep +r on when changing nicks and do not use SVID (ex. InspIRCd 1.2).
 * Instead we get a METADATA command containing the accountname the user was last identified to.
 * Since this is received after the user is introduced to us we should not yet mark the user
 * as identified or ask him to identify. We will mark him as recognized for the time being and let
 * him keep his +r if he has it.
 * It is the responsibility of the protocol module to make sure that this is either invalidated,
 * or changed to identified. ~ Viper
 **/
User *do_nick(const char *source, char *nick, char *username, char *host,
              char *server, char *realname, time_t ts, uint32 svid,
              uint32 ip, char *vhost, char *uid)
{
    User *user = NULL;

    char *tmp = NULL;
    NickAlias *old_na;          /* Old nick rec */
    int nc_changed = 1;         /* Did nick core change? */
    int status = 0;             /* Status to apply */
    char mask[USERMAX + HOSTMAX + 2];
    char *logrealname;
    char *oldnick;

    if (!*source) {
        char ipbuf[16];
        struct in_addr addr;

        if (ircd->nickvhost) {
            if (vhost) {
                if (!strcmp(vhost, "*")) {
                    vhost = NULL;
                    if (debug)
                        alog("debug: new user�with no vhost in NICK command: %s", nick);
                }
            }
        }

        /* This is a new user; create a User structure for it. */
        if (debug)
            alog("debug: new user: %s", nick);

        if (ircd->nickip) {
            addr.s_addr = htonl(ip);
            ntoa(addr, ipbuf, sizeof(ipbuf));
        }


        if (LogUsers) {
        /**
         * Ugly swap routine for Flop's bug :)
         **/
            if (realname) {
                tmp = strchr(realname, '%');
                while (tmp) {
                    *tmp = '-';
                    tmp = strchr(realname, '%');
                }
            }
            logrealname = normalizeBuffer(realname);

        /**
         * End of ugly swap
         **/

            if (ircd->nickvhost) {
                if (ircd->nickip) {
                    alog("LOGUSERS: %s (%s@%s => %s) (%s) [%s] connected to the network (%s).", nick, username, host, (vhost ? vhost : "none"), logrealname, ipbuf, server);
                } else {
                    alog("LOGUSERS: %s (%s@%s => %s) (%s) connected to the network (%s).", nick, username, host, (vhost ? vhost : "none"), logrealname, server);
                }
            } else {
                if (ircd->nickip) {
                    alog("LOGUSERS: %s (%s@%s) (%s) [%s] connected to the network (%s).", nick, username, host, logrealname, ipbuf, server);
                } else {
                    alog("LOGUSERS: %s (%s@%s) (%s) connected to the network (%s).", nick, username, host, logrealname, server);
                }
            }
            Anope_Free(logrealname);
        }

        /* We used to ignore the ~ which a lot of ircd's use to indicate no
         * identd response.  That caused channel bans to break, so now we
         * just take what the server gives us.  People are still encouraged
         * to read the RFCs and stop doing anything to usernames depending
         * on the result of an identd lookup.
         */

        /* First check for AKILLs. */
        /* DONT just return null if its an akill match anymore - yes its more efficent to, however, now that ircd's are
         * starting to use things like E/F lines, we cant be 100% sure the client will be removed from the network :/
         * as such, create a user_struct, and if the client is removed, we'll delete it again when the QUIT notice
         * comes in from the ircd.
         **/
        if (check_akill(nick, username, host, vhost, ipbuf)) {
/*            return NULL; */
        }

/**
 * DefCon AKILL system, if we want to akill all connecting user's here's where to do it
 * then force check_akill again on them...
 **/
        /* don't akill on netmerges -Certus */
        /* don't akill clients introduced by ulines. -Viper */
        if (is_sync(findserver(servlist, server))
            && checkDefCon(DEFCON_AKILL_NEW_CLIENTS) && !is_ulined(server)) {
            strncpy(mask, "*@", 3);
            strncat(mask, host, HOSTMAX);
            alog("DEFCON: adding akill for %s", mask);
            add_akill(NULL, mask, s_OperServ,
                      time(NULL) + dotime(DefConAKILL),
                      DefConAkillReason ? DefConAkillReason :
                      "DEFCON AKILL");
            if (check_akill(nick, username, host, vhost, ipbuf)) {
/*            return NULL; */
            }
        }

        /* SGLINE */
        if (ircd->sgline) {
            if (check_sgline(nick, realname))
                return NULL;
        }

        /* SQLINE */
        if (ircd->sqline) {
            if (check_sqline(nick, 0))
                return NULL;
        }

        /* SZLINE */
        if (ircd->szline && ircd->nickip) {
            if (check_szline(nick, ipbuf))
                return NULL;
        }
        /* Now check for session limits */
        if (LimitSessions && !is_ulined(server)
            && !add_session(nick, host, ipbuf))
            return NULL;

        /* Allocate User structure and fill it in. */
        user = new_user(nick);
        user->username = sstrdup(username);
        user->host = sstrdup(host);
        user->server = findserver(servlist, server);
        user->realname = sstrdup(realname);
        user->timestamp = ts;
        user->my_signon = time(NULL);
        user->chost = vhost ? sstrdup(vhost) : sstrdup(host);
        user->vhost = vhost ? sstrdup(vhost) : sstrdup(host);
        if (uid) {
            user->uid = sstrdup(uid);   /* p10/ts6 stuff */
        } else {
            user->uid = NULL;
        }
        user->vident = sstrdup(username);
        /* We now store the user's ip in the user_ struct,
         * because we will use it in serveral places -- DrStein */
        if (ircd->nickip) {
            user->hostip = sstrdup(ipbuf);
        } else {
            user->hostip = NULL;
        }

        if (svid == 0) {
            display_news(user, NEWS_LOGON);
            display_news(user, NEWS_RANDOM);
        }

        if (svid == 2 && user->na) {
            /* We do not yet know if the user should be identified or not.
             * mark him as recognized for now. 
             * It s up to the protocol module to make sure this either becomes ID'd or
             * is invalidated. ~ Viper */
            if (debug) 
                alog("debug: Marking %s as recognized..", user->nick);
            user->svid = 1;
            user->na->status |= NS_RECOGNIZED;
            nc_changed = 0;
        } else if (svid == ts && user->na) {
            /* Timestamp and svid match, and nick is registered; automagically identify the nick */
            user->svid = svid;
            user->na->status |= NS_IDENTIFIED;
            check_memos(user);
            nc_changed = 0;

            /* Start nick tracking if available */
            if (NSNickTracking)
                nsStartNickTracking(user);

        } else if (svid != 1) {
            /* Resets the svid because it doesn't match */
            user->svid = 1;

            anope_cmd_svid_umode(user->nick, user->timestamp);

        } else {
            user->svid = 1;
        }
        send_event(EVENT_NEWNICK, 1, nick);

    } else {
        /* An old user changing nicks. */
        if (UseTS6 && ircd->ts6)
            user = find_byuid(source);

        if (!user)
            user = finduser(source);

        if (!user) {
            alog("user: NICK from nonexistent nick %s", source);
            return NULL;
        }
        user->isSuperAdmin = 0; /* Dont let people nick change and stay SuperAdmins */
        if (debug)
            alog("debug: %s changes nick to %s", source, nick);

        if (LogUsers) {
            logrealname = normalizeBuffer(user->realname);
            if (ircd->vhost) {
                alog("LOGUSERS: %s (%s@%s => %s) (%s) changed nick to %s (%s).", user->nick, user->username, user->host, (user->vhost ? user->vhost : "(none)"), logrealname, nick, user->server->name);
            } else {
                alog("LOGUSERS: %s (%s@%s) (%s) changed nick to %s (%s).",
                     user->nick, user->username, user->host, logrealname,
                     nick, user->server->name);
            }
            if (logrealname) {
                free(logrealname);
            }
        }

        user->timestamp = ts;

        if (stricmp(nick, user->nick) == 0) {
            /* No need to redo things */
            change_user_nick(user, nick);
            nc_changed = 0;
        } else {
            /* Update this only if nicks aren't the same */
            user->my_signon = time(NULL);

            old_na = user->na;
            if (old_na) {
                if (nick_recognized(user))
                    user->na->last_seen = time(NULL);
                status = old_na->status & NS_TRANSGROUP;
                cancel_user(user);
            }

            oldnick = sstrdup(user->nick);
            change_user_nick(user, nick);

            if ((old_na ? old_na->nc : NULL) ==
                (user->na ? user->na->nc : NULL))
                nc_changed = 0;

            if (!nc_changed && (user->na))
                user->na->status |= status;
            else {
                anope_cmd_nc_change(user);
            }

            send_event(EVENT_CHANGE_NICK, 2, nick, oldnick);
            free(oldnick);
        }

        if (ircd->sqline) {
            if (!is_oper(user) && check_sqline(user->nick, 1))
                return NULL;
        }

    }                           /* if (!*source) */

    /* Check for nick tracking to bypass identification */
    if (NSNickTracking && nsCheckNickTracking(user)) {
        user->na->status |= NS_IDENTIFIED;
        nc_changed = 0;
    }

    if (nc_changed || !nick_recognized(user)) {
        if (validate_user(user))
            check_memos(user);

    } else {
        if (nick_identified(user)) {
            char tsbuf[16];
            user->na->last_seen = time(NULL);

            if (user->na->last_usermask)
                free(user->na->last_usermask);
            user->na->last_usermask =
                smalloc(strlen(common_get_vident(user)) +
                        strlen(common_get_vhost(user)) + 2);
            sprintf(user->na->last_usermask, "%s@%s",
                    common_get_vident(user), common_get_vhost(user));

            snprintf(tsbuf, sizeof(tsbuf), "%lu",
                     (unsigned long int) user->timestamp);
            anope_cmd_svid_umode2(user, tsbuf);

            alog("%s: %s!%s@%s automatically identified for nick %s",
                 s_NickServ, user->nick, user->username,
                 user->host, user->nick);
        }
    }

    /* Bahamut sets -r on every nick changes, so we must test it even if nc_changed == 0 */
    if (ircd->check_nick_id) {
        if (nick_identified(user)) {
            char tsbuf[16];
            snprintf(tsbuf, sizeof(tsbuf), "%lu",
                     (unsigned long int) user->timestamp);
            anope_cmd_svid_umode3(user, tsbuf);
        }
    }

    return user;
}
示例#28
0
文件: main.c 项目: maggu2810/cwiid
void process_plugin(struct plugin *plugin, int mesg_count,
                    union cwiid_mesg mesg[])
{
	static union cwiid_mesg plugin_mesg[CWIID_MAX_MESG_COUNT];
	int plugin_mesg_count = 0;
	int i;
	uint8_t flag;
	uint16_t pressed, released;
	__s32 axis_value;

	for (i=0; i < mesg_count; i++) {
		switch (mesg[i].type) {
		case CWIID_MESG_STATUS:
			flag = CWIID_RPT_STATUS;
			break;
		case CWIID_MESG_BTN:
			flag = CWIID_RPT_BTN;
			break;
		case CWIID_MESG_ACC:
			flag = CWIID_RPT_ACC;
			break;
		case CWIID_MESG_IR:
			flag = CWIID_RPT_IR;
			break;
		case CWIID_MESG_NUNCHUK:
			flag = CWIID_RPT_NUNCHUK;
			break;
		case CWIID_MESG_CLASSIC:
			flag = CWIID_RPT_CLASSIC;
			break;
		default:
			break;
		}
		if (plugin->rpt_mode_flags & flag) {
			/* TODO: copy correct (smaller) message size */
			memcpy(&plugin_mesg[plugin_mesg_count++], &mesg[i], sizeof mesg[i]);
		}
	}

	if (plugin_mesg_count > 0) {
		switch (plugin->type) {
		case PLUGIN_C:
			if (c_plugin_exec(plugin, plugin_mesg_count, plugin_mesg)) {
				return;
			}
			break;
#ifdef HAVE_PYTHON
		case PLUGIN_PYTHON:
			if (py_plugin_exec(plugin, plugin_mesg_count, plugin_mesg)) {
				return;
			}
			break;
#endif
		}

		/* Plugin Button/Key Events */
		pressed = plugin->data->buttons & ~plugin->prev_buttons;
		released = ~plugin->data->buttons & plugin->prev_buttons;
		for (i=0; i < plugin->info->button_count; i++) {
			if (plugin->bmap[i].active) {
				if (pressed & 1<<i) {
					send_event(&conf, EV_KEY, plugin->bmap[i].action, 1);
				}
				else if (released & 1<<i) {
					send_event(&conf, EV_KEY, plugin->bmap[i].action, 0);
				}
			}
		}
		plugin->prev_buttons = plugin->data->buttons;

		/* Plugin Axis Events */
		for (i=0; i < plugin->info->axis_count; i++) {
			if (plugin->amap[i].active && plugin->data->axes &&
			  plugin->data->axes[i].valid) {
				axis_value = plugin->data->axes[i].value;
				if (plugin->amap[i].flags & CONF_INVERT) {
					axis_value = plugin->info->axis_info[i].max +
					             plugin->info->axis_info[i].min - axis_value;
				}
				send_event(&conf, plugin->amap[i].axis_type,
				           plugin->amap[i].action, axis_value);
			}
		}
	}
}
示例#29
0
int do_saregister(User *u)
{
	char *buf, *nick, *pass, *email;
	NickRequest *nr;
	NickAlias *na;
	User *user;

	buf = moduleGetLastBuffer();
	nick = myStrGetToken(buf, ' ', 0);
	pass = myStrGetToken(buf, ' ', 1);
	email = myStrGetToken(buf, ' ', 2);

	if (!email)
	{
		notice_user(s_NickServ, u, "Syntax: \2SAREGISTER \37nick\37 \37password\37 \37email\37");
		notice_lang(s_NickServ, u, MORE_INFO, s_NickServ, "SAREGISTER");
	}
	else if (readonly)
	{
		notice_lang(s_NickServ, u, NICK_REGISTRATION_DISABLED);
	}
	else if ((nr = findrequestnick(nick)))
	{
		notice_lang(s_NickServ, u, NICK_REQUESTED);
	}
	else if (!anope_valid_nick(nick))
	{
		notice_lang(s_NickServ, u, NICK_X_FORBIDDEN, nick);
	}
	else if ((na = findnick(nick)))
	{
		if (na->status & NS_VERBOTEN)
			notice_lang(s_NickServ, u, NICK_CANNOT_BE_REGISTERED, nick);
		else
			notice_lang(s_NickServ, u, NICK_ALREADY_REGISTERED, nick);
	}
	else if (!MailValidate(email))
	{
		notice_lang(s_NickServ, u, MAIL_X_INVALID, email);
	}
	else
	{
		na = makenick(nick);

		if (!na)
		{
			alog("%s: makenick(%s) failed", s_NickServ, u->nick);
			notice_lang(s_NickServ, u, NICK_REGISTRATION_FAILED);
		}
		else
		{
			user = finduser(nick);

			enc_encrypt(pass, strlen(pass), na->nc->pass, PASSMAX - 1);
			na->nc->flags |= NSDefFlags;
			na->nc->memos.memomax = MSMaxMemos;
			if (user)
				na->last_usermask = user->vhost ? sstrdup(user->vhost) : sstrdup(user->host);
			else
				na->last_usermask = sstrdup("*@*");
			if (user)
				na->last_realname = sstrdup(user->realname);
			else
				na->last_realname = sstrdup("unknown");
			na->time_registered = na->last_seen = time(NULL);
			na->nc->language = NSDefLanguage;
			na->nc->email = sstrdup(email);

			send_event(EVENT_NICK_REGISTERED, 1, nick);
			
			alog("%s: %s (%s@%s) used saregister to register %s", s_NickServ, u->nick, u->username, u->host, nick);

			notice_user(s_NickServ, u, "Nick \2%s\2 has been registered", nick);

			if (user)
			{
				user->na = na;
				validate_user(user);
			}
		}
	}

	if (email)
		free(email);
	if (pass)
		free(pass);
	if (nick)
		free(nick);

	return MOD_CONT;
}
示例#30
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	fprintf( stderr, "lsmi-joystick" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME );

	if ( NULL == seq )
	{
		fprintf( stderr, "Error opening alsa sequencer!\n" );
		exit( 1 );
	}

	if ( ( port = open_output_port( seq ) ) < 0 )
	{
		fprintf( stderr, "Error opening MIDI output port!\n" );
		exit( 1 );
	}

	if ( sub_name )
	{
		snd_seq_addr_t addr;

		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}

	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	fprintf( stderr, "Initializing joystick...\n" );

	if ( -1 == ( jfd = open( joydevice, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		clean_up();
		exit(1);
	}

	set_traps();

	fprintf( stderr, "Waiting for events...\n" );

	for ( ;; )
	{
		struct js_event e;
		snd_seq_event_t ev;
		static int b1;
		static int b2;

		read (jfd, &e, sizeof(struct js_event));

		snd_seq_ev_clear( &ev );

		switch (e.type)
		{
			case JS_EVENT_BUTTON:
				switch (e.number)
				{
					case 0:
						if(e.value)
							b1 = 1;
						else
						{
							b1 = 0;
							snd_seq_ev_set_pitchbend( &ev, channel, 0 );

							send_event( &ev );
						}
						break;
					case 1:
						if (e.value)
							b2 = 1;
						else
						{
							b2 = 0;
							snd_seq_ev_set_controller( &ev, channel, 1, 0 );
							send_event( &ev );
							snd_seq_ev_set_controller( &ev, channel, 33, 0 );
							send_event( &ev );
						}
						break;
				}
				break;
			case JS_EVENT_AXIS:
				
				if ( e.number == 1 && ( b1 || nohold ) )
				{
					snd_seq_ev_set_pitchbend( &ev, channel, 0 - (int)((e.value) * ((float)8191/32767) ));

					send_event( &ev );
				}
				else
				if ( ( e.number == 1 && b2 ) ||
					 ( e.number == 0 && ( ( b1 && b2 ) || nohold ) )
				)
				{
					int fine = (int)((0 - e.value) + 32767) * ((float)16383/65534);
					int	course = fine >> 7;
					fine &= 0x7F;

					snd_seq_ev_set_controller( &ev, channel, 1, course );
					send_event( &ev );
					snd_seq_ev_set_controller( &ev, channel, 33, fine );
					send_event( &ev );
				}
				break;

			 default:
				break;
		}

	}