Exemple #1
0
void eRCDeviceDreambox2::handleCode(int rccode)
{
	/*eDebug("eRCDeviceDreambox2::handleCode rccode=%d 0x%x", rccode, rccode);*/
	if (rccode == 0x00FF) /* break code */
	{
		timeout.stop();
		repeattimer.stop();
		timeOut();
		return;
	}
	timeout.start(1500, 1);
	int old = ccode;
	ccode = rccode;
	if ((old != -1) && (((old & 0x7FFF) != (rccode & 0x7FFF)) || !(rccode & 0x8000)))
	{
		repeattimer.stop();
		/*emit*/ input->keyPressed(eRCKey(this, getKeyCode(old&0x7FFF), eRCKey::flagBreak));
	}
	if ((old^rccode)&0x7FFF)
	{
		input->keyPressed(eRCKey(this, getKeyCode(rccode&0x7FFF), 0));
	}
	else if (rccode&0x8000 && !repeattimer.isActive())
	{
		repeattimer.start(getRepeatDelay(), 1);
	}
}
Exemple #2
0
void eRCDeviceDreamboxButton::handleCode(int code)
{
	code = (~code) & 0x7;
	int l = last;
	last = code;
	for (int i = 0; i < 4; i++)
	{
		if ((l & ~code) & (1 << i))
		{
			/*emit*/ input->keyPressed(eRCKey(this, getKeyCode(i), eRCKey::flagBreak));
		}
		else if ((~l & code) & (1 << i))
		{
			/*emit*/ input->keyPressed(eRCKey(this, getKeyCode(i), 0));
		}
	}
	if (code)
	{
		repeattimer.start(getRepeatDelay(), 1);
	}
	else
	{
		repeattimer.stop();
	}
}
Exemple #3
0
size_t HIDKeyboard::press(uint8_t k) {
    uint8_t modifiers;
    
    k = getKeyCode(k, &modifiers);
    
    if (k == 0) {
        if (modifiers == 0) {
            return 0;
        }
    }
    else {
        for (unsigned i = 0; i<HID_KEYBOARD_ROLLOVER; i++) {
            if (keyReport.keys[i] == k) {
                goto SEND;
            }
        }
        for (unsigned i = 0; i<HID_KEYBOARD_ROLLOVER; i++) {
            if (keyReport.keys[i] == 0) {
                keyReport.keys[i] = k;
                goto SEND;
            }
        }
        return 0;
    }

SEND:
    keyReport.modifiers |= modifiers;
    sendReport();
    return 1;
}
Exemple #4
0
void handleSubCmd(struct Key k) {
    uint8_t h =getKeyCode(k.row, k.col, getActiveLayer());
    switch( subcmd )
    {
        case SUB_READ:
            if(h == HID_ESC) {
                printf("\nSubRead terminated");
                setCommandMode(false);
            } else {
                if(idx>=MAXLEN) {
                    idx=0;
                    setCommandMode(false);
                }
                str[idx++]=h;
                printf("\n%2d %d: ",idx,h);
                for(uint8_t i=0; i<idx; ++i)
                    printf("%02x", str[i]);
            }
            break;
        case SUB_LAYOUT:
        {
            // das nŠchste Layout auf die gedrŸckte Spalte setzen, also 12 verschiedene Layouts verfŸgbar
            /*
            Layout nextLayout = k.col < LAYOUTS ? k.col : eeprom_read_byte (&alternateLayoutNr);
            eeprom_write_byte(&alternateLayoutNr, nextLayout);
            PrintConfiguration();
            */
            printf("\nLAYOUTS not yet implemented");
            setCommandMode(false);
            break;
        }
        case SUB_GEOAREA:
        {
            // den geografischen Bereich auf die gedrŸckte Spalte setzen, DE, GB und US verfŸgbar
            GeoArea nextAlternateGeoArea = k.col < 3 ? k.col : eeprom_read_byte (&alternateGeoArea);
            eeprom_write_byte(&alternateGeoArea, nextAlternateGeoArea);
            PrintConfiguration();
            setCommandMode(false);
            break;
        }
        case SUB_PC_MAC:
        {
            // die Hardware auf die gedrŸckte Spalte setzen, PC/Mac verfŸgbar
            MacOrPC  nextAltMacOrPC = k.col < 2 ? k.col : eeprom_read_byte (&altMacOrPC);
            eeprom_write_byte(&altMacOrPC, nextAltMacOrPC);
            PrintConfiguration();
            setCommandMode(false);
            break;
        }
        case SUB_MACRO:
            setMacroMode(true);
            activateMacro(k.row*ROWS+k.col);
            setCommandMode(false);
            break;
        default:
            break;
    }
    clearActiveKeys();
    clearRowData();
}
Exemple #5
0
void eRCDeviceDreambox2::repeat()
{
	if (ccode != -1)
	{
		input->keyPressed(eRCKey(this, getKeyCode(ccode&0x7FFF), eRCKey::flagRepeat));
	}
	repeattimer.start(getRepeatRate(), 1);
}
mir::EventUPtr mia::Lexicon::translate(droidinput::InputEvent const* android_event)
{
    switch(android_event->getType())
    {
        case AINPUT_EVENT_TYPE_KEY:
        {
            auto kev = static_cast<const droidinput::KeyEvent*>(android_event);
            return mev::make_event(MirInputDeviceId(android_event->getDeviceId()),
                                   kev->getEventTime(),
                                   kev->getMac(),
                                   mia::mir_keyboard_action_from_android(kev->getAction(), kev->getRepeatCount()),
                                   kev->getKeyCode(),
                                   kev->getScanCode(),
                                   mia::mir_modifiers_from_android(kev->getMetaState()));
        }
        case AINPUT_EVENT_TYPE_MOTION:
        {
            if (mia::android_source_id_is_pointer_device(android_event->getSource()))
            {
                auto mev = static_cast<const droidinput::MotionEvent*>(android_event);
                return mev::make_event(MirInputDeviceId(android_event->getDeviceId()),
                                       mev->getEventTime(),
                                       mev->getMac(),
                                       mia::mir_modifiers_from_android(mev->getMetaState()),
                                       mia::mir_pointer_action_from_masked_android(mev->getAction() & AMOTION_EVENT_ACTION_MASK),
                                       mia::mir_pointer_buttons_from_android(mev->getButtonState()),
                                       mev->getX(0), mev->getY(0),
                                       mev->getRawAxisValue(AMOTION_EVENT_AXIS_HSCROLL, 0),
                                       mev->getRawAxisValue(AMOTION_EVENT_AXIS_VSCROLL, 0),
                                       mev->getRawAxisValue(AMOTION_EVENT_AXIS_RX, 0),
                                       mev->getRawAxisValue(AMOTION_EVENT_AXIS_RY, 0));
            }
            else
            {
                auto mev = static_cast<const droidinput::MotionEvent*>(android_event);
                auto ev = mev::make_event(MirInputDeviceId(android_event->getDeviceId()),
                                          mev->getEventTime(),
                                          mev->getMac(),
                                          mia::mir_modifiers_from_android(mev->getMetaState()));
                auto action = mev->getAction();
                size_t index_with_action = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
                auto masked_action = action & AMOTION_EVENT_ACTION_MASK;
                for (unsigned i = 0; i < mev->getPointerCount(); i++)
                {
                    auto action = (i == index_with_action) ? mia::mir_touch_action_from_masked_android(masked_action) :
                        mir_touch_action_change;
                    mev::add_touch(*ev, mev->getPointerId(i), action, mia::mir_tool_type_from_android(mev->getToolType(i)),
                        mev->getX(i), mev->getY(i),
                        mev->getPressure(i), mev->getTouchMajor(i),
			mev->getTouchMinor(i), mev->getSize(i));
                }
                return ev;
            }
        }
    default:
        BOOST_THROW_EXCEPTION(std::logic_error("Invalid android event"));
    }
}
Exemple #7
0
/*************************************************
 Function:		keymenu_proc
 Descroption:	 
 Input: 		None
 Output: 
 Return: 	
 Other:  
*************************************************/
static INT8U keyviewmain_proc(void)
{
    INT8U ret = 1;
    PKEYSTATE Key = getKeyCode();
    if(Key != NULL && Key->State == KEY_DOWN)
    {       
    
        switch(Key->Code)
        {
            case KEY_CODE_MENU:                
                GuiBackWindow(GUI_SETTING);
                break;
            
            case KEY_CODE_OK:
                GuiBackWindow(GUI_VIEWPARAM);
                break;

            case KEY_CODE_1:
            case KEY_CODE_3:    
            case KEY_CODE_4:    
            case KEY_CODE_5:
            case KEY_CODE_6:    
            case KEY_CODE_7:
            case KEY_CODE_8:
            case KEY_CODE_9:
                break;                

            case KEY_CODE_UP:
                ChangePageItem(0);
                break;
              
            case KEY_CODE_DOWN:
                ChangePageItem(1);
                break;

            case KEY_CODE_LEFT:
                ChangeItem(0);
                break;
                
            case KEY_CODE_RIGHT:
                ChangeItem(1);
                break;
            
            case KEY_CODE_POWER:
                GuiBackWindow(GUI_SETTING);
                break;
            
            default:
                ret = 0;
                break;
        }
            
    }

    return ret;
}
Exemple #8
0
void eRCDeviceDreambox2::timeOut()
{
	int oldcc = ccode;
	ccode = -1;
	repeattimer.stop();
	if (oldcc != -1)
	{
		input->keyPressed(eRCKey(this, getKeyCode(oldcc&0x7FFF), eRCKey::flagBreak));
	}
}
// Driver to test the reading of the color key codes
int main()
{
	char p1, p2, p3, p4;

	getKeyCode( &p1, &p2, &p3, &p4 );
	printf( "Echo print: %c %c %c %c\n", p1, p2, p3, p4 );

	printKeyCode( p1, p2, p3, p4 );

	return EXIT_SUCCESS;
}
int main()
{
    int gdriver = DETECT, gmode;
    initgraph(&gdriver, &gmode, "");
    setbkcolor(WHITE);

    Point p[4] =
    {
        Point{0,0},
        Point{100,0},
        Point{100,100},
        Point{0,100}
    };
    int ch;
    cleardevice();
    drawAxis(BLACK);
    for(int i = 0; i<4; i++)
    {
        Line l = {p[i], p[(i+1)%4]};
        l.plotLineDDA(RED);
    }
    while((ch = getKeyCode())!=ESC)
    {
        switch(ch)
        {
        case 'A' :
            for(int i = 0; i<4; i++)
            {
                rotateSingle(&p[i], toRadian(10));
            }
            break;
        case 'W' :
            for(int i = 0; i<4; i++)
            {
                translateSingle(&p[i], 10,10);
            }
            break;
        case 'D' :
            for(int i = 0; i<4; i++)
            {
                scaleSingle(&p[i], 1.5, 1.5);
            }
            break;
        }
        cleardevice();
        drawAxis(BLACK);
        for(int i = 0; i<4; i++)
        {
            Line l = {p[i], p[(i+1)%4]};
            l.plotLineDDA(RED);
        }
    }
    return 0;
}
Exemple #11
0
void eRCDeviceDreamboxButton::repeat()
{
	for (int i = 0; i < 4; i++)
	{
		if (last & (1<<i))
		{
			/*emit*/ input->keyPressed(eRCKey(this, getKeyCode(i), eRCKey::flagRepeat));
		}
	}
	repeattimer.start(getRepeatRate(), 1);
}
Exemple #12
0
bool EventPropertyBase::accepts(tgt::Event* e) const {

    if (!isEnabled())
        return false;

    bool accept = false;

    if (tgt::MouseEvent* mouseEvent = dynamic_cast<tgt::MouseEvent*>(e)) {
        accept = receivesMouseEvents();
        accept &= (mouseEvent->modifiers() == getModifier());
        accept &= ((mouseEvent->action() & getMouseAction())  || (mouseEvent->action() == getMouseAction()));
        accept &= ((mouseEvent->button() & getMouseButtons()) || (mouseEvent->button() == getMouseButtons()));
    }
    else if (tgt::KeyEvent* keyEvent = dynamic_cast<tgt::KeyEvent*>(e)) {
        accept = receivesKeyEvents();
        accept &= (keyEvent->modifiers() == getModifier());
        accept &= ((keyEvent->keyCode() == getKeyCode()) || (getKeyCode() == tgt::KeyEvent::K_LAST));
    }

    return accept;
}
Exemple #13
0
/*****************************************************************************
int updateCheckers(size_t _iBoardSize)
    Description :
		Updates and prints the GameBoard.
    Parameters  : 
		size_t _iBoardSize: The size of the board.
    Returns     : 
		TRUE, if everything went well. FALSE, if not.
*****************************************************************************/
int updateCheckers(size_t _iBoardSize)
{
	static Vec2ds16_t cursorPosition = { 0, 0 }; // last cursor coordinates
	static Vec2ds16_t selectedToken = { -1, -1 }; // the selected game token
	short iInput = 0;

	// user input
	iInput = getKeyCode();

	switch(iInput)
	{
	case 13: // ENTER
		selectedToken = cursorPosition;
		break;
	case 256 + 72: // ARROW UP
		if(cursorPosition.iY > 0)
		{
			--cursorPosition.iY;
		}
		break;
	case 256 + 80: // ARROW DOWN
		if((unsigned short)cursorPosition.iY < g_Fields - 1)
		{
			++cursorPosition.iY;
		}
		break;
	case 256 + 75: // ARROW LEFT
		if(cursorPosition.iX > 0)
		{
			--cursorPosition.iX;
		}
		break;
	case 256 + 77: // ARROW RIGHT
		if((unsigned short)cursorPosition.iX < g_Fields - 1)
		{
			++cursorPosition.iX;
		}
		break;
	case 27: // ESCAPE
		// set static variables to default
		selectedToken.iX = selectedToken.iY = -1;
		cursorPosition.iX = cursorPosition.iY = 0;

		// break game loop
		return FALSE;
	}

	// print board
	printGameBoard(g_Board, &g_Offset, &cursorPosition, &selectedToken, g_Fields, g_Fields);

	return TRUE;
}
Exemple #14
0
/**************************************************************************************

  Wait for key pressed and return its ASCII code

  return value:
    ASCII code

**************************************************************************************/
int8_t _getchar()
{
  uint8_t n;
  int8_t c;
  n=getKeyCode();
  if(n<10)c=n+48; // 0..9
  if((n>=11)&&(n<17))c=n+'A'-11; // A..F
  if(n==HASHKEY) c='i'; // increment
  if(n==17)c='r'; // reset
  if(n==18)c='g'; // go
  if(n==19)c='s'; // set address
  return c;
}
Exemple #15
0
void GLUTCanvas::keyboard(const unsigned char& key, const int& x, const int& y, const int& modifier)
{
    // glutKeyrepeat
    // glutKeyUpFunc()

    // maybe there is a GLUTMouse that needs update
    keepMouseUpdated(x, y);

    // get TGT keyCode and modifier
    KeyEvent::KeyCode tgtKey = getKeyCode(key);
    int tgtModifier = getModifier(modifier);

    // TODO: encapsulate this by shift press and release events?
    tgt::KeyEvent* ke_press = new tgt::KeyEvent(tgtKey, tgtModifier, true);
    tgt::KeyEvent* ke_release = new tgt::KeyEvent(tgtKey, tgtModifier, false);
    eventHandler_->broadcast(ke_press);
    eventHandler_->broadcast(ke_release);
}
Exemple #16
0
void AppState::updateKeyInputState() {
    DIDEVICEOBJECTDATA didod[kKeyInputBufferSize]; // Receives buffered data
    KeyInputData data_buff[kKeyInputBufferSize];
    DWORD dwElements = kKeyInputBufferSize;

    dx::throwIfFailed(
        keyboard_device_->GetDeviceState(sizeof(key_input_diks_), key_input_diks_.data())
    );

    HRESULT hr = keyboard_device_->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), didod, &dwElements, 0);
    if (hr == DI_OK) {
        ASSERT(dwElements != 0);
        std::transform(didod, didod + dwElements, data_buff, [this](DIDEVICEOBJECTDATA& d) {
            return KeyInputData {getKeyCode(d.dwOfs) , d.dwData & 0x80};
        });
        KeyboardInput::instance().updateState( { data_buff, data_buff + dwElements });
    } else {
        LOGI(kLogSignWin,"GetDeviceData[%ld]", hr);
    }
}
Exemple #17
0
// release() takes the specified key out of the persistent key report and
// sends the report.  This tells the OS the key is no longer pressed and that
// it shouldn't be repeated any more.
size_t HIDKeyboard::release(uint8_t k)
{
    uint8_t modifiers;
    k = getKeyCode(k, &modifiers);
    
    if (k != 0) {
        for (unsigned i=0; i<HID_KEYBOARD_ROLLOVER; i++) {
             if (keyReport.keys[i] == k) {
                 keyReport.keys[i] = 0;
                 break;
             }
        }
    }
    else {
        if (modifiers == 0)
            return 0;
    }
    
    keyReport.modifiers &= ~modifiers;
    
	sendReport();
	return 1;
}
Exemple #18
0
bool StageLayer::foundListener(Event *e, EventListener *l)
{
    switch (e->getType()) {
    case Event::Type::KEYBOARD:
    {
        auto ev = static_cast<EventKeyboard*>(e);
        auto idx = findEmptyKeySlot();
        if(idx>=0) { //if can't find a slot, just eat it
            keySlots_[idx] = {ev->getKeyCode(), l};
        }
        break;
    }
    case Event::Type::MOUSE:
    {
        auto ev = static_cast<EventMouse*>(e);
        auto idx = (int)ev->getMouseButton();
        mouseSlots_[idx] = l;
        break;
    }
    default:
        break;
    }
    return true;
}
Exemple #19
0
bool KeyEvent::isSystemKey() const {
    return isSystemKey(getKeyCode());
}
Exemple #20
0
bool KeyEvent::hasDefaultAction() const {
    return hasDefaultAction(getKeyCode());
}
Exemple #21
0
/** Called when command mode is active.
 *
 *  First pressed key is mapped to first layer defined and evaluated. Use only a-z and 0-9 for commands, others exit this mode. 
 *
 *  @todo: leave automatically on unknown command or timeout, or signal mode through leds.
 *
 */
void handleCommand(void) {
    if(!commandMode())
        return;

    if(activeKeys.keycnt==0)
        return;

    struct Key k=activeKeys.keys[0];
    
    uint8_t hid = getKeyCode(k.row, k.col, 0);

    if(subcmd) {
        handleSubCmd(k);
        return;
    }
    clearActiveKeys();
    clearRowData();

    // Char with Meaning:
    //  A:ASCIIPrint, B:BootL, C:PrintConfig, G:GeoArea, H:HardwarePC/Mac, L: SwitchLayout, M:Macro, P:PrintLayout, Q:QuitCommand,  T: Trackpoint
    // Char without Meaning:
    //  O:MouseMode, R:PrintKeyHID
    switch(hid) {
        case HID_D:
            g_pinkydrop = !g_pinkydrop;
            printf("\nPinkydrop %d", g_pinkydrop);
            setCommandMode(false);
            break;
        case HID_V:
            printf("\nAdNW %s", FW_VERSION);
            setCommandMode(false);
            break;
        case HID_C:
            PrintConfiguration();
            break;
        case HID_G:
            // G:GeoArea umschalten
            printf("\nG:GeoArea::");
            subcmd=SUB_GEOAREA;
            break;
        case HID_H:
            // HardwarePC/Mac umschalten
            printf("\nHardwarePC/Mac::");
            subcmd=SUB_PC_MAC;
            break;
        case HID_Q:
        case HID_ESC:
            printf("\nLeaving command mode::");
            setCommandMode(false);
            break;
        case HID_B:
            printf("\nBootloader::");
            jump_bootloader();
            break;
        case HID_P:
            // Print Layout: one layer per press on key 'p'
            printLayout(layer);
            layer=(layer+1)%LAYERS;
            if(layer==0)
                setCommandMode(false);
            break;
#ifdef MOUSE_HAS_SCROLL_WHEELS
        case HID_T:
            printf("\nTrackpoint:");
            tp_id();
            setCommandMode(false);
            break;
#endif
        case HID_L:
            g_alternateLayer=!g_alternateLayer;
            printf("\nAlternate layer %s", g_alternateLayer ? "selected." : "off.");
            setCommandMode(false);
            /*
            // Layout umschalten
            printf("\nSwitch layout::");
            subcmd=SUB_LAYOUT;
            */
            break;
        case HID_A:
            for(uint8_t i=32; i<255; ++i) {
                if(i%16==0)
                    printf("\n %03d", i);
                printf("%c ", (char)(i));
                if(i==127)
                    i+=33;
            }
            setCommandMode(false);
            break;
        case HID_M:
            g_mouse_enabled = g_mouse_enabled > 0 ? 0 : 1;
            printf("\nMouse %sabled", g_mouse_enabled ? "en" : "dis");
            setCommandMode(false);
            break;
        case HID_R:
            // print HID code of pressed key
            printf("\nHID code read active.");
            subcmd=SUB_READ;
            idx=0;
            break;
        case HID_X:
            subcmd=SUB_MACRO;
            printf("Macro mode true\n");
            break;
        default:
            printf("\nUnknown command.");
            break;
    }
}
Exemple #22
0
/*************************************************
 Function:		keymain_proc
 Descroption:	 
 Input: 		None
 Output: 
 Return: 	
 Other:  
*************************************************/
static INT8U keytimer_proc(void)
{
    INT8U ret = 0;
    PKEYSTATE Key = getKeyCode();
    if(Key != NULL && Key->State == KEY_DOWN)
    {       
        switch(Key->Code)
        {
            case KEY_CODE_MENU:                
                break;
            
            case KEY_CODE_OK:
                if(mEdit == 1)
                {
                    mEdit = 0;
                }
                else
                {
                    mEdit = 1;
                }
                InvalidateRect(NULL);
                break;

            case KEY_CODE_0:
            case KEY_CODE_1:
            case KEY_CODE_2:    
            case KEY_CODE_3:    
            case KEY_CODE_4:    
            case KEY_CODE_5:
            case KEY_CODE_6:    
            case KEY_CODE_7:
            case KEY_CODE_8:
            case KEY_CODE_9:
                InputItem(Key->Code);
                break;
              
            case KEY_CODE_LEFT:
                if(mEdit == 1)
                {
                    ChangeItem(0);
                }
                break;

            case KEY_CODE_RIGHT:
                if(mEdit == 1)
                {
                    ChangeItem(1);
                }
                break;
            
            case KEY_CODE_POWER:
                SaveParam();
                GuiBackWindow(GUI_SYS_SETTING);
                break;
            
            default:
                
                break;
        }
            
    }

    return ret;
}
bool CGameApplication::eventLoop()
{
    // Déclaration des variables
    static unsigned int time_fps = 0;
    static unsigned int nbr_img = 0;
    bool screenshot = false;
    sf::Event event;

    // Gestion du temps
    unsigned int time = getElapsedTime();
    unsigned int frameTime = time - m_time;
    m_time = time;

    // Boucle évènementielle
    while (m_window->pollEvent(event))
    {
        switch (event.type)
        {
            default:
                break;

            // Bouton Quitter (croix ou Alt-F4)
            case sf::Event::Closed:

                if (m_gameActive)
                {
                    showMouseCursor();
                    m_gameActive = false;
                }

                m_active = false;

                break;

            // Changement de taille de la fenêtre
            case sf::Event::Resized:
            {
                CResizeEvent ev;
                ev.width = event.size.width;
                ev.height = event.size.height;
                onEvent(ev);
                break;
            }

            // Texte provenant du clavier
            case sf::Event::TextEntered:
            {
                CTextEvent ev;
                ev.type = EventText;
                ev.unicode = event.text.unicode;
                onEvent(ev);
                break;
            }

            // Enfoncement d'une touche du clavier
            case sf::Event::KeyPressed:
            {
                switch (event.key.code)
                {
/*
                    // Touche F1 : Console
                    case sf::Keyboard::F1:

                        if (m_gameActive)
                        {
                            m_state = AppConsole;
                            showMouseCursor();
                        }

                        break;
*/
#ifdef T_ACTIVE_DEBUG_MODE

                    // Touche F2 : Debug
                    case sf::Keyboard::F2:

                        if (m_gameActive)
                        {
                            m_activityMenu = Game::guiEngine->getCurrentActivity();
                            Game::guiEngine->setCurrentActivity(m_activityDebug);
                            m_gameActive = false;
                            showMouseCursor();
                        }
                        else if (m_inGame && Game::guiEngine->getCurrentActivity() == m_activityDebug)
                        {
                            Game::guiEngine->setCurrentActivity(m_activityMenu);
                            m_gameActive = true;
                            showMouseCursor(false);
                        }

                        break;

#endif // T_ACTIVE_DEBUG_MODE

/* --------------------------- *
 *    Début du bloc de test    *
 * --------------------------- */

                    // DEBUG : Touche F4 : Quitter
                    case sf::Keyboard::F4:
                        m_active = false;
                        break;

                    // DEBUG : Touche F5 : Capture d'écran
                    case sf::Keyboard::F5:
                        screenshot = true;
                        Game::soundEngine->beep(2000, 100);
                        break;

/* --------------------------- *
*    Fin du bloc de test      *
* --------------------------- */

                    // Touche ÉCHAP : Quitter
                    case sf::Keyboard::Escape:

                        if (m_gameActive)
                        {
                            m_gameActive = false;
                            showMouseCursor();
                            break;
                        }
                        else if (m_inGame)
                        {
                            m_gameActive = true;
                            showMouseCursor(false);

#ifdef T_ACTIVE_DEBUG_MODE
                            if (Game::guiEngine->getCurrentActivity() == m_activityDebug)
                            {
                                Game::guiEngine->setCurrentActivity(m_activityMenu);
                            }
#endif // T_ACTIVE_DEBUG_MODE

                            break;
                        }

                        {
                            CKeyboardEvent ev;

                            ev.type  = KeyPressed;
                            ev.code  = getKeyCode(event.key.code);
                            ev.modif = NoModifier;

                            if (event.key.alt    ) ev.modif |= AltModifier;
                            if (event.key.control) ev.modif |= ControlModifier;
                            if (event.key.shift  ) ev.modif |= ShiftModifier;

                            onEvent(ev);
                        }

                        break;

                    // Autres touches : transmission de l'évènement
                    default:
                    {
                        CKeyboardEvent ev;

                        ev.type  = KeyPressed;
                        ev.code  = getKeyCode(event.key.code);
                        ev.modif = NoModifier;

                        if (event.key.alt    ) ev.modif |= AltModifier;
                        if (event.key.control) ev.modif |= ControlModifier;
                        if (event.key.shift  ) ev.modif |= ShiftModifier;

                        onEvent(ev);
                        break;
                    }
                }

                break;
            }

            // Relachement d'une touche du clavier
            case sf::Event::KeyReleased:
            {
                CKeyboardEvent ev;

                ev.type  = KeyReleased;
                ev.code  = getKeyCode(event.key.code);
                ev.modif = NoModifier;

                if (event.key.alt    ) ev.modif |= AltModifier;
                if (event.key.control) ev.modif |= ControlModifier;
                if (event.key.shift  ) ev.modif |= ShiftModifier;

                onEvent(ev);
                break;
            }

            case sf::Event::MouseButtonPressed:
            {
                CMouseEvent ev;

                ev.type = ButtonPressed;
                ev.x    = event.mouseButton.x;
                ev.y    = event.mouseButton.y;
                ev.xrel = 0;
                ev.yrel = 0;

                switch (event.mouseButton.button)
                {
                    default:
                        ev.button = MouseNoButton;
                        break;

                    case sf::Mouse::Left:
                        ev.button = MouseButtonLeft;
                        break;

                    case sf::Mouse::Right:
                        ev.button = MouseButtonRight;
                        break;

                    case sf::Mouse::Middle:
                        ev.button = MouseButtonMiddle;
                        break;

                    case sf::Mouse::XButton1:
                        ev.button = MouseButtonX1;
                        break;

                    case sf::Mouse::XButton2:
                        ev.button = MouseButtonX2;
                        break;
                }

                onEvent(ev);
                break;
            }

            case sf::Event::MouseButtonReleased:
            {
                CMouseEvent ev;

                ev.type = ButtonReleased;
                ev.x    = event.mouseButton.x;
                ev.y    = event.mouseButton.y;
                ev.xrel = 0;
                ev.yrel = 0;

                switch (event.mouseButton.button)
                {
                    default:
                        ev.button = MouseNoButton;
                        break;

                    case sf::Mouse::Left:
                        ev.button = MouseButtonLeft;
                        break;

                    case sf::Mouse::Right:
                        ev.button = MouseButtonRight;
                        break;

                    case sf::Mouse::Middle:
                        ev.button = MouseButtonMiddle;
                        break;

                    case sf::Mouse::XButton1:
                        ev.button = MouseButtonX1;
                        break;

                    case sf::Mouse::XButton2:
                        ev.button = MouseButtonX2;
                        break;
                }

                onEvent(ev);
                break;
            }

            case sf::Event::MouseWheelMoved:
            {
                CMouseEvent ev;

                ev.type   = MouseWheel;
                ev.x      = event.mouseWheel.x;
                ev.y      = event.mouseWheel.y;
                ev.xrel   = 0;
                ev.yrel   = 0;
                ev.button = (event.mouseWheel.delta > 0 ? MouseWheelUp : MouseWheelDown);

                onEvent(ev);
                break;
            }

            case sf::Event::MouseMoved:
            {
                CMouseEvent ev;

                ev.type   = MoveMouse;
                ev.x      = event.mouseMove.x;
                ev.y      = event.mouseMove.y;
                ev.xrel   = static_cast<int>(event.mouseMove.x) - static_cast<int>(m_cursorPos.X);
                ev.yrel   = static_cast<int>(event.mouseMove.y) - static_cast<int>(m_cursorPos.Y);
                ev.button = MouseNoButton;

                if (m_cursorVisible)
                {
                    m_cursorPos.set(ev.x, ev.y);
                }

                // On place le curseur au centre de l'écran
                if (!m_cursorVisible && (ev.xrel != 0 || ev.yrel != 0))
                {
                    sf::Mouse::setPosition(sf::Vector2i(getWidth() / 2, getHeight() / 2), *m_window);
                }

                onEvent(ev);
                break;
            }

        }
    }

    Game::renderer->beginScene();

    // Affichage de la scène
    if (m_inGame)
    {
        // Animation de la caméra si le jeu est lancé
        if (m_gameActive || m_multiplayer)
        {
            m_gameTime += frameTime;
            Game::renderer->getCamera()->animate(frameTime);

            // MAJ de la simulation physique
            Game::physicEngine->setFrameTime(frameTime);

            if (m_showBullet && m_debugBuffer)
            {
                m_debugBuffer->clear();
                Game::physicEngine->getWorld()->debugDrawWorld();
            }
        }

        // Affichage de la skybox
        Game::renderer->displayScene();

        // Mise-à-jour et affichage des entités
        m_gamedata->update((m_gameActive || m_multiplayer ? frameTime : 0));
        Game::entityManager->frame((m_gameActive || m_multiplayer ? frameTime : 0));

        // Affichage des données du moteur physique
        if (m_showBullet && m_debugBuffer)
        {
            m_debugBuffer->update();
            m_debugBuffer->draw();
        }
    }

    // Changement de map
    if (m_gamedataNew)
    {
        delete m_gamedata;
        m_gamedata = m_gamedataNew;
        m_gamedataNew = nullptr;
    }

    // Blur motion
    Game::renderer->useAccumBuffer(0.2f, 0.8f);

    // Capture d'écran
    if (m_gameActive && screenshot)
    {
        CRenderer::screenShot();
    }

    // Affichage des objets de l'interface graphique
    Game::guiEngine->beginFrame();
    Game::guiEngine->displayFrame();
    Game::guiEngine->endFrame();

    Game::renderer->endScene();

    if (m_window)
    {
        m_window->display();
    }

    // Mise-à-jour des sons
    Game::soundEngine->frame();

    // Mise-à-jour des textures et des buffers graphiques
    Game::textureManager->doPendingTasks();
    Game::renderer->doPendingTasks();

    // Calcul des FPS
    ++nbr_img;

    // À chaque seconde écoulée, on met à jour le compteur de FPS
    if (m_time - time_fps > 1000)
    {
        m_fps = (1000.0f * nbr_img / static_cast<float>(m_time - time_fps));
        nbr_img = 1;
        time_fps = m_time;

#ifdef T_ACTIVE_DEBUG_MODE
        // Enregistrement des dernières mesures de FPS
        m_fpsList.append(m_fps);
#endif // T_ACTIVE_DEBUG_MODE
    }

#ifdef T_ACTIVE_DEBUG_MODE
        // Enregistrement de la durée de chaque frame
        m_frameTimeList.append(frameTime);
#endif // T_ACTIVE_DEBUG_MODE

    return m_active;
}
InputDeviceAdapterMouse::InputDeviceAdapterMouse(InputDeviceManager* sInputDeviceManager,const Misc::ConfigurationFileSection& configFileSection)
    :InputDeviceAdapter(sInputDeviceManager),
     numButtons(0),
     numButtonKeys(0),buttonKeyCodes(0),
     numModifierKeys(0),modifierKeyCodes(0),
     numButtonStates(0),
     keyboardModeToggleKeyCode(0),controlKeyMap(101),
     modifierKeyMask(0x0),buttonStates(0),numPressedButtons(0),
     keyboardMode(false),
     numMouseWheelTicks(0),
     nextEventOrdinal(0),
     window(0),
     grabWindow(0),
     mouseLocked(false),
     fakeMouseCursor(false)
{
    typedef std::vector<std::string> StringList;

    /* Allocate new adapter state arrays: */
    numInputDevices=1;
    inputDevices=new InputDevice*[numInputDevices];
    inputDevices[0]=0;

    /* Retrieve the number of mouse buttons: */
    numButtons=configFileSection.retrieveValue<int>("./numButtons",0);

    /* Retrieve button key list: */
    StringList buttonKeyNames=configFileSection.retrieveValue<StringList>("./buttonKeys",StringList());
    numButtonKeys=buttonKeyNames.size();
    if(numButtonKeys>0)
    {
        /* Get key codes for all button keys: */
        buttonKeyCodes=new int[numButtonKeys];
        for(int i=0; i<numButtonKeys; ++i)
            buttonKeyCodes[i]=getKeyCode(buttonKeyNames[i]);
    }

    /* Retrieve modifier key list: */
    StringList modifierKeyNames=configFileSection.retrieveValue<StringList>("./modifierKeys",StringList());
    numModifierKeys=modifierKeyNames.size();
    if(numModifierKeys>0)
    {
        /* Get key codes for all modifier keys: */
        modifierKeyCodes=new int[numModifierKeys];
        for(int i=0; i<numModifierKeys; ++i)
            modifierKeyCodes[i]=getKeyCode(modifierKeyNames[i]);
    }

    /* Calculate number of buttons and valuators: */
    numButtonStates=(numButtons+numButtonKeys)*(1<<numModifierKeys);
    int numValuators=1<<numModifierKeys;

    /* Create new input device: */
    InputDevice* newDevice=inputDeviceManager->createInputDevice("Mouse",InputDevice::TRACK_POS|InputDevice::TRACK_DIR,numButtonStates,numValuators,true);

    /* Store the input device: */
    inputDevices[0]=newDevice;

    /* Retrieve the keyboard toggle key code: */
    keyboardModeToggleKeyCode=getKeyCode(configFileSection.retrieveValue<std::string>("./keyboardModeToggleKey","F1"));

    /* Create the control key map: */
    const int controlKeyMapSize=sizeof(rawControlKeyMap)/sizeof(ControlKeyMapItem);
    for(int i=0; i<controlKeyMapSize; ++i)
        controlKeyMap.setEntry(ControlKeyMap::Entry(rawControlKeyMap[i].ck,rawControlKeyMap[i].tce));

    /* Initialize button and valuator states: */
    buttonStates=new bool[numButtonStates];
    for(int i=0; i<numButtonStates; ++i)
        buttonStates[i]=false;
    numMouseWheelTicks=new int[numValuators];
    for(int i=0; i<numValuators; ++i)
        numMouseWheelTicks[i]=0;

    /* Initialize the mouse position: */
    mousePos[0]=mousePos[1]=0;

    /* Check if this adapter is supposed to draw a fake mouse cursor: */
    fakeMouseCursor=configFileSection.retrieveValue<bool>("./fakeMouseCursor",fakeMouseCursor);
    if(fakeMouseCursor)
    {
        /* Enable the device's glyph as a cursor: */
        Glyph& deviceGlyph=inputDeviceManager->getInputGraphManager()->getInputDeviceGlyph(newDevice);
        deviceGlyph.enable();
        deviceGlyph.setGlyphType(Glyph::CURSOR);
    }
}
Exemple #25
0
CApplication::CApplication(const CString& title) :
IEventReceiver    (),
m_time            (0),
m_inGame          (false),
m_gameActive      (false),
m_active          (true),
m_fps             (50.0f),
m_window          (nullptr),
m_cursorPos       (Origin2US),
m_gameTime        (0),
m_cursorVisible   (true),
m_frameTimeList   (100),
m_fpsList         (100),

#ifndef T_NO_DEFAULT_LOGGER
m_defaultLogger   (nullptr),
#endif // T_NO_DEFAULT_LOGGER

m_receiver        (nullptr),
m_title           (title/*"TEngine Application"*/),
m_videoMode       (800, 600, 32),
m_fullscreen      (false)
{
    if (m_instance)
        exit(-1);

    m_instance = this;

    // Création du logger par défaut
#ifndef T_NO_DEFAULT_LOGGER
    m_defaultLogger = new CLoggerFile(CDateTime::getCurrentDateTime().toString("logs/log-%Y-%m-%d-%H-%i-%s.txt"));
    T_ASSERT(m_defaultLogger != nullptr);
    addLogger(m_defaultLogger);
#endif // T_NO_DEFAULT_LOGGER

    log("Chargement du moteur");

    // Lecture des paramètres
    m_settings.loadFromFile("../../config.ini");

    // Initialisation de l'état des boutons de la souris
    m_buttons[MouseButtonLeft]   = false;
    m_buttons[MouseButtonRight]  = false;
    m_buttons[MouseButtonMiddle] = false;
    m_buttons[MouseWheelUp]      = false;
    m_buttons[MouseWheelDown]    = false;

    // Touches par défaut
    m_keyActions[ActionForward]     = getKeyCode(m_settings.getValue("Keys", "forward"    , "Key_Z"));
    m_keyActions[ActionBackward]    = getKeyCode(m_settings.getValue("Keys", "backward"   , "Key_S"));
    m_keyActions[ActionStrafeLeft]  = getKeyCode(m_settings.getValue("Keys", "strafeleft" , "Key_Q"));
    m_keyActions[ActionStrafeRight] = getKeyCode(m_settings.getValue("Keys", "straferight", "Key_D"));
    m_keyActions[ActionTurnLeft]    = getKeyCode(m_settings.getValue("Keys", "turnleft"   , "Key_Left"));
    m_keyActions[ActionTurnRight]   = getKeyCode(m_settings.getValue("Keys", "turnright"  , "Key_Right"));
    m_keyActions[ActionJump]        = getKeyCode(m_settings.getValue("Keys", "jump"       , "Key_Space"));
    m_keyActions[ActionCrunch]      = getKeyCode(m_settings.getValue("Keys", "crunch"     , "Key_LShift"));
    m_keyActions[ActionZoom]        = getKeyCode(m_settings.getValue("Keys", "zoom"       , "Key_G"));

    m_window = new sf::Window();
    T_ASSERT(m_window != nullptr);
    m_window->setMouseCursorVisible(false);
}
Exemple #26
0
bool CApplication::eventLoop()
{
    // Déclaration des variables
    static unsigned int time_fps = 0;
    static unsigned int nbr_img = 0;
    sf::Event event;

    // Gestion du temps
    unsigned int time = getElapsedTime();
    unsigned int frameTime = time - m_time;
    m_time = time;

    // Boucle évènementielle
    while (m_window->pollEvent(event))
    {
        switch (event.type)
        {
            default:
                break;

            // Bouton Quitter (croix ou Alt-F4)
            case sf::Event::Closed:

                if (m_gameActive)
                {
                    showMouseCursor();
                    m_gameActive = false;
                }

                break;

            // Changement de taille de la fenêtre
            case sf::Event::Resized:
            {
                CResizeEvent ev;
                ev.width = event.size.width;
                ev.height = event.size.height;
                onEvent(ev);
                break;
            }

            // Texte provenant du clavier
            case sf::Event::TextEntered:
            {
                CTextEvent ev;
                ev.type = EventText;
                ev.unicode = event.text.unicode;
                onEvent(ev);
                break;
            }

            // Enfoncement d'une touche du clavier
            case sf::Event::KeyPressed:
            {
                CKeyboardEvent ev;

                ev.type  = KeyPressed;
                ev.code  = getKeyCode(event.key.code);
                ev.modif = NoModifier;

                if (event.key.alt    ) ev.modif |= AltModifier;
                if (event.key.control) ev.modif |= ControlModifier;
                if (event.key.shift  ) ev.modif |= ShiftModifier;

                onEvent(ev);
                break;
            }

            // Relachement d'une touche du clavier
            case sf::Event::KeyReleased:
            {
                CKeyboardEvent ev;

                ev.type  = KeyReleased;
                ev.code  = getKeyCode(event.key.code);
                ev.modif = NoModifier;

                if (event.key.alt    ) ev.modif |= AltModifier;
                if (event.key.control) ev.modif |= ControlModifier;
                if (event.key.shift  ) ev.modif |= ShiftModifier;

                onEvent(ev);
                break;
            }

            case sf::Event::MouseButtonPressed:
            {
                CMouseEvent ev;

                ev.type = ButtonPressed;
                ev.x    = event.mouseButton.x;
                ev.y    = event.mouseButton.y;
                ev.xrel = static_cast<int>(event.mouseMove.x) - static_cast<int>(m_cursorPos.X);
                ev.yrel = static_cast<int>(event.mouseMove.y) - static_cast<int>(m_cursorPos.Y);

                switch (event.mouseButton.button)
                {
                    default:
                        ev.button = MouseNoButton;
                        break;

                    case sf::Mouse::Left:
                        ev.button = MouseButtonLeft;
                        break;

                    case sf::Mouse::Right:
                        ev.button = MouseButtonRight;
                        break;

                    case sf::Mouse::Middle:
                        ev.button = MouseButtonMiddle;
                        break;

                    case sf::Mouse::XButton1:
                        ev.button = MouseButtonX1;
                        break;

                    case sf::Mouse::XButton2:
                        ev.button = MouseButtonX2;
                        break;
                }

                m_cursorPos.set(ev.x, ev.y);

                // On place le curseur au centre de l'écran
                if (!m_cursorVisible && (ev.xrel != 0 || ev.yrel != 0))
                {
                    sf::Mouse::setPosition(sf::Vector2i(getWidth() / 2, getHeight() / 2), *m_window);
                }

                onEvent(ev);
                break;
            }

            case sf::Event::MouseButtonReleased:
            {
                CMouseEvent ev;

                ev.type = ButtonReleased;
                ev.x    = event.mouseButton.x;
                ev.y    = event.mouseButton.y;
                ev.xrel = static_cast<int>(event.mouseMove.x) - static_cast<int>(m_cursorPos.X);
                ev.yrel = static_cast<int>(event.mouseMove.y) - static_cast<int>(m_cursorPos.Y);

                switch (event.mouseButton.button)
                {
                    default:
                        ev.button = MouseNoButton;
                        break;

                    case sf::Mouse::Left:
                        ev.button = MouseButtonLeft;
                        break;

                    case sf::Mouse::Right:
                        ev.button = MouseButtonRight;
                        break;

                    case sf::Mouse::Middle:
                        ev.button = MouseButtonMiddle;
                        break;

                    case sf::Mouse::XButton1:
                        ev.button = MouseButtonX1;
                        break;

                    case sf::Mouse::XButton2:
                        ev.button = MouseButtonX2;
                        break;
                }

                m_cursorPos.set(ev.x, ev.y);

                // On place le curseur au centre de l'écran
                if (!m_cursorVisible && (ev.xrel != 0 || ev.yrel != 0))
                {
                    sf::Mouse::setPosition(sf::Vector2i(getWidth() / 2, getHeight() / 2), *m_window);
                }

                onEvent(ev);
                break;
            }

            case sf::Event::MouseWheelMoved:
            {
                CMouseEvent ev;

                ev.type   = MouseWheel;
                ev.x      = event.mouseWheel.x;
                ev.y      = event.mouseWheel.y;
                ev.xrel   = static_cast<int>(event.mouseMove.x) - static_cast<int>(m_cursorPos.X);
                ev.yrel   = static_cast<int>(event.mouseMove.y) - static_cast<int>(m_cursorPos.Y);
                ev.button = (event.mouseWheel.delta > 0 ? MouseWheelUp : MouseWheelDown);

                m_cursorPos.set(ev.x, ev.y);

                // On place le curseur au centre de l'écran
                if (!m_cursorVisible && (ev.xrel != 0 || ev.yrel != 0))
                {
                    sf::Mouse::setPosition(sf::Vector2i(getWidth() / 2, getHeight() / 2 ), *m_window);
                }

                onEvent(ev);
                break;
            }

            case sf::Event::MouseMoved:
            {
                CMouseEvent ev;

                ev.type   = MoveMouse;
                ev.x      = event.mouseMove.x;
                ev.y      = event.mouseMove.y;
                ev.xrel   = static_cast<int>(event.mouseMove.x) - static_cast<int>(m_cursorPos.X);
                ev.yrel   = static_cast<int>(event.mouseMove.y) - static_cast<int>(m_cursorPos.Y);
                ev.button = MouseNoButton;

                if (m_cursorVisible)
                {
                    m_cursorPos.set(ev.x, ev.y);
                }

                // On place le curseur au centre de l'écran
                if (!m_cursorVisible && (ev.xrel != 0 || ev.yrel != 0))
                {
                    sf::Mouse::setPosition(sf::Vector2i(getWidth() / 2, getHeight() / 2), *m_window);
                }

                onEvent(ev);
                break;
            }

        }
    }

    if (m_window)
    {
        m_window->display();
    }

    // Calcul des FPS
    ++nbr_img;

    // À chaque seconde écoulée, on met à jour le compteur de FPS
    if (m_time - time_fps > 1000)
    {
        m_fps = (1000.0f * nbr_img / static_cast<float>(m_time - time_fps));
        nbr_img = 1;
        time_fps = m_time;

#ifdef T_ACTIVE_DEBUG_MODE
        // Enregistrement des dernières mesures de FPS
        m_fpsList.append(m_fps);
#endif // T_ACTIVE_DEBUG_MODE
    }

#ifdef T_ACTIVE_DEBUG_MODE
        // Enregistrement de la durée de chaque frame
        m_frameTimeList.append(frameTime);
#endif // T_ACTIVE_DEBUG_MODE

    return m_active;
}
Exemple #27
0
/** Called when command mode is active.
 *
 *  First pressed key is mapped to first layer defined and evaluated. Use only a-z and 0-9 for commands, others exit this mode. 
 *
 *  @todo: leave automatically on unknown command or timeout, or signal mode through leds.
 *
 */
void handleCommand(void) {
    if(!commandMode())
        return;

    if(activeKeys.keycnt==0)
        return;

    struct Key k=activeKeys.keys[0];
    
    uint8_t hid = getKeyCode(k.row, k.col, 0);

    if(subcmd) {
        handleSubCmd(k);
        return;
    }
    clearActiveKeys();
    clearRowData();

    // Char with Meaning:
    //  A:ASCIIPrint, B:BootL, C:PrintConfig, G:GeoArea, H:HardwarePC/Mac, L: SwitchLayout, M:Macro, P:PrintLayout, Q:QuitCommand,  T: Trackpoint
    // Char without Meaning:
    //  O:MouseMode, R:PrintKeyHID
    switch(hid) {
#ifdef PINKYDROP
        case HID_D:
            g_pinkydrop = g_pinkydrop ? 0 : 1;
            printf("\nPinkydrop %d", g_pinkydrop);
            eeprom_write_byte(&ee_pinkyDrop, g_pinkydrop);
            setCommandMode(false);
            break;
#endif
        case HID_V:
            printf("\nAdNW %s", FW_VERSION);
            setCommandMode(false);
            break;
        case HID_Q:
        case HID_ESC:
            printf("\nLeaving command mode::");
            setCommandMode(false);
            break;
        case HID_B:
            printf("\nBootloader::");
            jump_bootloader();
            break;
/*
        case HID_P:
            // Print Layout: one layer per press on key 'p'
            printLayout(layer);
            layer=(layer+1)%LAYERS;
            if(layer==0)
                setCommandMode(false);
            break;
*/
#ifdef MOUSE_HAS_SCROLL_WHEELS
        case HID_T:
            printf("\nTrackpoint:");
            tp_id();
            setCommandMode(false);
            break;
#endif
        case HID_L:
            g_alternateLayer = g_alternateLayer ? 0 : 1;
            eeprom_write_byte(&ee_alternateLayer,g_alternateLayer);
            printf("\nAlternate layer %s", g_alternateLayer ? "selected." : "off.");
            setCommandMode(false);
            break;
#ifdef PS2MOUSE
        case HID_M:
            g_mouse_enabled = g_mouse_enabled > 0 ? 0 : 1;
            printf("\nMouse %sabled", g_mouse_enabled ? "en" : "dis");
            setCommandMode(false);
            break;
#endif
        case HID_X:
            subcmd=SUB_MACRO;
            printf("Macro mode true\n");
            break;
        case HID_R:
            printf("Macro recording\n");
            subcmd=SUB_MACRO_REC;
            break;
        case HID_H:
            subcmd=SUB_PASSHASH;
            break;
        default:
            printf("\nUnknown command.");
            break;
    }
}
Exemple #28
0
QStringList Preferences::getKeyCodeList() const {
  QStringList output;
  for (int i = 0; i < defaultKeyCodes.size(); i++)
    output << getKeyCode((KeyFinder::key_t)i);
  return output;
}
Exemple #29
0
map<set<ushort>, map<Event, string>> loadKeybindings(string strFile) {
	jxx::Array arr;
	map<set<ushort>, map<Event, string>> mapKeybindings;
	stringstream ssContent;
	ifstream is(strFile);
	bool bValidJson;

	ssContent << is.rdbuf();

	bValidJson = arr.parse(ssContent.str());

	fatal_error(!bValidJson, "invalid json");

	for(int i = 0, nLen = arr.size();
		i < nLen;
		i++) {
		if(arr.has<jxx::Object>(i)) {
			map<string, jxx::Value*> mapKV = arr.get<jxx::Object>(i).kv_map();
			set<ushort> setKeys;
			map<Event, string> mapEvents;

			if(mapKV.find(JXX_KEY_KEYS) == mapKV.end()
				|| !mapKV[JXX_KEY_KEYS]->is<jxx::Array>()) {
				// always required
				cout << "Error["<<i<<":depth 2]: keys missing / wrong type"<<endl;
			}
			else {
				jxx::Array arrKeys = mapKV[JXX_KEY_KEYS]->get<jxx::Array>();

				for(int j = 0, nLen2 = arrKeys.size();
					j < nLen2;
					j++) {

					if(arrKeys.has<jxx::Number>(j)) {
						setKeys.insert(static_cast<ushort>(arrKeys.get<jxx::Number>(j)));
					}
					else if(arrKeys.has<string>(j)) {
						string strKey = arrKeys.get<string>(j);
						KeyCode kc = getKeyCode(strKey);

						if(kc == KEY_UNKNOWN) {
							cout<< "Error["<<i<<":depth 3]: keys item unknown key "<<strKey<<endl;
						}
						else {
							setKeys.insert(kc);
						}
					}
					else {
						cout << "Error["<<i<<":depth 3]: keys item wrong type"<<endl;
					}
				}
			}

			for_each(mapKV.begin(), mapKV.end(), [&i, &mapEvents](pair<string, jxx::Value*> pair) {
				string strKey = pair.first;
				jxx::Value* value = pair.second;
				Event event = getEvent(strKey);

				if(strKey != JXX_KEY_KEYS) {
					if(strKey == JXX_KEY_REPEAT) {
						// repeat on long pressing
						if(!value->is<bool>()) {
							cout << "Error["<<i<<":depth 2]: invalid value "<<strKey<<endl;
						}
						else if(value->get<bool>()) {
							// value doesn't matter
							mapEvents[EVENT_PRESS_LONG_REPEAT] = "true";
						}
					}
					else if(event == EVENT_UNKNOWN) {
						// spelling mistake?
						cout << "Error["<<i<<":depth 2]: unknown event "<<strKey<<endl;
					}
					else if(contains(mapEvents, event)) {
						// duplicated key - event already added
						cout << "Error["<<i<<":depth 2]: duplicated event "<<strKey<<endl;
					}
					else {
						if(!value->is<string>()) {
							// value != type string -> we expected a command
							cout << "Error["<<i<<":depth 2]: invalid value event "<<strKey<<endl;
						}
						else {
							mapEvents[event] = value->get<string>();
						}
					}
				}
			});

			if(contains(mapEvents, EVENT_PRESS_LONG_REPEAT)
				&& !contains(mapEvents, EVENT_PRESS_LONG)
				&& contains(mapEvents, EVENT_PRESS)) {
				// repeat enabled - no long press command
				// -> use press command
				mapEvents[EVENT_PRESS_LONG] = mapEvents[EVENT_PRESS];
			}

			if(!setKeys.empty() && !mapEvents.empty()) {
				mapKeybindings[setKeys] = mapEvents;
			}
		}
		else {
			cout << "Error[depth 1]: object expected" << endl;
		}
	}

	return mapKeybindings;
}