Willy-JL 2 yıl önce
ebeveyn
işleme
9329c66b56
100 değiştirilmiş dosya ile 5050 ekleme ve 5059 silme
  1. 2 0
      .gitignore
  2. 49 74
      atomicdiceroller/flipper_atomicdiceroller.c
  3. 347 282
      blackjack/blackjack.c
  4. 165 145
      blackjack/common/card.c
  5. 43 28
      blackjack/common/card.h
  6. 10 17
      blackjack/common/dml.c
  7. 3 3
      blackjack/common/dml.h
  8. 52 38
      blackjack/common/menu.c
  9. 15 14
      blackjack/common/menu.h
  10. 29 26
      blackjack/common/queue.c
  11. 21 15
      blackjack/common/queue.h
  12. 110 69
      blackjack/common/ui.c
  13. 75 28
      blackjack/common/ui.h
  14. 2 3
      blackjack/defines.h
  15. 79 73
      blackjack/ui.c
  16. 8 8
      blackjack/ui.h
  17. 26 26
      blackjack/util.c
  18. 20 17
      bomberduck/bomberduck.c
  19. 21 9
      brainfuck/brainfuck.c
  20. 0 1
      brainfuck/brainfuck_i.h
  21. 0 1
      brainfuck/scenes/brainfuck_scene_dev.c
  22. 5 9
      brainfuck/scenes/brainfuck_scene_file_create.c
  23. 2 3
      brainfuck/scenes/brainfuck_scene_file_select.c
  24. 4 8
      brainfuck/scenes/brainfuck_scene_set_input.c
  25. 11 5
      brainfuck/scenes/brainfuck_scene_start.c
  26. 152 144
      brainfuck/views/bf_dev_env.c
  27. 1 4
      brainfuck/views/bf_dev_env.h
  28. 127 93
      brainfuck/worker.c
  29. 102 101
      caesarcipher/caesar_cipher.c
  30. 0 1
      cli_bridge/console_output.c
  31. 2 1
      cli_bridge/text_input.c
  32. 1 1
      cntdown_timer/utils/utils.h
  33. 8 8
      esubghz_chat/bgloader_api.h
  34. 251 294
      esubghz_chat/crypto/aes.c
  35. 24 25
      esubghz_chat/crypto/aes.h
  36. 196 191
      esubghz_chat/crypto/gcm.c
  37. 60 66
      esubghz_chat/crypto/gcm.h
  38. 167 159
      esubghz_chat/crypto_wrapper.c
  39. 28 25
      esubghz_chat/crypto_wrapper.h
  40. 622 689
      esubghz_chat/esubghz_chat.c
  41. 81 81
      esubghz_chat/esubghz_chat_i.h
  42. 9 9
      esubghz_chat/helpers/nfc_helpers.h
  43. 46 52
      esubghz_chat/scenes/esubghz_chat_chat_box.c
  44. 76 87
      esubghz_chat/scenes/esubghz_chat_chat_input.c
  45. 85 102
      esubghz_chat/scenes/esubghz_chat_freq_input.c
  46. 59 68
      esubghz_chat/scenes/esubghz_chat_hex_key_input.c
  47. 133 116
      esubghz_chat/scenes/esubghz_chat_key_display.c
  48. 140 162
      esubghz_chat/scenes/esubghz_chat_key_menu.c
  49. 231 261
      esubghz_chat/scenes/esubghz_chat_key_read_popup.c
  50. 87 103
      esubghz_chat/scenes/esubghz_chat_key_share_popup.c
  51. 78 94
      esubghz_chat/scenes/esubghz_chat_pass_input.c
  52. 2 2
      esubghz_chat/scenes/esubghz_chat_scene.h
  53. 116 120
      evil_portal/evil_portal_app.c
  54. 37 38
      evil_portal/evil_portal_app_i.h
  55. 5 5
      evil_portal/evil_portal_custom_event.h
  56. 119 121
      evil_portal/evil_portal_uart.c
  57. 5 5
      evil_portal/evil_portal_uart.h
  58. 134 136
      evil_portal/helpers/evil_portal_storage.c
  59. 8 5
      evil_portal/helpers/evil_portal_storage.h
  60. 3 4
      evil_portal/scenes/evil_portal_scene.c
  61. 5 7
      evil_portal/scenes/evil_portal_scene.h
  62. 136 148
      evil_portal/scenes/evil_portal_scene_console_output.c
  63. 27 28
      evil_portal/scenes/evil_portal_scene_rename.c
  64. 36 39
      evil_portal/scenes/evil_portal_scene_select_html.c
  65. 92 132
      evil_portal/scenes/evil_portal_scene_start.c
  66. 3 3
      flipbip/flipbip.c
  67. 1 3
      flipbip/flipbip.h
  68. 48 56
      game15/game15.c
  69. 13 16
      game15/sandbox.c
  70. 148 125
      geiger/flipper_geiger.c
  71. 56 35
      gpio_reader_a/GPIO_reader.c
  72. 4 3
      gpio_reader_a/GPIO_reader_item.c
  73. 1 1
      gpio_reader_a/application.fam
  74. 1 1
      gpio_reader_b/gpio_item.c
  75. 1 1
      gpio_reader_b/scenes/gpio_scene_start.c
  76. 14 18
      gpio_reader_b/views/gpio_reader.c
  77. 4 1
      gpio_reader_b/views/gpio_reader.h
  78. 0 3
      hex_editor/hex_editor.c
  79. 0 1
      magspoof/helpers/mag_types.h
  80. 4 5
      magspoof/mag_device.c
  81. 1 2
      magspoof/mag_i.h
  82. 0 1
      magspoof/scenes/mag_scene_read.h
  83. 3 3
      mass_storage/scenes/mass_storage_scene_start.c
  84. 45 43
      mayhem_camera/camera.c
  85. 29 10
      mayhem_camera/camera.h
  86. 2 2
      mayhem_marauder/scenes/wifi_marauder_scene_user_input.c
  87. 7 8
      mayhem_marauder/script/menu/wifi_marauder_script_stage_menu_sniffpmkid.c
  88. 5 6
      mayhem_marauder/script/wifi_marauder_script.c
  89. 4 6
      mayhem_marauder/script/wifi_marauder_script_executor.c
  90. 0 1
      mayhem_marauder/script/wifi_marauder_script_worker.c
  91. 3 2
      mayhem_morseflash/scenes/uart_terminal_scene_console_output.c
  92. 8 1
      mayhem_morseflash/scenes/uart_terminal_scene_start.c
  93. 5 6
      mayhem_morseflash/uart_terminal_app.c
  94. 2 2
      mayhem_morseflash/uart_terminal_uart.c
  95. 3 4
      mayhem_motion/uart_echo.c
  96. 2 3
      mayhem_nannycam/uart_echo.c
  97. 2 3
      mayhem_qrcode/uart_echo.c
  98. 21 29
      mifare_fuzzer/mifare_fuzzer.c
  99. 0 2
      mifare_fuzzer/mifare_fuzzer_i.h
  100. 20 24
      mifare_fuzzer/mifare_fuzzer_worker.c

+ 2 - 0
.gitignore

@@ -1 +1,3 @@
 .vscode/
+venv/
+.clang-format

+ 49 - 74
atomicdiceroller/flipper_atomicdiceroller.c

@@ -38,8 +38,7 @@ typedef struct {
     uint8_t pause;
 } mutexStruct;
 
-static void draw_callback(Canvas* canvas, void* ctx) 
-{
+static void draw_callback(Canvas* canvas, void* ctx) {
     mutexStruct* mutexVal = ctx;
     mutexStruct mutexDraw;
     furi_mutex_acquire(mutexVal->mutex, FuriWaitForever);
@@ -54,19 +53,19 @@ static void draw_callback(Canvas* canvas, void* ctx)
     snprintf(buffer, sizeof(buffer), "%lu/64", mutexDraw.diceAvailiable);
     canvas_draw_str_aligned(canvas, SCREEN_SIZE_X, 10, AlignRight, AlignBottom, buffer);
 
-    if (mutexDraw.method == 0) canvas_draw_str_aligned(canvas, 0, 20, AlignLeft, AlignBottom, "Hash: CRC32");
-    else canvas_draw_str_aligned(canvas, 0, 20, AlignLeft, AlignBottom, "Hash: MD5");
+    if(mutexDraw.method == 0)
+        canvas_draw_str_aligned(canvas, 0, 20, AlignLeft, AlignBottom, "Hash: CRC32");
+    else
+        canvas_draw_str_aligned(canvas, 0, 20, AlignLeft, AlignBottom, "Hash: MD5");
 
-    if (mutexDraw.dice != 0 && mutexDraw.pause == 0)
-    {
+    if(mutexDraw.dice != 0 && mutexDraw.pause == 0) {
         canvas_set_font(canvas, FontBigNumbers);
         snprintf(buffer, sizeof(buffer), "%u", mutexDraw.dice);
-        canvas_draw_str_aligned(canvas, SCREEN_SIZE_X/2, 50, AlignCenter, AlignBottom, buffer);
+        canvas_draw_str_aligned(canvas, SCREEN_SIZE_X / 2, 50, AlignCenter, AlignBottom, buffer);
     }
 }
 
-static void input_callback(InputEvent* input_event, void* ctx) 
-{
+static void input_callback(InputEvent* input_event, void* ctx) {
     furi_assert(ctx);
     FuriMessageQueue* event_queue = ctx;
     EventApp event = {.type = EventTypeInput, .input = *input_event};
@@ -96,8 +95,7 @@ static void gpiocallback(void* ctx) {
     furi_message_queue_put(queue, &event, 0);
 }
 
-int32_t flipper_atomicdiceroller_app() 
-{
+int32_t flipper_atomicdiceroller_app() {
     furi_hal_bus_enable(FuriHalBusTIM2);
     LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP);
     LL_TIM_SetClockDivision(TIM2, LL_TIM_CLOCKDIVISION_DIV1);
@@ -118,7 +116,7 @@ int32_t flipper_atomicdiceroller_app()
     mutexVal.method = 0;
     uint32_t counter = 0;
 
-    mutexVal.mutex= furi_mutex_alloc(FuriMutexTypeNormal);
+    mutexVal.mutex = furi_mutex_alloc(FuriMutexTypeNormal);
     if(!mutexVal.mutex) {
         furi_message_queue_free(event_queue);
         return 255;
@@ -145,7 +143,7 @@ int32_t flipper_atomicdiceroller_app()
         furi_delay_ms(10);
     }
     uint8_t diceBuffer[64];
-    for (uint8_t i=0;i<64;i++) diceBuffer[i] = 0;
+    for(uint8_t i = 0; i < 64; i++) diceBuffer[i] = 0;
 
     uint8_t diceBufferCounter = 0;
     uint8_t diceBufferPositionWrite = 0;
@@ -162,44 +160,35 @@ int32_t flipper_atomicdiceroller_app()
 
     uint8_t pause = 0;
 
-    while(1) 
-    {
+    while(1) {
         FuriStatus event_status = furi_message_queue_get(event_queue, &event, FuriWaitForever);
-        
+
         uint8_t screenRefresh = 0;
 
-        if (event_status == FuriStatusOk)
-        {   
-            if(event.type == EventTypeInput) 
-            {
-                if(event.input.key == InputKeyBack && event.input.type == InputTypeLong) 
-                {
+        if(event_status == FuriStatusOk) {
+            if(event.type == EventTypeInput) {
+                if(event.input.key == InputKeyBack && event.input.type == InputTypeLong) {
                     break;
-                }
-                else if (pause == 0)
-                {
-                    if (event.input.key == InputKeyOk  && event.input.type == InputTypeShort)
-                    {
-                        if (diceBufferCounter > 0)
-                        {
+                } else if(pause == 0) {
+                    if(event.input.key == InputKeyOk && event.input.type == InputTypeShort) {
+                        if(diceBufferCounter > 0) {
                             furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
                             mutexVal.dice = diceBuffer[diceBufferPositionRead];
                             mutexVal.diceAvailiable = --diceBufferCounter;
                             mutexVal.pause = 1;
                             furi_mutex_release(mutexVal.mutex);
 
-                            if (diceBufferPositionRead != 63) diceBufferPositionRead++;
-                            else diceBufferPositionRead = 0;
+                            if(diceBufferPositionRead != 63)
+                                diceBufferPositionRead++;
+                            else
+                                diceBufferPositionRead = 0;
 
                             pause = 1;
                             furi_timer_start(timerPause, 500);
                             screenRefresh = 1;
                         }
-                    }
-                    else if (event.input.key == InputKeyLeft  && event.input.type == InputTypeLong)
-                    {
-                        if (method == 1)
-                        {
+                    } else if(event.input.key == InputKeyLeft && event.input.type == InputTypeLong) {
+                        if(method == 1) {
                             method = 0;
                             diceBufferPositionWrite = 0;
                             diceBufferPositionRead = 0;
@@ -213,11 +202,8 @@ int32_t flipper_atomicdiceroller_app()
                             furi_mutex_release(mutexVal.mutex);
                             screenRefresh = 1;
                         }
-                    }
-                    else if (event.input.key == InputKeyRight && event.input.type == InputTypeLong)
-                    {
-                        if (method == 0)
-                        {
+                    } else if(event.input.key == InputKeyRight && event.input.type == InputTypeLong) {
+                        if(method == 0) {
                             method = 1;
                             diceBufferPositionWrite = 0;
                             diceBufferPositionRead = 0;
@@ -233,18 +219,14 @@ int32_t flipper_atomicdiceroller_app()
                         }
                     }
                 }
-            }
-            else if (event.type == ClockEventTypeTick)
-            {
+            } else if(event.type == ClockEventTypeTick) {
                 furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
                 mutexVal.cps = counter;
                 furi_mutex_release(mutexVal.mutex);
 
                 counter = 0;
                 screenRefresh = 1;
-            }
-            else if (event.type == ClockEventTypeTickPause)
-            {
+            } else if(event.type == ClockEventTypeTickPause) {
                 furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
                 mutexVal.pause = 0;
                 furi_mutex_release(mutexVal.mutex);
@@ -253,14 +235,10 @@ int32_t flipper_atomicdiceroller_app()
 
                 pause = 0;
                 screenRefresh = 1;
-            }
-            else if (event.type == EventGPIO)
-            {
-                if (diceBufferCounter < 64)
-                {
+            } else if(event.type == EventGPIO) {
+                if(diceBufferCounter < 64) {
                     // CRC32
-                    if (method == 0)
-                    {
+                    if(method == 0) {
                         uint32_t TIM2Tick = TIM2->CNT;
                         bufferTim2[0] = (uint8_t)(TIM2Tick >> 24);
                         bufferTim2[1] = (uint8_t)(TIM2Tick >> 16);
@@ -269,21 +247,20 @@ int32_t flipper_atomicdiceroller_app()
                         CRC32 = crc32_calc_buffer(CRC32, bufferTim2, 4);
                         tickCounter++;
 
-                        if (tickCounter == 8)
-                        {
+                        if(tickCounter == 8) {
                             uint8_t localDice = CRC32 & 0b111;
 
-                            if (localDice == 0 || localDice == 7)
-                            {
+                            if(localDice == 0 || localDice == 7) {
                                 localDice = (diceBuffer[diceBufferPositionRead] >> 3) & 0b111;
                             }
 
-                            if (localDice >= 1 && localDice <= 6)
-                            {
+                            if(localDice >= 1 && localDice <= 6) {
                                 diceBuffer[diceBufferPositionWrite] = localDice;
                                 diceBufferCounter++;
-                                if (diceBufferPositionWrite != 63) diceBufferPositionWrite++;
-                                else diceBufferPositionWrite = 0;
+                                if(diceBufferPositionWrite != 63)
+                                    diceBufferPositionWrite++;
+                                else
+                                    diceBufferPositionWrite = 0;
 
                                 furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
                                 mutexVal.diceAvailiable = diceBufferCounter;
@@ -297,8 +274,7 @@ int32_t flipper_atomicdiceroller_app()
                         }
                     }
                     // MD5
-                    else
-                    {
+                    else {
                         uint32_t tick = TIM2->CNT;
                         bufferTim2[0] = (uint8_t)(tick >> 24);
                         bufferTim2[1] = (uint8_t)(tick >> 16);
@@ -308,20 +284,19 @@ int32_t flipper_atomicdiceroller_app()
 
                         tickCounter++;
 
-                        if (tickCounter == 32)
-                        {
+                        if(tickCounter == 32) {
                             md5_finish(md5_ctx, hash);
                             uint8_t localDice = 0;
 
-                            for (uint8_t i=0;i<16;i++)
-                            {
+                            for(uint8_t i = 0; i < 16; i++) {
                                 localDice = hash[i] & 0b111;
-                                if (localDice >= 1 && localDice <= 6)
-                                {
+                                if(localDice >= 1 && localDice <= 6) {
                                     diceBuffer[diceBufferPositionWrite] = localDice;
                                     diceBufferCounter++;
-                                    if (diceBufferPositionWrite != 63) diceBufferPositionWrite++;
-                                    else diceBufferPositionWrite = 0;
+                                    if(diceBufferPositionWrite != 63)
+                                        diceBufferPositionWrite++;
+                                    else
+                                        diceBufferPositionWrite = 0;
 
                                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
                                     mutexVal.diceAvailiable = diceBufferCounter;
@@ -342,7 +317,7 @@ int32_t flipper_atomicdiceroller_app()
             }
         }
 
-        if (screenRefresh == 1) view_port_update(view_port);
+        if(screenRefresh == 1) view_port_update(view_port);
     }
 
     LL_TIM_DisableCounter(TIM2);
@@ -351,7 +326,7 @@ int32_t flipper_atomicdiceroller_app()
     free(md5_ctx);
     free(bufferTim2);
     free(hash);
-        
+
     furi_record_close(RECORD_NOTIFICATION);
 
     // Disable 5v power

+ 347 - 282
blackjack/blackjack.c

@@ -18,47 +18,46 @@
 
 #define DEALER_MAX 17
 
-void start_round(GameState *game_state);
+void start_round(GameState* game_state);
 
-void init(GameState *game_state);
-
-static void draw_ui(Canvas *const canvas, const GameState *game_state) {
+void init(GameState* game_state);
 
+static void draw_ui(Canvas* const canvas, const GameState* game_state) {
     draw_money(canvas, game_state->player_score);
 
     draw_score(canvas, true, hand_count(game_state->player_cards, game_state->player_card_count));
 
-    if (!game_state->queue_state.running && game_state->state == GameStatePlay) {
-        render_menu(game_state->menu,canvas, 2, 47);
+    if(!game_state->queue_state.running && game_state->state == GameStatePlay) {
+        render_menu(game_state->menu, canvas, 2, 47);
     }
 }
 
-static void render_callback(Canvas *const canvas, void *ctx) {
-    const GameState *game_state = ctx;
+static void render_callback(Canvas* const canvas, void* ctx) {
+    const GameState* game_state = ctx;
     furi_mutex_acquire(game_state->mutex, 25);
 
-    if (game_state == NULL) {
+    if(game_state == NULL) {
         return;
     }
 
     canvas_set_color(canvas, ColorBlack);
     canvas_draw_frame(canvas, 0, 0, 128, 64);
 
-    if (game_state->state == GameStateStart) {
+    if(game_state->state == GameStateStart) {
         canvas_draw_icon(canvas, 0, 0, &I_blackjack);
     }
-    if (game_state->state == GameStateGameOver) {
+    if(game_state->state == GameStateGameOver) {
         canvas_draw_icon(canvas, 0, 0, &I_endscreen);
     }
 
-    if (game_state->state == GameStatePlay || game_state->state == GameStateDealer) {
-        if (game_state->state == GameStatePlay)
+    if(game_state->state == GameStatePlay || game_state->state == GameStateDealer) {
+        if(game_state->state == GameStatePlay)
             draw_player_scene(canvas, game_state);
         else
             draw_dealer_scene(canvas, game_state);
         render_queue(&(game_state->queue_state), game_state, canvas);
         draw_ui(canvas, game_state);
-    } else if (game_state->state == GameStateSettings) {
+    } else if(game_state->state == GameStateSettings) {
         settings_page(canvas, game_state);
     }
 
@@ -66,25 +65,24 @@ static void render_callback(Canvas *const canvas, void *ctx) {
 }
 
 //region card draw
-Card draw_card(GameState *game_state) {
+Card draw_card(GameState* game_state) {
     Card c = game_state->deck.cards[game_state->deck.index];
     game_state->deck.index++;
     return c;
 }
 
-
-void drawPlayerCard(void *ctx) {
-    GameState *game_state = ctx;
+void drawPlayerCard(void* ctx) {
+    GameState* game_state = ctx;
     Card c = draw_card(game_state);
     game_state->player_cards[game_state->player_card_count] = c;
     game_state->player_card_count++;
-    if(game_state->player_score < game_state->settings.round_price || game_state->doubled){
+    if(game_state->player_score < game_state->settings.round_price || game_state->doubled) {
         set_menu_state(game_state->menu, 0, false);
     }
 }
 
-void drawDealerCard(void *ctx) {
-    GameState *game_state = ctx;
+void drawDealerCard(void* ctx) {
+    GameState* game_state = ctx;
     Card c = draw_card(game_state);
     game_state->dealer_cards[game_state->dealer_card_count] = c;
     game_state->dealer_card_count++;
@@ -92,318 +90,362 @@ void drawDealerCard(void *ctx) {
 //endregion
 
 //region queue callbacks
-void to_lose_state(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_lose_state(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "You lost");
 }
 
-void to_bust_state(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_bust_state(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "Busted!");
 }
 
-void to_draw_state(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_draw_state(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "Draw");
 }
 
-void to_dealer_turn(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_dealer_turn(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "Dealers turn");
 }
 
-void to_win_state(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_win_state(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "You win");
 }
 
-void to_start(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
-    if (game_state->settings.message_duration == 0)
-        return;
+void to_start(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
+    if(game_state->settings.message_duration == 0) return;
     popup_frame(canvas);
     elements_multiline_text_aligned(canvas, 64, 22, AlignCenter, AlignCenter, "Round started");
 }
 
-void before_start(void *ctx) {
-    GameState *game_state = ctx;
+void before_start(void* ctx) {
+    GameState* game_state = ctx;
     game_state->dealer_card_count = 0;
     game_state->player_card_count = 0;
 }
 
-
-void start(void *ctx) {
-    GameState *game_state = ctx;
+void start(void* ctx) {
+    GameState* game_state = ctx;
     start_round(game_state);
 }
 
-void draw(void *ctx) {
-    GameState *game_state = ctx;
+void draw(void* ctx) {
+    GameState* game_state = ctx;
     game_state->player_score += game_state->bet;
     game_state->bet = 0;
-    enqueue(&(game_state->queue_state), game_state, start, before_start, to_start,
-            game_state->settings.message_duration);
+    enqueue(
+        &(game_state->queue_state),
+        game_state,
+        start,
+        before_start,
+        to_start,
+        game_state->settings.message_duration);
 }
 
-void game_over(void *ctx) {
-    GameState *game_state = ctx;
+void game_over(void* ctx) {
+    GameState* game_state = ctx;
     game_state->state = GameStateGameOver;
 }
 
-void lose(void *ctx) {
-    GameState *game_state = ctx;
+void lose(void* ctx) {
+    GameState* game_state = ctx;
     game_state->state = GameStatePlay;
     game_state->bet = 0;
-    if (game_state->player_score >= game_state->settings.round_price) {
-        enqueue(&(game_state->queue_state), game_state, start, before_start, to_start,
-                game_state->settings.message_duration);
+    if(game_state->player_score >= game_state->settings.round_price) {
+        enqueue(
+            &(game_state->queue_state),
+            game_state,
+            start,
+            before_start,
+            to_start,
+            game_state->settings.message_duration);
     } else {
-        enqueue(&(game_state->queue_state), game_state, game_over, NULL, NULL,
-                0);
+        enqueue(&(game_state->queue_state), game_state, game_over, NULL, NULL, 0);
     }
 }
 
-void win(void *ctx) {
+void win(void* ctx) {
     dolphin_deed(DolphinDeedPluginGameWin);
-    GameState *game_state = ctx;
+    GameState* game_state = ctx;
     game_state->state = GameStatePlay;
     game_state->player_score += game_state->bet * 2;
     game_state->bet = 0;
-    enqueue(&(game_state->queue_state), game_state, start, before_start, to_start,
-            game_state->settings.message_duration);
+    enqueue(
+        &(game_state->queue_state),
+        game_state,
+        start,
+        before_start,
+        to_start,
+        game_state->settings.message_duration);
 }
 
-
-void dealerTurn(void *ctx) {
-    GameState *game_state = ctx;
+void dealerTurn(void* ctx) {
+    GameState* game_state = ctx;
     game_state->state = GameStateDealer;
 }
 
-float animationTime(const GameState *game_state){
-    return (float) (furi_get_tick() - game_state->queue_state.start) /
-           (float) (game_state->settings.animation_duration);
+float animationTime(const GameState* game_state) {
+    return (float)(furi_get_tick() - game_state->queue_state.start) /
+           (float)(game_state->settings.animation_duration);
 }
 
-void dealer_card_animation(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
+void dealer_card_animation(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
     float t = animationTime(game_state);
 
     Card animatingCard = game_state->deck.cards[game_state->deck.index];
-    if (game_state->dealer_card_count > 1) {
+    if(game_state->dealer_card_count > 1) {
         Vector end = card_pos_at_index(game_state->dealer_card_count);
-        draw_card_animation(animatingCard,
-                            (Vector) {0, 64},
-                            (Vector) {0, 32},
-                            end,
-                            t,
-                            true,
-                            canvas);
+        draw_card_animation(animatingCard, (Vector){0, 64}, (Vector){0, 32}, end, t, true, canvas);
     } else {
-        draw_card_animation(animatingCard,
-                            (Vector) {32, -CARD_HEIGHT},
-                            (Vector) {64, 32},
-                            (Vector) {2, 2},
-                            t,
-                            false,
-                            canvas);
+        draw_card_animation(
+            animatingCard,
+            (Vector){32, -CARD_HEIGHT},
+            (Vector){64, 32},
+            (Vector){2, 2},
+            t,
+            false,
+            canvas);
     }
 }
 
-void dealer_back_card_animation(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
+void dealer_back_card_animation(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
     float t = animationTime(game_state);
 
-    Vector currentPos = quadratic_2d((Vector) {32, -CARD_HEIGHT}, (Vector) {64, 32}, (Vector) {13, 5}, t);
+    Vector currentPos =
+        quadratic_2d((Vector){32, -CARD_HEIGHT}, (Vector){64, 32}, (Vector){13, 5}, t);
     draw_card_back_at(currentPos.x, currentPos.y, canvas);
 }
 
-void player_card_animation(const void *ctx, Canvas *const canvas) {
-    const GameState *game_state = ctx;
+void player_card_animation(const void* ctx, Canvas* const canvas) {
+    const GameState* game_state = ctx;
     float t = animationTime(game_state);
 
     Card animatingCard = game_state->deck.cards[game_state->deck.index];
     Vector end = card_pos_at_index(game_state->player_card_count);
 
-    draw_card_animation(animatingCard,
-                        (Vector) {32, -CARD_HEIGHT},
-                        (Vector) {0, 32},
-                        end,
-                        t,
-                        true,
-                        canvas);
+    draw_card_animation(
+        animatingCard, (Vector){32, -CARD_HEIGHT}, (Vector){0, 32}, end, t, true, canvas);
 }
 //endregion
 
-void player_tick(GameState *game_state) {
+void player_tick(GameState* game_state) {
     uint8_t score = hand_count(game_state->player_cards, game_state->player_card_count);
-    if ((game_state->doubled && score <= 21) || score == 21) {
-        enqueue(&(game_state->queue_state), game_state, dealerTurn, NULL, to_dealer_turn,
-                game_state->settings.message_duration);
-    } else if (score > 21) {
-        enqueue(&(game_state->queue_state), game_state, lose, NULL, to_bust_state,
-                game_state->settings.message_duration);
+    if((game_state->doubled && score <= 21) || score == 21) {
+        enqueue(
+            &(game_state->queue_state),
+            game_state,
+            dealerTurn,
+            NULL,
+            to_dealer_turn,
+            game_state->settings.message_duration);
+    } else if(score > 21) {
+        enqueue(
+            &(game_state->queue_state),
+            game_state,
+            lose,
+            NULL,
+            to_bust_state,
+            game_state->settings.message_duration);
     } else {
-        if(game_state->selectDirection == DirectionUp || game_state->selectDirection == DirectionDown){
+        if(game_state->selectDirection == DirectionUp ||
+           game_state->selectDirection == DirectionDown) {
             move_menu(game_state->menu, game_state->selectDirection == DirectionUp ? -1 : 1);
         }
 
-        if (game_state->selectDirection == Select){
+        if(game_state->selectDirection == Select) {
             activate_menu(game_state->menu, game_state);
-
         }
     }
 }
 
-void dealer_tick(GameState *game_state) {
+void dealer_tick(GameState* game_state) {
     uint8_t dealer_score = hand_count(game_state->dealer_cards, game_state->dealer_card_count);
     uint8_t player_score = hand_count(game_state->player_cards, game_state->player_card_count);
 
-    if (dealer_score >= DEALER_MAX) {
-        if (dealer_score > 21 || dealer_score < player_score) {
-            enqueue(&(game_state->queue_state), game_state, win, NULL, to_win_state,
-                    game_state->settings.message_duration);
-        } else if (dealer_score > player_score) {
-            enqueue(&(game_state->queue_state), game_state, lose, NULL, to_lose_state,
-                    game_state->settings.message_duration);
-        } else if (dealer_score == player_score) {
-            enqueue(&(game_state->queue_state), game_state, draw, NULL, to_draw_state,
-                    game_state->settings.message_duration);
+    if(dealer_score >= DEALER_MAX) {
+        if(dealer_score > 21 || dealer_score < player_score) {
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                win,
+                NULL,
+                to_win_state,
+                game_state->settings.message_duration);
+        } else if(dealer_score > player_score) {
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                lose,
+                NULL,
+                to_lose_state,
+                game_state->settings.message_duration);
+        } else if(dealer_score == player_score) {
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                draw,
+                NULL,
+                to_draw_state,
+                game_state->settings.message_duration);
         }
     } else {
-        enqueue(&(game_state->queue_state), game_state, drawDealerCard, NULL, dealer_card_animation,
-                game_state->settings.animation_duration);
+        enqueue(
+            &(game_state->queue_state),
+            game_state,
+            drawDealerCard,
+            NULL,
+            dealer_card_animation,
+            game_state->settings.animation_duration);
     }
 }
 
-void settings_tick(GameState *game_state) {
-    if (game_state->selectDirection == DirectionDown && game_state->selectedMenu < 4) {
+void settings_tick(GameState* game_state) {
+    if(game_state->selectDirection == DirectionDown && game_state->selectedMenu < 4) {
         game_state->selectedMenu++;
     }
-    if (game_state->selectDirection == DirectionUp && game_state->selectedMenu > 0) {
+    if(game_state->selectDirection == DirectionUp && game_state->selectedMenu > 0) {
         game_state->selectedMenu--;
     }
 
-    if (game_state->selectDirection == DirectionLeft || game_state->selectDirection == DirectionRight) {
+    if(game_state->selectDirection == DirectionLeft ||
+       game_state->selectDirection == DirectionRight) {
         int nextScore = 0;
-        switch (game_state->selectedMenu) {
-            case 0:
-                nextScore = game_state->settings.starting_money;
-                if (game_state->selectDirection == DirectionLeft)
-                    nextScore -= 10;
-                else
-                    nextScore += 10;
-                if (nextScore >= (int) game_state->settings.round_price && nextScore < 400)
-                    game_state->settings.starting_money = nextScore;
-                break;
-            case 1:
-                nextScore = game_state->settings.round_price;
-                if (game_state->selectDirection == DirectionLeft)
-                    nextScore -= 10;
-                else
-                    nextScore += 10;
-                if (nextScore >= 5 && nextScore <= (int) game_state->settings.starting_money)
-                    game_state->settings.round_price = nextScore;
-                break;
-            case 2:
-                nextScore = game_state->settings.animation_duration;
-                if (game_state->selectDirection == DirectionLeft)
-                    nextScore -= 100;
-                else
-                    nextScore += 100;
-                if (nextScore >= 0 && nextScore < 2000)
-                    game_state->settings.animation_duration = nextScore;
-                break;
-            case 3:
-                nextScore = game_state->settings.message_duration;
-                if (game_state->selectDirection == DirectionLeft)
-                    nextScore -= 100;
-                else
-                    nextScore += 100;
-                if (nextScore >= 0 && nextScore < 2000)
-                    game_state->settings.message_duration = nextScore;
-                break;
-            case 4:
-                game_state->settings.sound_effects = !game_state->settings.sound_effects;
-            default:
-                break;
+        switch(game_state->selectedMenu) {
+        case 0:
+            nextScore = game_state->settings.starting_money;
+            if(game_state->selectDirection == DirectionLeft)
+                nextScore -= 10;
+            else
+                nextScore += 10;
+            if(nextScore >= (int)game_state->settings.round_price && nextScore < 400)
+                game_state->settings.starting_money = nextScore;
+            break;
+        case 1:
+            nextScore = game_state->settings.round_price;
+            if(game_state->selectDirection == DirectionLeft)
+                nextScore -= 10;
+            else
+                nextScore += 10;
+            if(nextScore >= 5 && nextScore <= (int)game_state->settings.starting_money)
+                game_state->settings.round_price = nextScore;
+            break;
+        case 2:
+            nextScore = game_state->settings.animation_duration;
+            if(game_state->selectDirection == DirectionLeft)
+                nextScore -= 100;
+            else
+                nextScore += 100;
+            if(nextScore >= 0 && nextScore < 2000)
+                game_state->settings.animation_duration = nextScore;
+            break;
+        case 3:
+            nextScore = game_state->settings.message_duration;
+            if(game_state->selectDirection == DirectionLeft)
+                nextScore -= 100;
+            else
+                nextScore += 100;
+            if(nextScore >= 0 && nextScore < 2000)
+                game_state->settings.message_duration = nextScore;
+            break;
+        case 4:
+            game_state->settings.sound_effects = !game_state->settings.sound_effects;
+        default:
+            break;
         }
     }
-
 }
 
-void tick(GameState *game_state) {
+void tick(GameState* game_state) {
     game_state->last_tick = furi_get_tick();
     bool queue_ran = run_queue(&(game_state->queue_state), game_state);
 
-    switch (game_state->state) {
-        case GameStateGameOver:
-        case GameStateStart:
-            if (game_state->selectDirection == Select)
-                init(game_state);
-            else if (game_state->selectDirection == DirectionRight) {
-                game_state->selectedMenu = 0;
-                game_state->state = GameStateSettings;
-            }
-            break;
-        case GameStatePlay:
-            if (!game_state->started) {
-                game_state->selectedMenu = 0;
-                game_state->started = true;
-                enqueue(&(game_state->queue_state), game_state, drawDealerCard, NULL, dealer_back_card_animation,
-                        game_state->settings.animation_duration);
-                enqueue(&(game_state->queue_state), game_state, drawPlayerCard, NULL, player_card_animation,
-                        game_state->settings.animation_duration);
-                enqueue(&(game_state->queue_state), game_state, drawDealerCard, NULL, dealer_card_animation,
-                        game_state->settings.animation_duration);
-                enqueue(&(game_state->queue_state), game_state, drawPlayerCard, NULL, player_card_animation,
-                        game_state->settings.animation_duration);
-            }
-            if (!queue_ran)
-                player_tick(game_state);
-            break;
-        case GameStateDealer:
-            if (!queue_ran)
-                dealer_tick(game_state);
-            break;
-        case GameStateSettings:
-            settings_tick(game_state);
-            break;
-        default:
-            break;
+    switch(game_state->state) {
+    case GameStateGameOver:
+    case GameStateStart:
+        if(game_state->selectDirection == Select)
+            init(game_state);
+        else if(game_state->selectDirection == DirectionRight) {
+            game_state->selectedMenu = 0;
+            game_state->state = GameStateSettings;
+        }
+        break;
+    case GameStatePlay:
+        if(!game_state->started) {
+            game_state->selectedMenu = 0;
+            game_state->started = true;
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                drawDealerCard,
+                NULL,
+                dealer_back_card_animation,
+                game_state->settings.animation_duration);
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                drawPlayerCard,
+                NULL,
+                player_card_animation,
+                game_state->settings.animation_duration);
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                drawDealerCard,
+                NULL,
+                dealer_card_animation,
+                game_state->settings.animation_duration);
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                drawPlayerCard,
+                NULL,
+                player_card_animation,
+                game_state->settings.animation_duration);
+        }
+        if(!queue_ran) player_tick(game_state);
+        break;
+    case GameStateDealer:
+        if(!queue_ran) dealer_tick(game_state);
+        break;
+    case GameStateSettings:
+        settings_tick(game_state);
+        break;
+    default:
+        break;
     }
 
     game_state->selectDirection = None;
-
 }
 
-void start_round(GameState *game_state) {
-    game_state->menu->current_menu=1;
+void start_round(GameState* game_state) {
+    game_state->menu->current_menu = 1;
     game_state->player_card_count = 0;
     game_state->dealer_card_count = 0;
     set_menu_state(game_state->menu, 0, true);
-    game_state->menu->enabled=true;
+    game_state->menu->enabled = true;
     game_state->started = false;
     game_state->doubled = false;
     game_state->queue_state.running = true;
     shuffle_deck(&(game_state->deck));
     game_state->doubled = false;
     game_state->bet = game_state->settings.round_price;
-    if (game_state->player_score < game_state->settings.round_price) {
+    if(game_state->player_score < game_state->settings.round_price) {
         game_state->state = GameStateGameOver;
     } else {
         game_state->player_score -= game_state->settings.round_price;
@@ -411,10 +453,10 @@ void start_round(GameState *game_state) {
     game_state->state = GameStatePlay;
 }
 
-void init(GameState *game_state) {
+void init(GameState* game_state) {
     set_menu_state(game_state->menu, 0, true);
-    game_state->menu->enabled=true;
-    game_state->menu->current_menu=1;
+    game_state->menu->enabled = true;
+    game_state->menu->current_menu = 1;
     game_state->settings = load_settings();
     game_state->last_tick = 0;
     game_state->processing = true;
@@ -424,60 +466,86 @@ void init(GameState *game_state) {
     start_round(game_state);
 }
 
-static void input_callback(InputEvent *input_event, FuriMessageQueue *event_queue) {
+static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
     furi_assert(event_queue);
     AppEvent event = {.type = EventTypeKey, .input = *input_event};
     furi_message_queue_put(event_queue, &event, FuriWaitForever);
 }
 
-static void update_timer_callback(FuriMessageQueue *event_queue) {
+static void update_timer_callback(FuriMessageQueue* event_queue) {
     furi_assert(event_queue);
     AppEvent event = {.type = EventTypeTick};
     furi_message_queue_put(event_queue, &event, 0);
 }
 
-void doubleAction(void *state){
-    GameState *game_state = state;
-    if (!game_state->doubled &&  game_state->player_score >= game_state->settings.round_price) {
+void doubleAction(void* state) {
+    GameState* game_state = state;
+    if(!game_state->doubled && game_state->player_score >= game_state->settings.round_price) {
         game_state->player_score -= game_state->settings.round_price;
         game_state->bet += game_state->settings.round_price;
         game_state->doubled = true;
-        enqueue(&(game_state->queue_state), game_state, drawPlayerCard, NULL, player_card_animation,
-                game_state->settings.animation_duration);
-        game_state->player_cards[game_state->player_card_count] = game_state->deck.cards[game_state->deck.index];
+        enqueue(
+            &(game_state->queue_state),
+            game_state,
+            drawPlayerCard,
+            NULL,
+            player_card_animation,
+            game_state->settings.animation_duration);
+        game_state->player_cards[game_state->player_card_count] =
+            game_state->deck.cards[game_state->deck.index];
         uint8_t score = hand_count(game_state->player_cards, game_state->player_card_count + 1);
-        if (score > 21) {
-            enqueue(&(game_state->queue_state), game_state, lose, NULL, to_bust_state,
-                    game_state->settings.message_duration);
+        if(score > 21) {
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                lose,
+                NULL,
+                to_bust_state,
+                game_state->settings.message_duration);
         } else {
-            enqueue(&(game_state->queue_state), game_state, dealerTurn, NULL, to_dealer_turn,
-                    game_state->settings.message_duration);
+            enqueue(
+                &(game_state->queue_state),
+                game_state,
+                dealerTurn,
+                NULL,
+                to_dealer_turn,
+                game_state->settings.message_duration);
         }
         set_menu_state(game_state->menu, 0, false);
     }
 }
 
-void hitAction(void *state){
-    GameState *game_state = state;
-    enqueue(&(game_state->queue_state), game_state, drawPlayerCard, NULL, player_card_animation,
-            game_state->settings.animation_duration);
-}
-void stayAction(void *state){
-    GameState *game_state = state;
-    enqueue(&(game_state->queue_state), game_state, dealerTurn, NULL, to_dealer_turn,
-            game_state->settings.message_duration);
-}
-
-int32_t blackjack_app(void *p) {
+void hitAction(void* state) {
+    GameState* game_state = state;
+    enqueue(
+        &(game_state->queue_state),
+        game_state,
+        drawPlayerCard,
+        NULL,
+        player_card_animation,
+        game_state->settings.animation_duration);
+}
+void stayAction(void* state) {
+    GameState* game_state = state;
+    enqueue(
+        &(game_state->queue_state),
+        game_state,
+        dealerTurn,
+        NULL,
+        to_dealer_turn,
+        game_state->settings.message_duration);
+}
+
+int32_t blackjack_app(void* p) {
     UNUSED(p);
 
     int32_t return_code = 0;
 
-    FuriMessageQueue *event_queue = furi_message_queue_alloc(8, sizeof(AppEvent));
+    FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(AppEvent));
     dolphin_deed(DolphinDeedPluginGameStart);
-    GameState *game_state = malloc(sizeof(GameState));
-    game_state->menu= malloc(sizeof(Menu));
-    game_state->menu->menu_width=40;
+    GameState* game_state = malloc(sizeof(GameState));
+    game_state->menu = malloc(sizeof(Menu));
+    game_state->menu->menu_width = 40;
     init(game_state);
     add_menu(game_state->menu, "Double", doubleAction);
     add_menu(game_state->menu, "Hit", hitAction);
@@ -487,60 +555,58 @@ int32_t blackjack_app(void *p) {
     game_state->state = GameStateStart;
 
     game_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
-    if (!game_state->mutex) {
+    if(!game_state->mutex) {
         FURI_LOG_E(APP_NAME, "cannot create mutex\r\n");
         return_code = 255;
         goto free_and_exit;
     }
 
-    ViewPort *view_port = view_port_alloc();
+    ViewPort* view_port = view_port_alloc();
     view_port_draw_callback_set(view_port, render_callback, game_state);
     view_port_input_callback_set(view_port, input_callback, event_queue);
 
-    FuriTimer *timer =
-            furi_timer_alloc(update_timer_callback, FuriTimerTypePeriodic, event_queue);
+    FuriTimer* timer = furi_timer_alloc(update_timer_callback, FuriTimerTypePeriodic, event_queue);
     furi_timer_start(timer, furi_kernel_get_tick_frequency() / 25);
 
-    Gui *gui = furi_record_open("gui");
+    Gui* gui = furi_record_open("gui");
     gui_add_view_port(gui, view_port, GuiLayerFullscreen);
 
     AppEvent event;
 
-    for (bool processing = true; processing;) {
+    for(bool processing = true; processing;) {
         FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
         furi_mutex_acquire(game_state->mutex, FuriWaitForever);
-        if (event_status == FuriStatusOk) {
-            if (event.type == EventTypeKey) {
-
-                if (event.input.type == InputTypePress) {
-                    switch (event.input.key) {
-                        case InputKeyUp:
-                            game_state->selectDirection = DirectionUp;
-                            break;
-                        case InputKeyDown:
-                            game_state->selectDirection = DirectionDown;
-                            break;
-                        case InputKeyRight:
-                            game_state->selectDirection = DirectionRight;
-                            break;
-                        case InputKeyLeft:
-                            game_state->selectDirection = DirectionLeft;
-                            break;
-                        case InputKeyBack:
-                            if (game_state->state == GameStateSettings) {
-                                game_state->state = GameStateStart;
-                                save_settings(game_state->settings);
-                            } else
-                                processing = false;
-                            break;
-                        case InputKeyOk:
-                            game_state->selectDirection = Select;
-                            break;
-                        default:
-                            break;
+        if(event_status == FuriStatusOk) {
+            if(event.type == EventTypeKey) {
+                if(event.input.type == InputTypePress) {
+                    switch(event.input.key) {
+                    case InputKeyUp:
+                        game_state->selectDirection = DirectionUp;
+                        break;
+                    case InputKeyDown:
+                        game_state->selectDirection = DirectionDown;
+                        break;
+                    case InputKeyRight:
+                        game_state->selectDirection = DirectionRight;
+                        break;
+                    case InputKeyLeft:
+                        game_state->selectDirection = DirectionLeft;
+                        break;
+                    case InputKeyBack:
+                        if(game_state->state == GameStateSettings) {
+                            game_state->state = GameStateStart;
+                            save_settings(game_state->settings);
+                        } else
+                            processing = false;
+                        break;
+                    case InputKeyOk:
+                        game_state->selectDirection = Select;
+                        break;
+                    default:
+                        break;
                     }
                 }
-            } else if (event.type == EventTypeTick) {
+            } else if(event.type == EventTypeTick) {
                 tick(game_state);
                 processing = game_state->processing;
             }
@@ -552,7 +618,6 @@ int32_t blackjack_app(void *p) {
         furi_mutex_release(game_state->mutex);
     }
 
-
     furi_timer_free(timer);
     view_port_enabled_set(view_port, false);
     gui_remove_view_port(gui, view_port);
@@ -560,7 +625,7 @@ int32_t blackjack_app(void *p) {
     view_port_free(view_port);
     furi_mutex_free(game_state->mutex);
 
-    free_and_exit:
+free_and_exit:
     free(game_state->deck.cards);
     free_menu(game_state->menu);
     queue_clear(&(game_state->queue_state));

+ 165 - 145
blackjack/common/card.c

@@ -10,69 +10,74 @@
 #define CARD_DRAW_FIRST_ROW_LENGTH 7
 
 uint8_t pips[4][3] = {
-        {21, 10, 7},    //spades
-        {7,  10, 7},     //hearts
-        {0,  10, 7},     //diamonds
-        {14, 10, 7},     //clubs
+    {21, 10, 7}, //spades
+    {7, 10, 7}, //hearts
+    {0, 10, 7}, //diamonds
+    {14, 10, 7}, //clubs
 };
 uint8_t letters[13][3] = {
-        {0,  0, 5},
-        {5,  0, 5},
-        {10, 0, 5},
-        {15, 0, 5},
-        {20, 0, 5},
-        {25, 0, 5},
-        {30, 0, 5},
-        {0,  5, 5},
-        {5,  5, 5},
-        {10, 5, 5},
-        {15, 5, 5},
-        {20, 5, 5},
-        {25, 5, 5},
+    {0, 0, 5},
+    {5, 0, 5},
+    {10, 0, 5},
+    {15, 0, 5},
+    {20, 0, 5},
+    {25, 0, 5},
+    {30, 0, 5},
+    {0, 5, 5},
+    {5, 5, 5},
+    {10, 5, 5},
+    {15, 5, 5},
+    {20, 5, 5},
+    {25, 5, 5},
 };
 
 //region Player card positions
 uint8_t playerCardPositions[22][4] = {
-        //first row
-        {108, 38},
-        {98,  38},
-        {88,  38},
-        {78,  38},
-        {68,  38},
-        {58,  38},
-        {48,  38},
-        {38,  38},
-        //second row
-        {104, 26},
-        {94,  26},
-        {84,  26},
-        {74,  26},
-        {64,  26},
-        {54,  26},
-        {44,  26},
-        //third row
-        {99,  14},
-        {89,  14},
-        {79,  14},
-        {69,  14},
-        {59,  14},
-        {49,  14},
+    //first row
+    {108, 38},
+    {98, 38},
+    {88, 38},
+    {78, 38},
+    {68, 38},
+    {58, 38},
+    {48, 38},
+    {38, 38},
+    //second row
+    {104, 26},
+    {94, 26},
+    {84, 26},
+    {74, 26},
+    {64, 26},
+    {54, 26},
+    {44, 26},
+    //third row
+    {99, 14},
+    {89, 14},
+    {79, 14},
+    {69, 14},
+    {59, 14},
+    {49, 14},
 };
 //endregion
-Icon *card_graphics = NULL;
+Icon* card_graphics = NULL;
 
-void set_card_graphics(const Icon *graphics) {
-    card_graphics = (Icon *) graphics;
+void set_card_graphics(const Icon* graphics) {
+    card_graphics = (Icon*)graphics;
 }
 
-void
-draw_card_at_colored(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, bool inverted, Canvas *const canvas) {
+void draw_card_at_colored(
+    int8_t pos_x,
+    int8_t pos_y,
+    uint8_t pip,
+    uint8_t character,
+    bool inverted,
+    Canvas* const canvas) {
     DrawMode primary = inverted ? Black : White;
     DrawMode secondary = inverted ? White : Black;
     draw_rounded_box(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, primary);
     draw_rounded_box_frame(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, Black);
 
-    uint8_t *drawInfo = pips[pip];
+    uint8_t* drawInfo = pips[pip];
     uint8_t px = drawInfo[0], py = drawInfo[1], s = drawInfo[2];
 
     uint8_t left = pos_x + 2;
@@ -80,10 +85,8 @@ draw_card_at_colored(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character,
     uint8_t top = pos_y + 2;
     uint8_t bottom = (pos_y + CARD_HEIGHT - s - 2);
 
-    draw_icon_clip(canvas, card_graphics, right, top, px, py, s, s,
-                   secondary);
-    draw_icon_clip_flipped(canvas, card_graphics, left, bottom, px, py, s, s,
-                           secondary);
+    draw_icon_clip(canvas, card_graphics, right, top, px, py, s, s, secondary);
+    draw_icon_clip_flipped(canvas, card_graphics, left, bottom, px, py, s, s, secondary);
 
     drawInfo = letters[character];
     px = drawInfo[0], py = drawInfo[1], s = drawInfo[2];
@@ -92,40 +95,39 @@ draw_card_at_colored(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character,
     top = pos_y + 2;
     bottom = (pos_y + CARD_HEIGHT - s - 2);
 
-    draw_icon_clip(canvas, card_graphics, left, top + 1, px, py, s, s,
-                   secondary);
-    draw_icon_clip_flipped(canvas, card_graphics, right, bottom - 1, px, py, s, s,
-                           secondary);
+    draw_icon_clip(canvas, card_graphics, left, top + 1, px, py, s, s, secondary);
+    draw_icon_clip_flipped(canvas, card_graphics, right, bottom - 1, px, py, s, s, secondary);
 }
 
-void draw_card_at(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, Canvas *const canvas) {
+void draw_card_at(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, Canvas* const canvas) {
     draw_card_at_colored(pos_x, pos_y, pip, character, false, canvas);
 }
 
-void draw_deck(const Card *cards, uint8_t count, Canvas *const canvas) {
-    for (int i = count - 1; i >= 0; i--) {
-        draw_card_at(playerCardPositions[i][0], playerCardPositions[i][1], cards[i].pip, cards[i].character, canvas);
+void draw_deck(const Card* cards, uint8_t count, Canvas* const canvas) {
+    for(int i = count - 1; i >= 0; i--) {
+        draw_card_at(
+            playerCardPositions[i][0],
+            playerCardPositions[i][1],
+            cards[i].pip,
+            cards[i].character,
+            canvas);
     }
 }
 
 Vector card_pos_at_index(uint8_t index) {
-    return (Vector) {
-            playerCardPositions[index][0],
-            playerCardPositions[index][1]
-    };
+    return (Vector){playerCardPositions[index][0], playerCardPositions[index][1]};
 }
 
-void draw_card_back_at(int8_t pos_x, int8_t pos_y, Canvas *const canvas) {
+void draw_card_back_at(int8_t pos_x, int8_t pos_y, Canvas* const canvas) {
     draw_rounded_box(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, White);
     draw_rounded_box_frame(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, Black);
 
     draw_icon_clip(canvas, card_graphics, pos_x + 1, pos_y + 1, 35, 0, 15, 21, Black);
-
 }
 
-void generate_deck(Deck *deck_ptr, uint8_t deck_count) {
+void generate_deck(Deck* deck_ptr, uint8_t deck_count) {
     uint16_t counter = 0;
-    if (deck_ptr->cards != NULL) {
+    if(deck_ptr->cards != NULL) {
         free(deck_ptr->cards);
     }
 
@@ -133,24 +135,21 @@ void generate_deck(Deck *deck_ptr, uint8_t deck_count) {
     deck_ptr->card_count = deck_count * 52;
     deck_ptr->cards = malloc(sizeof(Card) * deck_ptr->card_count);
 
-    for (uint8_t deck = 0; deck < deck_count; deck++) {
-        for (uint8_t pip = 0; pip < 4; pip++) {
-            for (uint8_t label = 0; label < 13; label++) {
-                deck_ptr->cards[counter] = (Card)
-                        {
-                                pip, label, false, false
-                        };
+    for(uint8_t deck = 0; deck < deck_count; deck++) {
+        for(uint8_t pip = 0; pip < 4; pip++) {
+            for(uint8_t label = 0; label < 13; label++) {
+                deck_ptr->cards[counter] = (Card){pip, label, false, false};
                 counter++;
             }
         }
     }
 }
 
-void shuffle_deck(Deck *deck_ptr) {
+void shuffle_deck(Deck* deck_ptr) {
     srand(DWT->CYCCNT);
     deck_ptr->index = 0;
     int max = deck_ptr->deck_count * 52;
-    for (int i = 0; i < max; i++) {
+    for(int i = 0; i < max; i++) {
         int r = i + (rand() % (max - i));
         Card tmp = deck_ptr->cards[i];
         deck_ptr->cards[i] = deck_ptr->cards[r];
@@ -158,175 +157,196 @@ void shuffle_deck(Deck *deck_ptr) {
     }
 }
 
-uint8_t hand_count(const Card *cards, uint8_t count) {
+uint8_t hand_count(const Card* cards, uint8_t count) {
     uint8_t aceCount = 0;
     uint8_t score = 0;
 
-    for (uint8_t i = 0; i < count; i++) {
-        if (cards[i].character == 12)
+    for(uint8_t i = 0; i < count; i++) {
+        if(cards[i].character == 12)
             aceCount++;
         else {
-            if (cards[i].character > 8)
+            if(cards[i].character > 8)
                 score += 10;
             else
                 score += cards[i].character + 2;
         }
     }
 
-    for (uint8_t i = 0; i < aceCount; i++) {
-        if ((score + 11) <= 21) score += 11;
-        else score++;
+    for(uint8_t i = 0; i < aceCount; i++) {
+        if((score + 11) <= 21)
+            score += 11;
+        else
+            score++;
     }
 
     return score;
 }
 
-void draw_card_animation(Card animatingCard, Vector from, Vector control, Vector to, float t, bool extra_margin,
-                         Canvas *const canvas) {
+void draw_card_animation(
+    Card animatingCard,
+    Vector from,
+    Vector control,
+    Vector to,
+    float t,
+    bool extra_margin,
+    Canvas* const canvas) {
     float time = t;
-    if (extra_margin) {
+    if(extra_margin) {
         time += 0.2;
     }
 
     Vector currentPos = quadratic_2d(from, control, to, time);
-    if (t > 1) {
-        draw_card_at(currentPos.x, currentPos.y, animatingCard.pip,
-                     animatingCard.character, canvas);
+    if(t > 1) {
+        draw_card_at(
+            currentPos.x, currentPos.y, animatingCard.pip, animatingCard.character, canvas);
     } else {
-        if (t < 0.5)
+        if(t < 0.5)
             draw_card_back_at(currentPos.x, currentPos.y, canvas);
         else
-            draw_card_at(currentPos.x, currentPos.y, animatingCard.pip,
-                         animatingCard.character, canvas);
+            draw_card_at(
+                currentPos.x, currentPos.y, animatingCard.pip, animatingCard.character, canvas);
     }
 }
 
-void init_hand(Hand *hand_ptr, uint8_t count) {
+void init_hand(Hand* hand_ptr, uint8_t count) {
     hand_ptr->cards = malloc(sizeof(Card) * count);
     hand_ptr->index = 0;
     hand_ptr->max = count;
 }
 
-void free_hand(Hand *hand_ptr) {
+void free_hand(Hand* hand_ptr) {
     FURI_LOG_D("CARD", "Freeing hand");
     free(hand_ptr->cards);
 }
 
-void add_to_hand(Hand *hand_ptr, Card card) {
+void add_to_hand(Hand* hand_ptr, Card card) {
     FURI_LOG_D("CARD", "Adding to hand");
-    if (hand_ptr->index < hand_ptr->max) {
+    if(hand_ptr->index < hand_ptr->max) {
         hand_ptr->cards[hand_ptr->index] = card;
         hand_ptr->index++;
     }
 }
 
-void draw_card_space(int16_t pos_x, int16_t pos_y, bool highlighted, Canvas *const canvas) {
-    if (highlighted) {
+void draw_card_space(int16_t pos_x, int16_t pos_y, bool highlighted, Canvas* const canvas) {
+    if(highlighted) {
         draw_rounded_box_frame(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, Black);
-        draw_rounded_box_frame(canvas, pos_x + 2, pos_y + 2, CARD_WIDTH - 4, CARD_HEIGHT - 4, White);
+        draw_rounded_box_frame(
+            canvas, pos_x + 2, pos_y + 2, CARD_WIDTH - 4, CARD_HEIGHT - 4, White);
     } else {
         draw_rounded_box(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, Black);
-        draw_rounded_box_frame(canvas, pos_x + 2, pos_y + 2, CARD_WIDTH - 4, CARD_HEIGHT - 4, White);
+        draw_rounded_box_frame(
+            canvas, pos_x + 2, pos_y + 2, CARD_WIDTH - 4, CARD_HEIGHT - 4, White);
     }
 }
 
 int first_non_flipped_card(Hand hand) {
-    for (int i = 0; i < hand.index; i++) {
-        if (!hand.cards[i].flipped) {
+    for(int i = 0; i < hand.index; i++) {
+        if(!hand.cards[i].flipped) {
             return i;
         }
     }
     return hand.index;
 }
 
-void draw_hand_column(Hand hand, int16_t pos_x, int16_t pos_y, int8_t highlight, Canvas *const canvas) {
-    if (hand.index == 0) {
+void draw_hand_column(
+    Hand hand,
+    int16_t pos_x,
+    int16_t pos_y,
+    int8_t highlight,
+    Canvas* const canvas) {
+    if(hand.index == 0) {
         draw_card_space(pos_x, pos_y, highlight > 0, canvas);
-        if(highlight==0)
-            draw_rounded_box(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT,
-                             Inverse);
+        if(highlight == 0)
+            draw_rounded_box(canvas, pos_x, pos_y, CARD_WIDTH, CARD_HEIGHT, Inverse);
         return;
     }
 
     int loopEnd = hand.index;
-    int hStart = max(loopEnd-4, 0);
+    int hStart = max(loopEnd - 4, 0);
     int pos = 0;
-    int first= first_non_flipped_card(hand);
-    bool wastop=false;
-    if(first>=0 && first<=hStart && highlight!=first){
-        if(first>0){
+    int first = first_non_flipped_card(hand);
+    bool wastop = false;
+    if(first >= 0 && first <= hStart && highlight != first) {
+        if(first > 0) {
             draw_card_back_at(pos_x, pos_y + pos, canvas);
-            pos+=4;
+            pos += 4;
             hStart++;
-            wastop=true;
+            wastop = true;
         }
-        draw_card_at_colored(pos_x, pos_y + pos, hand.cards[first].pip, hand.cards[first].character,
-                             false,
-                             canvas);
-        pos+=8;
+        draw_card_at_colored(
+            pos_x, pos_y + pos, hand.cards[first].pip, hand.cards[first].character, false, canvas);
+        pos += 8;
         hStart++;
     }
-    if(hStart>highlight && highlight>=0){
-        if(!wastop && first>0){
+    if(hStart > highlight && highlight >= 0) {
+        if(!wastop && first > 0) {
             draw_card_back_at(pos_x, pos_y + pos, canvas);
-            pos+=4;
+            pos += 4;
             hStart++;
         }
-        draw_card_at_colored(pos_x, pos_y + pos, hand.cards[highlight].pip, hand.cards[highlight].character,
-                             true,
-                             canvas);
-        pos+=8;
+        draw_card_at_colored(
+            pos_x,
+            pos_y + pos,
+            hand.cards[highlight].pip,
+            hand.cards[highlight].character,
+            true,
+            canvas);
+        pos += 8;
         hStart++;
     }
-    for (int i = hStart; i < loopEnd; i++, pos+=4) {
-        if (hand.cards[i].flipped) {
+    for(int i = hStart; i < loopEnd; i++, pos += 4) {
+        if(hand.cards[i].flipped) {
             draw_card_back_at(pos_x, pos_y + pos, canvas);
-            if(i==highlight)
-            draw_rounded_box(canvas, pos_x+1, pos_y + pos+1, CARD_WIDTH - 2, CARD_HEIGHT - 2,
-                             Inverse);
+            if(i == highlight)
+                draw_rounded_box(
+                    canvas, pos_x + 1, pos_y + pos + 1, CARD_WIDTH - 2, CARD_HEIGHT - 2, Inverse);
         } else {
-            draw_card_at_colored(pos_x, pos_y + pos, hand.cards[i].pip, hand.cards[i].character,
-                                 (i == highlight),
-                                 canvas);
-            if(i == highlight || i==first) pos+=4;
+            draw_card_at_colored(
+                pos_x,
+                pos_y + pos,
+                hand.cards[i].pip,
+                hand.cards[i].character,
+                (i == highlight),
+                canvas);
+            if(i == highlight || i == first) pos += 4;
         }
     }
 }
 
-Card remove_from_deck(uint16_t index, Deck *deck) {
+Card remove_from_deck(uint16_t index, Deck* deck) {
     FURI_LOG_D("CARD", "Removing from deck");
     Card result = {0, 0, true, false};
-    if (deck->card_count > 0) {
+    if(deck->card_count > 0) {
         deck->card_count--;
-        for (int i = 0, curr_index = 0; i <= deck->card_count; i++) {
-            if (i != index) {
+        for(int i = 0, curr_index = 0; i <= deck->card_count; i++) {
+            if(i != index) {
                 deck->cards[curr_index] = deck->cards[i];
                 curr_index++;
             } else {
                 result = deck->cards[i];
             }
         }
-        if (deck->index >= 0) {
+        if(deck->index >= 0) {
             deck->index--;
         }
     }
     return result;
 }
 
-void extract_hand_region(Hand *hand, Hand *to, uint8_t start_index) {
+void extract_hand_region(Hand* hand, Hand* to, uint8_t start_index) {
     FURI_LOG_D("CARD", "Extracting hand region");
-    if (start_index >= hand->index) return;
+    if(start_index >= hand->index) return;
 
-    for (uint8_t i = start_index; i < hand->index; i++) {
+    for(uint8_t i = start_index; i < hand->index; i++) {
         add_to_hand(to, hand->cards[i]);
     }
     hand->index = start_index;
 }
 
-void add_hand_region(Hand *to, Hand *from) {
+void add_hand_region(Hand* to, Hand* from) {
     FURI_LOG_D("CARD", "Adding hand region");
-    if ((to->index + from->index) <= to->max) {
-        for (int i = 0; i < from->index; i++) {
+    if((to->index + from->index) <= to->max) {
+        for(int i = 0; i < from->index; i++) {
             add_to_hand(to, from->cards[i]);
         }
     }

+ 43 - 28
blackjack/common/card.h

@@ -12,27 +12,27 @@
 
 //region types
 typedef struct {
-    uint8_t pip;        //Pip index 0:spades, 1:hearths, 2:diamonds, 3:clubs
-    uint8_t character;  //Card letter [0-12], 0 means 2, 12 is Ace
+    uint8_t pip; //Pip index 0:spades, 1:hearths, 2:diamonds, 3:clubs
+    uint8_t character; //Card letter [0-12], 0 means 2, 12 is Ace
     bool disabled;
     bool flipped;
 } Card;
 
 typedef struct {
-    uint8_t deck_count;     //Number of decks used
-    Card *cards;            //Cards in the deck
+    uint8_t deck_count; //Number of decks used
+    Card* cards; //Cards in the deck
     int card_count;
-    int index;              //Card index (to know where we at in the deck)
+    int index; //Card index (to know where we at in the deck)
 } Deck;
 
 typedef struct {
-    Card *cards;            //Cards in the deck
-    uint8_t index;          //Current index
-    uint8_t max;            //How many cards we want to store
+    Card* cards; //Cards in the deck
+    uint8_t index; //Current index
+    uint8_t max; //How many cards we want to store
 } Hand;
 //endregion
 
-void set_card_graphics(const Icon *graphics);
+void set_card_graphics(const Icon* graphics);
 
 /**
  * Gets card coordinates at the index (range: 0-20).
@@ -51,7 +51,7 @@ Vector card_pos_at_index(uint8_t index);
  * @param character     Letter [0-12] 0 is 2, 12 is A
  * @param canvas        Pointer to Flipper's canvas object
  */
-void draw_card_at(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, Canvas *const canvas);
+void draw_card_at(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, Canvas* const canvas);
 
 /**
  * Draws card at a given coordinate (top-left corner)
@@ -63,8 +63,13 @@ void draw_card_at(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, Ca
  * @param inverted      Invert colors
  * @param canvas        Pointer to Flipper's canvas object
  */
-void
-draw_card_at_colored(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character, bool inverted, Canvas *const canvas);
+void draw_card_at_colored(
+    int8_t pos_x,
+    int8_t pos_y,
+    uint8_t pip,
+    uint8_t character,
+    bool inverted,
+    Canvas* const canvas);
 
 /**
  * Draws 'count' cards at the bottom right corner
@@ -73,7 +78,7 @@ draw_card_at_colored(int8_t pos_x, int8_t pos_y, uint8_t pip, uint8_t character,
  * @param count     Count of cards
  * @param canvas    Pointer to Flipper's canvas object
  */
-void draw_deck(const Card *cards, uint8_t count, Canvas *const canvas);
+void draw_deck(const Card* cards, uint8_t count, Canvas* const canvas);
 
 /**
  * Draws card back at a given coordinate (top-left corner)
@@ -82,7 +87,7 @@ void draw_deck(const Card *cards, uint8_t count, Canvas *const canvas);
  * @param pos_y     Y coordinate
  * @param canvas    Pointer to Flipper's canvas object
  */
-void draw_card_back_at(int8_t pos_x, int8_t pos_y, Canvas *const canvas);
+void draw_card_back_at(int8_t pos_x, int8_t pos_y, Canvas* const canvas);
 
 /**
  * Generates the deck
@@ -90,14 +95,14 @@ void draw_card_back_at(int8_t pos_x, int8_t pos_y, Canvas *const canvas);
  * @param deck_ptr      Pointer to the deck
  * @param deck_count    Number of decks
  */
-void generate_deck(Deck *deck_ptr, uint8_t deck_count);
+void generate_deck(Deck* deck_ptr, uint8_t deck_count);
 
 /**
  * Shuffles the deck
  *
  * @param deck_ptr Pointer to the deck
  */
-void shuffle_deck(Deck *deck_ptr);
+void shuffle_deck(Deck* deck_ptr);
 
 /**
  * Calculates the hand count for blackjack
@@ -106,7 +111,7 @@ void shuffle_deck(Deck *deck_ptr);
  * @param count     Count of cards
  * @return          Hand value
  */
-uint8_t hand_count(const Card *cards, uint8_t count);
+uint8_t hand_count(const Card* cards, uint8_t count);
 
 /**
  * Draws card animation
@@ -119,28 +124,34 @@ uint8_t hand_count(const Card *cards, uint8_t count);
  * @param extra_margin  Use extra margin at the end (arrives 0.2 unit before the end so it can stay there a bit)
  * @param canvas        Pointer to Flipper's canvas object
  */
-void draw_card_animation(Card animatingCard, Vector from, Vector control, Vector to, float t, bool extra_margin,
-                         Canvas *const canvas);
+void draw_card_animation(
+    Card animatingCard,
+    Vector from,
+    Vector control,
+    Vector to,
+    float t,
+    bool extra_margin,
+    Canvas* const canvas);
 
 /**
  * Init hand pointer
  * @param hand_ptr   Pointer to hand
  * @param count      Number of cards we want to store
  */
-void init_hand(Hand *hand_ptr, uint8_t count);
+void init_hand(Hand* hand_ptr, uint8_t count);
 
 /**
  * Free hand resources
  * @param hand_ptr  Pointer to hand
  */
-void free_hand(Hand *hand_ptr);
+void free_hand(Hand* hand_ptr);
 
 /**
  * Add card to hand
  * @param hand_ptr  Pointer to hand
  * @param card      Card to add
  */
-void add_to_hand(Hand *hand_ptr, Card card);
+void add_to_hand(Hand* hand_ptr, Card card);
 
 /**
  * Draw card placement position at coordinate
@@ -149,7 +160,7 @@ void add_to_hand(Hand *hand_ptr, Card card);
  * @param highlighted   Apply highlight effect
  * @param canvas    Canvas object
  */
-void draw_card_space(int16_t pos_x, int16_t pos_y, bool highlighted, Canvas *const canvas);
+void draw_card_space(int16_t pos_x, int16_t pos_y, bool highlighted, Canvas* const canvas);
 
 /**
  * Draws a column of card, displaying the last 4 cards on the list
@@ -159,8 +170,12 @@ void draw_card_space(int16_t pos_x, int16_t pos_y, bool highlighted, Canvas *con
  * @param highlight         Index to highlight, negative means no highlight
  * @param canvas            Canvas object
  */
-void
-draw_hand_column(Hand hand, int16_t pos_x, int16_t pos_y, int8_t highlight, Canvas *const canvas);
+void draw_hand_column(
+    Hand hand,
+    int16_t pos_x,
+    int16_t pos_y,
+    int8_t highlight,
+    Canvas* const canvas);
 
 /**
  * Removes a card from the deck (Be aware, if you remove the first item, the deck index will be at -1 so you have to handle that)
@@ -168,10 +183,10 @@ draw_hand_column(Hand hand, int16_t pos_x, int16_t pos_y, int8_t highlight, Canv
  * @param deck  Deck reference
  * @return      The removed card
  */
-Card remove_from_deck(uint16_t index, Deck *deck);
+Card remove_from_deck(uint16_t index, Deck* deck);
 
 int first_non_flipped_card(Hand hand);
 
-void extract_hand_region(Hand *hand, Hand *to, uint8_t start_index);
+void extract_hand_region(Hand* hand, Hand* to, uint8_t start_index);
 
-void add_hand_region(Hand *to, Hand *from);
+void add_hand_region(Hand* to, Hand* from);

+ 10 - 17
blackjack/common/dml.c

@@ -2,47 +2,40 @@
 #include <math.h>
 
 float lerp(float v0, float v1, float t) {
-    if (t > 1) return v1;
+    if(t > 1) return v1;
     return (1 - t) * v0 + t * v1;
 }
 
 Vector lerp_2d(Vector start, Vector end, float t) {
-    return (Vector) {
-            lerp(start.x, end.x, t),
-            lerp(start.y, end.y, t),
+    return (Vector){
+        lerp(start.x, end.x, t),
+        lerp(start.y, end.y, t),
     };
 }
 
 Vector quadratic_2d(Vector start, Vector control, Vector end, float t) {
-    return lerp_2d(
-            lerp_2d(start, control, t),
-            lerp_2d(control, end, t),
-            t
-    );
+    return lerp_2d(lerp_2d(start, control, t), lerp_2d(control, end, t), t);
 }
 
 Vector vector_add(Vector a, Vector b) {
-    return (Vector) {a.x + b.x, a.y + b.y};
+    return (Vector){a.x + b.x, a.y + b.y};
 }
 
 Vector vector_sub(Vector a, Vector b) {
-    return (Vector) {a.x - b.x, a.y - b.y};
+    return (Vector){a.x - b.x, a.y - b.y};
 }
 
 Vector vector_mul_components(Vector a, Vector b) {
-    return (Vector) {a.x * b.x, a.y * b.y};
+    return (Vector){a.x * b.x, a.y * b.y};
 }
 
 Vector vector_div_components(Vector a, Vector b) {
-    return (Vector) {a.x / b.x, a.y / b.y};
+    return (Vector){a.x / b.x, a.y / b.y};
 }
 
 Vector vector_normalized(Vector a) {
     float length = vector_magnitude(a);
-    return (Vector) {
-            a.x / length,
-            a.y / length
-    };
+    return (Vector){a.x / length, a.y / length};
 }
 
 float vector_magnitude(Vector a) {

+ 3 - 3
blackjack/common/dml.h

@@ -9,9 +9,9 @@ typedef struct {
     float y;
 } Vector;
 
-#define min(a,b) ((a)<(b)?(a):(b))
-#define max(a,b) ((a)>(b)?(a):(b))
-#define abs(x) ((x)>0?(x):-(x))
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#define max(a, b) ((a) > (b) ? (a) : (b))
+#define abs(x) ((x) > 0 ? (x) : -(x))
 
 /**
  * Lerp function

+ 52 - 38
blackjack/common/menu.c

@@ -1,43 +1,53 @@
 #include "menu.h"
 
-void add_menu(Menu *menu, const char *name, void (*callback)(void *)) {
-    MenuItem *items = menu->items;
+void add_menu(Menu* menu, const char* name, void (*callback)(void*)) {
+    MenuItem* items = menu->items;
 
     menu->items = malloc(sizeof(MenuItem) * (menu->menu_count + 1));
-    for (uint8_t i = 0; i < menu->menu_count; i++) {
+    for(uint8_t i = 0; i < menu->menu_count; i++) {
         menu->items[i] = items[i];
     }
     free(items);
 
-    menu->items[menu->menu_count] = (MenuItem) {name, true, callback};
+    menu->items[menu->menu_count] = (MenuItem){name, true, callback};
     menu->menu_count++;
 }
 
-void free_menu(Menu *menu) {
+void free_menu(Menu* menu) {
     free(menu->items);
     free(menu);
 }
 
-void set_menu_state(Menu *menu, uint8_t index, bool state) {
-    if (menu->menu_count > index) {
+void set_menu_state(Menu* menu, uint8_t index, bool state) {
+    if(menu->menu_count > index) {
         menu->items[index].enabled = state;
     }
-    if(!state && menu->current_menu==index)
-        move_menu(menu, 1);
+    if(!state && menu->current_menu == index) move_menu(menu, 1);
 }
 
-void move_menu(Menu *menu, int8_t direction) {
-    if (!menu->enabled) return;
+void move_menu(Menu* menu, int8_t direction) {
+    if(!menu->enabled) return;
     int max = menu->menu_count;
-    for (int8_t i = 0; i < max; i++) {
-        FURI_LOG_D("MENU", "Iteration %i, current %i, direction %i, state %i", i, menu->current_menu,direction,menu->items[menu->current_menu].enabled?1:0);
-        if (direction < 0 && menu->current_menu == 0) {
+    for(int8_t i = 0; i < max; i++) {
+        FURI_LOG_D(
+            "MENU",
+            "Iteration %i, current %i, direction %i, state %i",
+            i,
+            menu->current_menu,
+            direction,
+            menu->items[menu->current_menu].enabled ? 1 : 0);
+        if(direction < 0 && menu->current_menu == 0) {
             menu->current_menu = menu->menu_count - 1;
         } else {
             menu->current_menu = (menu->current_menu + direction) % menu->menu_count;
         }
-        FURI_LOG_D("MENU", "After process current %i, direction %i, state %i", menu->current_menu,direction,menu->items[menu->current_menu].enabled?1:0);
-        if (menu->items[menu->current_menu].enabled) {
+        FURI_LOG_D(
+            "MENU",
+            "After process current %i, direction %i, state %i",
+            menu->current_menu,
+            direction,
+            menu->items[menu->current_menu].enabled ? 1 : 0);
+        if(menu->items[menu->current_menu].enabled) {
             FURI_LOG_D("MENU", "Next menu %i", menu->current_menu);
             return;
         }
@@ -46,44 +56,48 @@ void move_menu(Menu *menu, int8_t direction) {
     menu->enabled = false;
 }
 
-void activate_menu(Menu *menu, void *state) {
-    if (!menu->enabled) return;
+void activate_menu(Menu* menu, void* state) {
+    if(!menu->enabled) return;
     menu->items[menu->current_menu].callback(state);
 }
 
-void render_menu(Menu *menu, Canvas *canvas, uint8_t pos_x, uint8_t pos_y) {
-    if (!menu->enabled) return;
+void render_menu(Menu* menu, Canvas* canvas, uint8_t pos_x, uint8_t pos_y) {
+    if(!menu->enabled) return;
     canvas_set_color(canvas, ColorWhite);
     canvas_draw_rbox(canvas, pos_x, pos_y, menu->menu_width + 2, 10, 2);
 
-    uint8_t w = pos_x+menu->menu_width;
-    uint8_t h = pos_y+10;
-    uint8_t p1x = pos_x+2;
-    uint8_t p2x = pos_x+menu->menu_width-2;
-    uint8_t p1y = pos_y+2;
-    uint8_t p2y = pos_y+8;
+    uint8_t w = pos_x + menu->menu_width;
+    uint8_t h = pos_y + 10;
+    uint8_t p1x = pos_x + 2;
+    uint8_t p2x = pos_x + menu->menu_width - 2;
+    uint8_t p1y = pos_y + 2;
+    uint8_t p2y = pos_y + 8;
 
     canvas_set_color(canvas, ColorBlack);
     canvas_draw_line(canvas, p1x, pos_y, p2x, pos_y);
     canvas_draw_line(canvas, p1x, h, p2x, h);
     canvas_draw_line(canvas, pos_x, p1y, pos_x, p2y);
     canvas_draw_line(canvas, w, p1y, w, p2y);
-    canvas_draw_dot(canvas, pos_x+1, pos_y+1);
-    canvas_draw_dot(canvas, w-1, pos_y+1);
-    canvas_draw_dot(canvas, w-1, h-1);
-    canvas_draw_dot(canvas, pos_x+1, h-1);
+    canvas_draw_dot(canvas, pos_x + 1, pos_y + 1);
+    canvas_draw_dot(canvas, w - 1, pos_y + 1);
+    canvas_draw_dot(canvas, w - 1, h - 1);
+    canvas_draw_dot(canvas, pos_x + 1, h - 1);
 
-//    canvas_draw_rbox(canvas, pos_x, pos_y, menu->menu_width + 2, 10, 2);
+    //    canvas_draw_rbox(canvas, pos_x, pos_y, menu->menu_width + 2, 10, 2);
     canvas_set_font(canvas, FontSecondary);
-    canvas_draw_str_aligned(canvas, pos_x + menu->menu_width / 2, pos_y + 6, AlignCenter, AlignCenter,
-                            menu->items[menu->current_menu].name);
+    canvas_draw_str_aligned(
+        canvas,
+        pos_x + menu->menu_width / 2,
+        pos_y + 6,
+        AlignCenter,
+        AlignCenter,
+        menu->items[menu->current_menu].name);
     //9*5
     int center = pos_x + menu->menu_width / 2;
-    for(uint8_t i=0;i<4;i++){
-        for(int8_t j = -i; j<=i;j++){
-            canvas_draw_dot(canvas, center+j, pos_y-4+i);
-            canvas_draw_dot(canvas, center+j, pos_y+14-i);
+    for(uint8_t i = 0; i < 4; i++) {
+        for(int8_t j = -i; j <= i; j++) {
+            canvas_draw_dot(canvas, center + j, pos_y - 4 + i);
+            canvas_draw_dot(canvas, center + j, pos_y + 14 - i);
         }
     }
-
 }

+ 15 - 14
blackjack/common/menu.h

@@ -4,18 +4,19 @@
 #include <gui/gui.h>
 
 typedef struct {
-    const char *name;               //Name of the menu
-    bool enabled;                   //Is the menu item enabled (it will not render, you cannot select it)
+    const char* name; //Name of the menu
+    bool enabled; //Is the menu item enabled (it will not render, you cannot select it)
 
-    void (*callback)(void *state);  //Callback for when the activate_menu is called while this menu is selected
+    void (*callback)(
+        void* state); //Callback for when the activate_menu is called while this menu is selected
 } MenuItem;
 
 typedef struct {
-    MenuItem *items;                //list of menu items
-    uint8_t menu_count;             //count of menu items (do not change)
-    uint8_t current_menu;           //currently selected menu item
-    uint8_t menu_width;             //width of the menu
-    bool enabled;                   //is the menu enabled (it will not render and accept events when disabled)
+    MenuItem* items; //list of menu items
+    uint8_t menu_count; //count of menu items (do not change)
+    uint8_t current_menu; //currently selected menu item
+    uint8_t menu_width; //width of the menu
+    bool enabled; //is the menu enabled (it will not render and accept events when disabled)
 } Menu;
 
 /**
@@ -23,7 +24,7 @@ typedef struct {
  *
  * @param menu Pointer of the menu to clean up
  */
-void free_menu(Menu *menu);
+void free_menu(Menu* menu);
 
 /**
  * Add a new menu item
@@ -32,7 +33,7 @@ void free_menu(Menu *menu);
  * @param name      Name of the menu item
  * @param callback  Callback called on activation
  */
-void add_menu(Menu *menu, const char *name, void (*callback)(void *));
+void add_menu(Menu* menu, const char* name, void (*callback)(void*));
 
 /**
  * Setting menu item to be enabled/disabled
@@ -41,7 +42,7 @@ void add_menu(Menu *menu, const char *name, void (*callback)(void *));
  * @param index Menu index to set
  * @param state Enabled (true), Disabled(false)
  */
-void set_menu_state(Menu *menu, uint8_t index, bool state);
+void set_menu_state(Menu* menu, uint8_t index, bool state);
 
 /**
  * Moves selection up or down
@@ -49,7 +50,7 @@ void set_menu_state(Menu *menu, uint8_t index, bool state);
  * @param menu      Pointer of the menu
  * @param direction Direction to move -1 down, 1 up
  */
-void move_menu(Menu *menu, int8_t direction);
+void move_menu(Menu* menu, int8_t direction);
 
 /**
  * Triggers the current menu callback
@@ -57,7 +58,7 @@ void move_menu(Menu *menu, int8_t direction);
  * @param menu  Pointer of the menu
  * @param state Usually your application state
  */
-void activate_menu(Menu *menu, void *state);
+void activate_menu(Menu* menu, void* state);
 
 /**
  * Renders the menu at a coordinate (call it in your render function).
@@ -73,4 +74,4 @@ void activate_menu(Menu *menu, void *state);
  * @param pos_x     X position to draw
  * @param pos_y     Y position to draw
  */
-void render_menu(Menu *menu, Canvas *canvas, uint8_t pos_x, uint8_t pos_y);
+void render_menu(Menu* menu, Canvas* canvas, uint8_t pos_x, uint8_t pos_y);

+ 29 - 26
blackjack/common/queue.c

@@ -1,15 +1,14 @@
 #include "queue.h"
 
-
-void render_queue(const QueueState *queue_state, const void *app_state, Canvas *const canvas) {
-    if (queue_state->current != NULL && queue_state->current->render != NULL)
-        ((QueueItem *) queue_state->current)->render(app_state, canvas);
+void render_queue(const QueueState* queue_state, const void* app_state, Canvas* const canvas) {
+    if(queue_state->current != NULL && queue_state->current->render != NULL)
+        ((QueueItem*)queue_state->current)->render(app_state, canvas);
 }
 
-bool run_queue(QueueState *queue_state, void *app_state) {
-    if (queue_state->current != NULL) {
+bool run_queue(QueueState* queue_state, void* app_state) {
+    if(queue_state->current != NULL) {
         queue_state->running = true;
-        if ((furi_get_tick() - queue_state->start) >= queue_state->current->duration)
+        if((furi_get_tick() - queue_state->start) >= queue_state->current->duration)
             dequeue(queue_state, app_state);
 
         return true;
@@ -17,44 +16,48 @@ bool run_queue(QueueState *queue_state, void *app_state) {
     return false;
 }
 
-void dequeue(QueueState *queue_state, void *app_state) {
-    ((QueueItem *) queue_state->current)->callback(app_state);
-    QueueItem *f = queue_state->current;
+void dequeue(QueueState* queue_state, void* app_state) {
+    ((QueueItem*)queue_state->current)->callback(app_state);
+    QueueItem* f = queue_state->current;
     queue_state->current = f->next;
     free(f);
-    if (queue_state->current != NULL) {
-        if (queue_state->current->start != NULL)
-            queue_state->current->start(app_state);
+    if(queue_state->current != NULL) {
+        if(queue_state->current->start != NULL) queue_state->current->start(app_state);
         queue_state->start = furi_get_tick();
-    }else{
+    } else {
         queue_state->running = false;
     }
 }
 
-void queue_clear(QueueState *queue_state) {
+void queue_clear(QueueState* queue_state) {
     queue_state->running = false;
-    QueueItem *curr = queue_state->current;
-    while (curr != NULL) {
-        QueueItem *f = curr;
+    QueueItem* curr = queue_state->current;
+    while(curr != NULL) {
+        QueueItem* f = curr;
         curr = curr->next;
         free(f);
     }
 }
 
-void enqueue(QueueState *queue_state, void *app_state,
-             void(*done)(void *state), void(*start)(void *state),
-             void (*render)(const void *state, Canvas *const canvas), uint32_t duration) {
-    QueueItem *next;
-    if (queue_state->current == NULL) {
+void enqueue(
+    QueueState* queue_state,
+    void* app_state,
+    void (*done)(void* state),
+    void (*start)(void* state),
+    void (*render)(const void* state, Canvas* const canvas),
+    uint32_t duration) {
+    QueueItem* next;
+    if(queue_state->current == NULL) {
         queue_state->start = furi_get_tick();
         queue_state->current = malloc(sizeof(QueueItem));
         next = queue_state->current;
-        if (next->start != NULL)
-            next->start(app_state);
+        if(next->start != NULL) next->start(app_state);
 
     } else {
         next = queue_state->current;
-        while (next->next != NULL) { next = (QueueItem *) (next->next); }
+        while(next->next != NULL) {
+            next = (QueueItem*)(next->next);
+        }
         next->next = malloc(sizeof(QueueItem));
         next = next->next;
     }

+ 21 - 15
blackjack/common/queue.h

@@ -4,17 +4,19 @@
 #include <furi.h>
 
 typedef struct {
-    void (*callback)(void *state);                              //Callback for when the item is dequeued
-    void (*render)(const void *state, Canvas *const canvas);    //Callback for the rendering loop while this item is running
-    void (*start)(void *state);                                 //Callback when this item is started running
-    void *next;                                                 //Pointer to the next item
-    uint32_t duration;                                          //duration of the item
+    void (*callback)(void* state); //Callback for when the item is dequeued
+    void (*render)(
+        const void* state,
+        Canvas* const canvas); //Callback for the rendering loop while this item is running
+    void (*start)(void* state); //Callback when this item is started running
+    void* next; //Pointer to the next item
+    uint32_t duration; //duration of the item
 } QueueItem;
 
 typedef struct {
-    unsigned int start;                                         //current queue item start time
-    QueueItem *current;                                         //current queue item
-    bool running;                                               //is the queue running
+    unsigned int start; //current queue item start time
+    QueueItem* current; //current queue item
+    bool running; //is the queue running
 } QueueState;
 
 /**
@@ -27,15 +29,19 @@ typedef struct {
  * @param render        Callback to render loop if needed
  * @param duration      Length of the item
  */
-void enqueue(QueueState *queue_state, void *app_state,
-             void(*done)(void *state), void(*start)(void *state),
-             void (*render)(const void *state, Canvas *const canvas), uint32_t duration);
+void enqueue(
+    QueueState* queue_state,
+    void* app_state,
+    void (*done)(void* state),
+    void (*start)(void* state),
+    void (*render)(const void* state, Canvas* const canvas),
+    uint32_t duration);
 /**
  * Clears all queue items
  *
  * @param queue_state   The queue state pointer
  */
-void queue_clear(QueueState *queue_state);
+void queue_clear(QueueState* queue_state);
 
 /**
  * Dequeues the active queue item. Usually you don't need to call it directly.
@@ -43,7 +49,7 @@ void queue_clear(QueueState *queue_state);
  * @param queue_state   The queue state pointer
  * @param app_state     Your application state
  */
-void dequeue(QueueState *queue_state, void *app_state);
+void dequeue(QueueState* queue_state, void* app_state);
 
 /**
  * Runs the queue logic (place it in your tick function)
@@ -52,7 +58,7 @@ void dequeue(QueueState *queue_state, void *app_state);
  * @param app_state     Your application state
  * @return              FALSE when there is nothing to run, TRUE otherwise
  */
-bool run_queue(QueueState *queue_state, void *app_state);
+bool run_queue(QueueState* queue_state, void* app_state);
 
 /**
  * Calls the currently active queue items render callback (if there is any)
@@ -61,4 +67,4 @@ bool run_queue(QueueState *queue_state, void *app_state);
  * @param app_state     Your application state
  * @param canvas        Pointer to Flipper's canvas object
  */
-void render_queue(const QueueState *queue_state, const void *app_state, Canvas *const canvas);
+void render_queue(const QueueState* queue_state, const void* app_state, Canvas* const canvas);

+ 110 - 69
blackjack/common/ui.c

@@ -6,35 +6,31 @@
 #include <gui/icon_i.h>
 #include <furi_hal.h>
 
-TileMap *tileMap;
+TileMap* tileMap;
 uint8_t tileMapCount = 0;
 
 void ui_cleanup() {
-    if (tileMap != NULL) {
-        for (uint8_t i = 0; i < tileMapCount; i++) {
-            if (tileMap[i].data != NULL)
-                free(tileMap[i].data);
+    if(tileMap != NULL) {
+        for(uint8_t i = 0; i < tileMapCount; i++) {
+            if(tileMap[i].data != NULL) free(tileMap[i].data);
         }
         free(tileMap);
     }
 }
 
-void add_new_tilemap(uint8_t *data, unsigned long iconId) {
-    TileMap *old = tileMap;
+void add_new_tilemap(uint8_t* data, unsigned long iconId) {
+    TileMap* old = tileMap;
     tileMapCount++;
     tileMap = malloc(sizeof(TileMap) * tileMapCount);
-    if (tileMapCount > 1) {
-        for (uint8_t i = 0; i < tileMapCount; i++)
-            tileMap[i] = old[i];
+    if(tileMapCount > 1) {
+        for(uint8_t i = 0; i < tileMapCount; i++) tileMap[i] = old[i];
     }
-    tileMap[tileMapCount - 1] = (TileMap) {data, iconId};
+    tileMap[tileMapCount - 1] = (TileMap){data, iconId};
 }
 
-
-uint8_t *get_tilemap(unsigned long icon_id) {
-    for (uint8_t i = 0; i < tileMapCount; i++) {
-        if (tileMap[i].iconId == icon_id)
-            return tileMap[i].data;
+uint8_t* get_tilemap(unsigned long icon_id) {
+    for(uint8_t i = 0; i < tileMapCount; i++) {
+        if(tileMap[i].iconId == icon_id) return tileMap[i].data;
     }
 
     return NULL;
@@ -60,46 +56,45 @@ unsigned unsetBit(uint8_t x, uint8_t bit) {
     return x & ~(1 << bit);
 }
 
-bool test_pixel(uint8_t *data, uint8_t x, uint8_t y, uint8_t w) {
+bool test_pixel(uint8_t* data, uint8_t x, uint8_t y, uint8_t w) {
     uint8_t current_bit = (y % 8);
     uint8_t current_row = ((y - current_bit) / 8);
     uint8_t current_value = data[current_row * w + x];
     return current_value & (1 << current_bit);
 }
 
-uint8_t* get_buffer(Canvas *const canvas){
+uint8_t* get_buffer(Canvas* const canvas) {
     return canvas->fb.tile_buf_ptr;
-  //  return canvas_get_buffer(canvas);
+    //  return canvas_get_buffer(canvas);
 }
-uint8_t* make_buffer(){
+uint8_t* make_buffer() {
     return malloc(sizeof(uint8_t) * 8 * 128);
 }
-void clone_buffer(uint8_t* canvas, uint8_t* data){
-    for(int i=0;i<1024;i++){
-        data[i]= canvas[i];
+void clone_buffer(uint8_t* canvas, uint8_t* data) {
+    for(int i = 0; i < 1024; i++) {
+        data[i] = canvas[i];
     }
 }
 
-
-bool read_pixel(Canvas *const canvas, int16_t x, int16_t y) {
-    if (in_screen(x, y)) {
+bool read_pixel(Canvas* const canvas, int16_t x, int16_t y) {
+    if(in_screen(x, y)) {
         return test_pixel(get_buffer(canvas), x, y, SCREEN_WIDTH);
     }
     return false;
 }
 
-void set_pixel(Canvas *const canvas, int16_t x, int16_t y, DrawMode draw_mode) {
-    if (in_screen(x, y)) {
+void set_pixel(Canvas* const canvas, int16_t x, int16_t y, DrawMode draw_mode) {
+    if(in_screen(x, y)) {
         uint8_t current_bit = (y % 8);
         uint8_t current_row = ((y - current_bit) / 8);
         uint32_t i = pixel_index(x, current_row);
         uint8_t* buffer = get_buffer(canvas);
 
         uint8_t current_value = buffer[i];
-        if (draw_mode == Inverse) {
+        if(draw_mode == Inverse) {
             buffer[i] = flipBit(current_value, current_bit);
         } else {
-            if (draw_mode == White) {
+            if(draw_mode == White) {
                 buffer[i] = unsetBit(current_value, current_bit);
             } else {
                 buffer[i] = setBit(current_value, current_bit);
@@ -108,15 +103,27 @@ void set_pixel(Canvas *const canvas, int16_t x, int16_t y, DrawMode draw_mode) {
     }
 }
 
-void draw_line(Canvas *const canvas, int16_t x1, int16_t y1, int16_t x2, int16_t y2, DrawMode draw_mode) {
-    for (int16_t x = x2; x >= x1; x--) {
-        for (int16_t y = y2; y >= y1; y--) {
+void draw_line(
+    Canvas* const canvas,
+    int16_t x1,
+    int16_t y1,
+    int16_t x2,
+    int16_t y2,
+    DrawMode draw_mode) {
+    for(int16_t x = x2; x >= x1; x--) {
+        for(int16_t y = y2; y >= y1; y--) {
             set_pixel(canvas, x, y, draw_mode);
         }
     }
 }
 
-void draw_rounded_box_frame(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode draw_mode) {
+void draw_rounded_box_frame(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode draw_mode) {
     int16_t xMinCorner = x + 1;
     int16_t xMax = x + w - 1;
     int16_t xMaxCorner = x + w - 2;
@@ -129,87 +136,121 @@ void draw_rounded_box_frame(Canvas *const canvas, int16_t x, int16_t y, uint8_t
     draw_line(canvas, xMax, yMinCorner, xMax, yMaxCorner, draw_mode);
 }
 
-void draw_rounded_box(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode draw_mode) {
-    for (int16_t o = w - 2; o >= 1; o--) {
-        for (int16_t p = h - 2; p >= 1; p--) {
+void draw_rounded_box(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode draw_mode) {
+    for(int16_t o = w - 2; o >= 1; o--) {
+        for(int16_t p = h - 2; p >= 1; p--) {
             set_pixel(canvas, x + o, y + p, draw_mode);
         }
     }
     draw_rounded_box_frame(canvas, x, y, w, h, draw_mode);
 }
 
-void invert_shape(Canvas *const canvas, uint8_t *data, int16_t x, int16_t y, uint8_t w, uint8_t h) {
+void invert_shape(Canvas* const canvas, uint8_t* data, int16_t x, int16_t y, uint8_t w, uint8_t h) {
     draw_pixels(canvas, data, x, y, w, h, Inverse);
 }
 
-void draw_pixels(Canvas *const canvas, uint8_t *data, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode) {
-    for (int8_t o = 0; o < w; o++) {
-        for (int8_t p = 0; p < h; p++) {
-            if (in_screen(o + x, p + y) && data[p * w + o] == 1)
+void draw_pixels(
+    Canvas* const canvas,
+    uint8_t* data,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode) {
+    for(int8_t o = 0; o < w; o++) {
+        for(int8_t p = 0; p < h; p++) {
+            if(in_screen(o + x, p + y) && data[p * w + o] == 1)
                 set_pixel(canvas, o + x, p + y, drawMode);
         }
     }
 }
 
-void draw_rectangle(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode) {
-    for (int8_t o = 0; o < w; o++) {
-        for (int8_t p = 0; p < h; p++) {
-            if (in_screen(o + x, p + y)) {
+void draw_rectangle(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode) {
+    for(int8_t o = 0; o < w; o++) {
+        for(int8_t p = 0; p < h; p++) {
+            if(in_screen(o + x, p + y)) {
                 set_pixel(canvas, o + x, p + y, drawMode);
             }
         }
     }
 }
 
-void invert_rectangle(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h) {
+void invert_rectangle(Canvas* const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h) {
     draw_rectangle(canvas, x, y, w, h, Inverse);
 }
 
-uint8_t *image_data(Canvas *const canvas, const Icon *icon) {
-    uint8_t *data = malloc(sizeof(uint8_t) * 8 * 128);
-    uint8_t *screen = canvas->fb.tile_buf_ptr;
+uint8_t* image_data(Canvas* const canvas, const Icon* icon) {
+    uint8_t* data = malloc(sizeof(uint8_t) * 8 * 128);
+    uint8_t* screen = canvas->fb.tile_buf_ptr;
     canvas->fb.tile_buf_ptr = data;
     canvas_draw_icon(canvas, 0, 0, icon);
     canvas->fb.tile_buf_ptr = screen;
     return data;
 }
 
-uint8_t *getOrAddIconData(Canvas *const canvas, const Icon *icon) {
-    uint8_t *icon_data = get_tilemap((unsigned long) icon);
-    if (icon_data == NULL) {
+uint8_t* getOrAddIconData(Canvas* const canvas, const Icon* icon) {
+    uint8_t* icon_data = get_tilemap((unsigned long)icon);
+    if(icon_data == NULL) {
         icon_data = image_data(canvas, icon);
-        add_new_tilemap(icon_data, (unsigned long) icon);
+        add_new_tilemap(icon_data, (unsigned long)icon);
     }
     return icon_data;
 }
 
-void draw_icon_clip(Canvas *const canvas, const Icon *icon, int16_t x, int16_t y, uint8_t left, uint8_t top, uint8_t w,
-                    uint8_t h, DrawMode drawMode) {
-    uint8_t *icon_data = getOrAddIconData(canvas, icon);
+void draw_icon_clip(
+    Canvas* const canvas,
+    const Icon* icon,
+    int16_t x,
+    int16_t y,
+    uint8_t left,
+    uint8_t top,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode) {
+    uint8_t* icon_data = getOrAddIconData(canvas, icon);
 
-    for (int i = 0; i < w; i++) {
-        for (int j = 0; j < h; j++) {
+    for(int i = 0; i < w; i++) {
+        for(int j = 0; j < h; j++) {
             bool on = test_pixel(icon_data, left + i, top + j, SCREEN_WIDTH);
-            if (drawMode == Filled) {
+            if(drawMode == Filled) {
                 set_pixel(canvas, x + i, y + j, on ? Black : White);
-            } else if (on)
+            } else if(on)
                 set_pixel(canvas, x + i, y + j, drawMode);
         }
     }
 }
 
-void draw_icon_clip_flipped(Canvas *const canvas, const Icon *icon, int16_t x, int16_t y, uint8_t left, uint8_t top,
-                            uint8_t w,
-                            uint8_t h, DrawMode drawMode) {
-    uint8_t *icon_data = getOrAddIconData(canvas, icon);
+void draw_icon_clip_flipped(
+    Canvas* const canvas,
+    const Icon* icon,
+    int16_t x,
+    int16_t y,
+    uint8_t left,
+    uint8_t top,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode) {
+    uint8_t* icon_data = getOrAddIconData(canvas, icon);
 
-    for (int i = 0; i < w; i++) {
-        for (int j = 0; j < h; j++) {
+    for(int i = 0; i < w; i++) {
+        for(int j = 0; j < h; j++) {
             bool on = test_pixel(icon_data, left + i, top + j, SCREEN_WIDTH);
 
-            if (drawMode == Filled) {
+            if(drawMode == Filled) {
                 set_pixel(canvas, x + w - i - 1, y + h - j - 1, on ? Black : White);
-            } else if (on)
+            } else if(on)
                 set_pixel(canvas, x + w - i - 1, y + h - j - 1, drawMode);
         }
     }

+ 75 - 28
blackjack/common/ui.h

@@ -10,49 +10,96 @@ typedef enum {
     Black,
     White,
     Inverse,
-    Filled  //Currently only for Icon clip drawing
+    Filled //Currently only for Icon clip drawing
 } DrawMode;
 
 // size is the screen size
 
 typedef struct {
-    uint8_t *data;
+    uint8_t* data;
     unsigned long iconId;
 } TileMap;
 
-bool test_pixel(uint8_t *data, uint8_t x, uint8_t y, uint8_t w);
+bool test_pixel(uint8_t* data, uint8_t x, uint8_t y, uint8_t w);
 
-uint8_t *image_data(Canvas *const canvas, const Icon *icon);
+uint8_t* image_data(Canvas* const canvas, const Icon* icon);
 
 uint32_t pixel_index(uint8_t x, uint8_t y);
 
-void draw_icon_clip(Canvas *const canvas, const Icon *icon, int16_t x, int16_t y, uint8_t left, uint8_t top, uint8_t w,
-                    uint8_t h, DrawMode drawMode);
-
-void draw_icon_clip_flipped(Canvas *const canvas, const Icon *icon, int16_t x, int16_t y, uint8_t left, uint8_t top, uint8_t w,
-                    uint8_t h, DrawMode drawMode);
-
-void draw_rounded_box(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode);
-
-void draw_rounded_box_frame(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode);
-
-void draw_rectangle(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode);
-
-void invert_rectangle(Canvas *const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h);
-
-void invert_shape(Canvas *const canvas, uint8_t *data, int16_t x, int16_t y, uint8_t w, uint8_t h);
-
-void draw_pixels(Canvas *const canvas, uint8_t *data, int16_t x, int16_t y, uint8_t w, uint8_t h, DrawMode drawMode);
-
-bool read_pixel(Canvas *const canvas, int16_t x, int16_t y);
-
-void set_pixel(Canvas *const canvas, int16_t x, int16_t y, DrawMode draw_mode);
-
-void draw_line(Canvas *const canvas, int16_t x1, int16_t y1, int16_t x2, int16_t y2, DrawMode draw_mode);
+void draw_icon_clip(
+    Canvas* const canvas,
+    const Icon* icon,
+    int16_t x,
+    int16_t y,
+    uint8_t left,
+    uint8_t top,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+void draw_icon_clip_flipped(
+    Canvas* const canvas,
+    const Icon* icon,
+    int16_t x,
+    int16_t y,
+    uint8_t left,
+    uint8_t top,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+void draw_rounded_box(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+void draw_rounded_box_frame(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+void draw_rectangle(
+    Canvas* const canvas,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+void invert_rectangle(Canvas* const canvas, int16_t x, int16_t y, uint8_t w, uint8_t h);
+
+void invert_shape(Canvas* const canvas, uint8_t* data, int16_t x, int16_t y, uint8_t w, uint8_t h);
+
+void draw_pixels(
+    Canvas* const canvas,
+    uint8_t* data,
+    int16_t x,
+    int16_t y,
+    uint8_t w,
+    uint8_t h,
+    DrawMode drawMode);
+
+bool read_pixel(Canvas* const canvas, int16_t x, int16_t y);
+
+void set_pixel(Canvas* const canvas, int16_t x, int16_t y, DrawMode draw_mode);
+
+void draw_line(
+    Canvas* const canvas,
+    int16_t x1,
+    int16_t y1,
+    int16_t x2,
+    int16_t y2,
+    DrawMode draw_mode);
 
 bool in_screen(int16_t x, int16_t y);
 
 void ui_cleanup();
-uint8_t* get_buffer(Canvas *const canvas);
+uint8_t* get_buffer(Canvas* const canvas);
 uint8_t* make_buffer();
 void clone_buffer(uint8_t* canvas, uint8_t* data);

+ 2 - 3
blackjack/defines.h

@@ -22,7 +22,7 @@ typedef enum {
     EventTypeKey,
 } EventType;
 
-typedef struct{
+typedef struct {
     uint32_t animation_duration;
     uint32_t message_duration;
     uint32_t starting_money;
@@ -71,8 +71,7 @@ typedef struct {
     Deck deck;
     PlayState state;
     QueueState queue_state;
-    Menu *menu;
+    Menu* menu;
     unsigned int last_tick;
     FuriMutex* mutex;
 } GameState;
-

+ 79 - 73
blackjack/ui.c

@@ -6,32 +6,28 @@
 #define LINE_HEIGHT 16
 #define ITEM_PADDING 4
 
-const char MoneyMul[4] = {
-        'K', 'B', 'T', 'S'
-};
+const char MoneyMul[4] = {'K', 'B', 'T', 'S'};
 
-void draw_player_scene(Canvas *const canvas, const GameState *game_state) {
+void draw_player_scene(Canvas* const canvas, const GameState* game_state) {
     int max_card = game_state->player_card_count;
 
-    if (max_card > 0)
-        draw_deck((game_state->player_cards), max_card, canvas);
+    if(max_card > 0) draw_deck((game_state->player_cards), max_card, canvas);
 
-    if (game_state->dealer_card_count > 0)
-        draw_card_back_at(13, 5, canvas);
+    if(game_state->dealer_card_count > 0) draw_card_back_at(13, 5, canvas);
 
     max_card = game_state->dealer_card_count;
-    if (max_card > 1) {
-        draw_card_at(2, 2, game_state->dealer_cards[1].pip, game_state->dealer_cards[1].character,
-                   canvas);
+    if(max_card > 1) {
+        draw_card_at(
+            2, 2, game_state->dealer_cards[1].pip, game_state->dealer_cards[1].character, canvas);
     }
 }
 
-void draw_dealer_scene(Canvas *const canvas, const GameState *game_state) {
+void draw_dealer_scene(Canvas* const canvas, const GameState* game_state) {
     uint8_t max_card = game_state->dealer_card_count;
     draw_deck((game_state->dealer_cards), max_card, canvas);
 }
 
-void popup_frame(Canvas *const canvas) {
+void popup_frame(Canvas* const canvas) {
     canvas_set_color(canvas, ColorWhite);
     canvas_draw_box(canvas, 32, 15, 66, 13);
     canvas_set_color(canvas, ColorBlack);
@@ -39,15 +35,16 @@ void popup_frame(Canvas *const canvas) {
     canvas_set_font(canvas, FontSecondary);
 }
 
-
-void draw_play_menu(Canvas *const canvas, const GameState *game_state) {
-    const char *menus[3] = {"Double", "Hit", "Stay"};
-    for (uint8_t m = 0; m < 3; m++) {
-        if (m == 0 && (game_state->doubled || game_state->player_score < game_state->settings.round_price)) continue;
+void draw_play_menu(Canvas* const canvas, const GameState* game_state) {
+    const char* menus[3] = {"Double", "Hit", "Stay"};
+    for(uint8_t m = 0; m < 3; m++) {
+        if(m == 0 &&
+           (game_state->doubled || game_state->player_score < game_state->settings.round_price))
+            continue;
         int y = m * 13 + 25;
         canvas_set_color(canvas, ColorBlack);
 
-        if (game_state->selectedMenu == m) {
+        if(game_state->selectedMenu == m) {
             canvas_set_color(canvas, ColorBlack);
             canvas_draw_box(canvas, 1, y, 31, 12);
         } else {
@@ -57,7 +54,7 @@ void draw_play_menu(Canvas *const canvas, const GameState *game_state) {
             canvas_draw_frame(canvas, 1, y, 31, 12);
         }
 
-        if (game_state->selectedMenu == m)
+        if(game_state->selectedMenu == m)
             canvas_set_color(canvas, ColorWhite);
         else
             canvas_set_color(canvas, ColorBlack);
@@ -65,35 +62,34 @@ void draw_play_menu(Canvas *const canvas, const GameState *game_state) {
     }
 }
 
-void draw_screen(Canvas *const canvas, const bool *points) {
-    for (uint8_t x = 0; x < 128; x++) {
-        for (uint8_t y = 0; y < 64; y++) {
-            if (points[y * 128 + x])
-                canvas_draw_dot(canvas, x, y);
+void draw_screen(Canvas* const canvas, const bool* points) {
+    for(uint8_t x = 0; x < 128; x++) {
+        for(uint8_t y = 0; y < 64; y++) {
+            if(points[y * 128 + x]) canvas_draw_dot(canvas, x, y);
         }
     }
 }
 
-void draw_score(Canvas *const canvas, bool top, uint8_t amount) {
+void draw_score(Canvas* const canvas, bool top, uint8_t amount) {
     char drawChar[20];
     snprintf(drawChar, sizeof(drawChar), "Player score: %i", amount);
-    if (top)
+    if(top)
         canvas_draw_str_aligned(canvas, 64, 2, AlignCenter, AlignTop, drawChar);
     else
         canvas_draw_str_aligned(canvas, 64, 62, AlignCenter, AlignBottom, drawChar);
 }
 
-void draw_money(Canvas *const canvas, uint32_t score) {
+void draw_money(Canvas* const canvas, uint32_t score) {
     canvas_set_font(canvas, FontSecondary);
     char drawChar[10];
     uint32_t currAmount = score;
-    if (currAmount < 1000) {
+    if(currAmount < 1000) {
         snprintf(drawChar, sizeof(drawChar), "$%lu", currAmount);
     } else {
         char c = 'K';
-        for (uint8_t i = 0; i < 4; i++) {
+        for(uint8_t i = 0; i < 4; i++) {
             currAmount = currAmount / 1000;
-            if (currAmount < 1000) {
+            if(currAmount < 1000) {
                 c = MoneyMul[i];
                 break;
             }
@@ -104,77 +100,87 @@ void draw_money(Canvas *const canvas, uint32_t score) {
     canvas_draw_str_aligned(canvas, 126, 2, AlignRight, AlignTop, drawChar);
 }
 
-
-void draw_menu(Canvas *const canvas, const char *text, const char *value, int8_t y, bool left_caret, bool right_caret,
-               bool selected) {
+void draw_menu(
+    Canvas* const canvas,
+    const char* text,
+    const char* value,
+    int8_t y,
+    bool left_caret,
+    bool right_caret,
+    bool selected) {
     UNUSED(selected);
-    if (y < 0 || y >= 64) return;
+    if(y < 0 || y >= 64) return;
 
-    if (selected) {
+    if(selected) {
         canvas_set_color(canvas, ColorBlack);
         canvas_draw_box(canvas, 0, y, 122, LINE_HEIGHT);
         canvas_set_color(canvas, ColorWhite);
     }
 
     canvas_draw_str_aligned(canvas, 4, y + ITEM_PADDING, AlignLeft, AlignTop, text);
-    if (left_caret)
-        canvas_draw_str_aligned(canvas, 80, y + ITEM_PADDING, AlignLeft, AlignTop, "<");
+    if(left_caret) canvas_draw_str_aligned(canvas, 80, y + ITEM_PADDING, AlignLeft, AlignTop, "<");
     canvas_draw_str_aligned(canvas, 100, y + ITEM_PADDING, AlignCenter, AlignTop, value);
-    if (right_caret)
+    if(right_caret)
         canvas_draw_str_aligned(canvas, 120, y + ITEM_PADDING, AlignRight, AlignTop, ">");
 
     canvas_set_color(canvas, ColorBlack);
 }
 
-void settings_page(Canvas *const canvas, const GameState *gameState) {
+void settings_page(Canvas* const canvas, const GameState* gameState) {
     char drawChar[10];
     int startY = 0;
-    if (LINE_HEIGHT * (gameState->selectedMenu + 1) >= 64) {
+    if(LINE_HEIGHT * (gameState->selectedMenu + 1) >= 64) {
         startY -= (LINE_HEIGHT * (gameState->selectedMenu + 1)) - 64;
     }
 
     int scrollHeight = round(64 / 6.0) + ITEM_PADDING * 2;
     int scrollPos = 64 / (6.0 / (gameState->selectedMenu + 1)) - ITEM_PADDING * 2;
 
-
     canvas_set_color(canvas, ColorBlack);
     canvas_draw_box(canvas, 123, scrollPos, 4, scrollHeight);
     canvas_draw_box(canvas, 125, 0, 1, 64);
 
     snprintf(drawChar, sizeof(drawChar), "%li", gameState->settings.starting_money);
-    draw_menu(canvas, "Start money", drawChar,
-              0 * LINE_HEIGHT + startY,
-              gameState->settings.starting_money > gameState->settings.round_price,
-              gameState->settings.starting_money < 400,
-              gameState->selectedMenu == 0
-    );
+    draw_menu(
+        canvas,
+        "Start money",
+        drawChar,
+        0 * LINE_HEIGHT + startY,
+        gameState->settings.starting_money > gameState->settings.round_price,
+        gameState->settings.starting_money < 400,
+        gameState->selectedMenu == 0);
     snprintf(drawChar, sizeof(drawChar), "%li", gameState->settings.round_price);
-    draw_menu(canvas, "Round price", drawChar,
-              1 * LINE_HEIGHT + startY,
-              gameState->settings.round_price > 10,
-              gameState->settings.round_price < gameState->settings.starting_money,
-              gameState->selectedMenu == 1
-    );
+    draw_menu(
+        canvas,
+        "Round price",
+        drawChar,
+        1 * LINE_HEIGHT + startY,
+        gameState->settings.round_price > 10,
+        gameState->settings.round_price < gameState->settings.starting_money,
+        gameState->selectedMenu == 1);
 
     snprintf(drawChar, sizeof(drawChar), "%li", gameState->settings.animation_duration);
-    draw_menu(canvas, "Anim. length", drawChar,
-              2 * LINE_HEIGHT + startY,
-              gameState->settings.animation_duration > 0,
-              gameState->settings.animation_duration < 2000,
-              gameState->selectedMenu == 2
-    );
+    draw_menu(
+        canvas,
+        "Anim. length",
+        drawChar,
+        2 * LINE_HEIGHT + startY,
+        gameState->settings.animation_duration > 0,
+        gameState->settings.animation_duration < 2000,
+        gameState->selectedMenu == 2);
     snprintf(drawChar, sizeof(drawChar), "%li", gameState->settings.message_duration);
-    draw_menu(canvas, "Popup time", drawChar,
-              3 * LINE_HEIGHT + startY,
-              gameState->settings.message_duration > 0,
-              gameState->settings.message_duration < 2000,
-              gameState->selectedMenu == 3
-    );
-//    draw_menu(canvas, "Sound", gameState->settings.sound_effects ? "Yes" : "No",
-//              5 * LINE_HEIGHT + startY,
-//              true,
-//              true,
-//              gameState->selectedMenu == 5
-//    );
-
+    draw_menu(
+        canvas,
+        "Popup time",
+        drawChar,
+        3 * LINE_HEIGHT + startY,
+        gameState->settings.message_duration > 0,
+        gameState->settings.message_duration < 2000,
+        gameState->selectedMenu == 3);
+    //    draw_menu(canvas, "Sound", gameState->settings.sound_effects ? "Yes" : "No",
+    //              5 * LINE_HEIGHT + startY,
+    //              true,
+    //              true,
+    //              gameState->selectedMenu == 5
+    //    );
 }

+ 8 - 8
blackjack/ui.h

@@ -3,16 +3,16 @@
 #include "defines.h"
 #include <gui/gui.h>
 
-void draw_player_scene(Canvas *const canvas, const GameState *game_state);
+void draw_player_scene(Canvas* const canvas, const GameState* game_state);
 
-void draw_dealer_scene(Canvas *const canvas, const GameState *game_state);
+void draw_dealer_scene(Canvas* const canvas, const GameState* game_state);
 
-void draw_play_menu(Canvas *const canvas, const GameState *game_state);
+void draw_play_menu(Canvas* const canvas, const GameState* game_state);
 
-void draw_score(Canvas *const canvas, bool top, uint8_t amount);
+void draw_score(Canvas* const canvas, bool top, uint8_t amount);
 
-void draw_money(Canvas *const canvas, uint32_t score);
-void settings_page(Canvas *const canvas, const GameState * gameState);
+void draw_money(Canvas* const canvas, uint32_t score);
+void settings_page(Canvas* const canvas, const GameState* gameState);
 
-void popup_frame(Canvas *const canvas);
-void draw_screen(Canvas *const canvas, const bool* points);
+void popup_frame(Canvas* const canvas);
+void draw_screen(Canvas* const canvas, const bool* points);

+ 26 - 26
blackjack/util.c

@@ -1,16 +1,17 @@
 #include <storage/storage.h>
 #include "util.h"
 
-const char *CONFIG_FILE_PATH = APP_DATA_PATH("blackjack.settings");
+const char* CONFIG_FILE_PATH = APP_DATA_PATH("blackjack.settings");
 
 void save_settings(Settings settings) {
-    Storage *storage = furi_record_open(RECORD_STORAGE);
-    FlipperFormat *file = flipper_format_file_alloc(storage);
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    FlipperFormat* file = flipper_format_file_alloc(storage);
     FURI_LOG_D(APP_NAME, "Saving config");
-    if (flipper_format_file_open_existing(file, CONFIG_FILE_PATH)) {
-        FURI_LOG_D(APP_NAME, "Saving %s: %ld", CONF_ANIMATION_DURATION, settings.animation_duration);
-        flipper_format_update_uint32(file, CONF_ANIMATION_DURATION, &(settings.animation_duration), 1);
-
+    if(flipper_format_file_open_existing(file, CONFIG_FILE_PATH)) {
+        FURI_LOG_D(
+            APP_NAME, "Saving %s: %ld", CONF_ANIMATION_DURATION, settings.animation_duration);
+        flipper_format_update_uint32(
+            file, CONF_ANIMATION_DURATION, &(settings.animation_duration), 1);
 
         FURI_LOG_D(APP_NAME, "Saving %s: %ld", CONF_MESSAGE_DURATION, settings.message_duration);
         flipper_format_update_uint32(file, CONF_MESSAGE_DURATION, &(settings.message_duration), 1);
@@ -21,10 +22,10 @@ void save_settings(Settings settings) {
         FURI_LOG_D(APP_NAME, "Saving %s: %ld", CONF_ROUND_PRICE, settings.round_price);
         flipper_format_update_uint32(file, CONF_ROUND_PRICE, &(settings.round_price), 1);
 
-        FURI_LOG_D(APP_NAME, "Saving %s: %i", CONF_SOUND_EFFECTS, settings.sound_effects?1:0);
+        FURI_LOG_D(APP_NAME, "Saving %s: %i", CONF_SOUND_EFFECTS, settings.sound_effects ? 1 : 0);
         flipper_format_update_bool(file, CONF_SOUND_EFFECTS, &(settings.sound_effects), 1);
         FURI_LOG_D(APP_NAME, "Config saved");
-    }else{
+    } else {
         FURI_LOG_E(APP_NAME, "Save error");
     }
     flipper_format_file_close(file);
@@ -32,7 +33,7 @@ void save_settings(Settings settings) {
     furi_record_close(RECORD_STORAGE);
 }
 
-void save_settings_file(FlipperFormat *file, Settings *settings) {
+void save_settings_file(FlipperFormat* file, Settings* settings) {
     flipper_format_write_header_cstr(file, CONFIG_FILE_HEADER, CONFIG_FILE_VERSION);
     flipper_format_write_comment_cstr(file, "Card animation duration in ms");
     flipper_format_write_uint32(file, CONF_ANIMATION_DURATION, &(settings->animation_duration), 1);
@@ -57,59 +58,58 @@ Settings load_settings() {
     settings.sound_effects = true;
 
     FURI_LOG_D(APP_NAME, "Opening storage");
-    Storage *storage = furi_record_open(RECORD_STORAGE);
+    Storage* storage = furi_record_open(RECORD_STORAGE);
     storage_common_migrate(storage, EXT_PATH(".blackjack.settings"), CONFIG_FILE_PATH);
     FURI_LOG_D(APP_NAME, "Allocating file");
-    FlipperFormat *file = flipper_format_file_alloc(storage);
+    FlipperFormat* file = flipper_format_file_alloc(storage);
 
     FURI_LOG_D(APP_NAME, "Allocating string");
-    FuriString *string_value;
+    FuriString* string_value;
     string_value = furi_string_alloc();
 
-    if (storage_common_stat(storage, CONFIG_FILE_PATH, NULL) != FSE_OK) {
+    if(storage_common_stat(storage, CONFIG_FILE_PATH, NULL) != FSE_OK) {
         FURI_LOG_D(APP_NAME, "Config file %s not found, creating new one...", CONFIG_FILE_PATH);
-        if (!flipper_format_file_open_new(file, CONFIG_FILE_PATH)) {
+        if(!flipper_format_file_open_new(file, CONFIG_FILE_PATH)) {
             FURI_LOG_E(APP_NAME, "Error creating new file %s", CONFIG_FILE_PATH);
             flipper_format_file_close(file);
         } else {
             save_settings_file(file, &settings);
         }
     } else {
-        if (!flipper_format_file_open_existing(file, CONFIG_FILE_PATH)) {
+        if(!flipper_format_file_open_existing(file, CONFIG_FILE_PATH)) {
             FURI_LOG_E(APP_NAME, "Error opening existing file %s", CONFIG_FILE_PATH);
             flipper_format_file_close(file);
-        }
-        else {
+        } else {
             uint32_t value;
             bool valueBool;
             FURI_LOG_D(APP_NAME, "Checking version");
-            if (!flipper_format_read_header(file, string_value, &value)) {
+            if(!flipper_format_read_header(file, string_value, &value)) {
                 FURI_LOG_E(APP_NAME, "Config file mismatch");
             } else {
                 FURI_LOG_D(APP_NAME, "Loading %s", CONF_ANIMATION_DURATION);
-                if (flipper_format_read_uint32(file, CONF_ANIMATION_DURATION, &value, 1)) {
+                if(flipper_format_read_uint32(file, CONF_ANIMATION_DURATION, &value, 1)) {
                     settings.animation_duration = value;
                     FURI_LOG_D(APP_NAME, "Loaded %s: %ld", CONF_ANIMATION_DURATION, value);
                 }
                 FURI_LOG_D(APP_NAME, "Loading %s", CONF_MESSAGE_DURATION);
-                if (flipper_format_read_uint32(file, CONF_MESSAGE_DURATION, &value, 1)) {
+                if(flipper_format_read_uint32(file, CONF_MESSAGE_DURATION, &value, 1)) {
                     settings.message_duration = value;
                     FURI_LOG_D(APP_NAME, "Loaded %s: %ld", CONF_MESSAGE_DURATION, value);
                 }
                 FURI_LOG_D(APP_NAME, "Loading %s", CONF_STARTING_MONEY);
-                if (flipper_format_read_uint32(file, CONF_STARTING_MONEY, &value, 1)) {
+                if(flipper_format_read_uint32(file, CONF_STARTING_MONEY, &value, 1)) {
                     settings.starting_money = value;
                     FURI_LOG_D(APP_NAME, "Loaded %s: %ld", CONF_STARTING_MONEY, value);
                 }
                 FURI_LOG_D(APP_NAME, "Loading %s", CONF_ROUND_PRICE);
-                if (flipper_format_read_uint32(file, CONF_ROUND_PRICE, &value, 1)) {
+                if(flipper_format_read_uint32(file, CONF_ROUND_PRICE, &value, 1)) {
                     settings.round_price = value;
                     FURI_LOG_D(APP_NAME, "Loaded %s: %ld", CONF_ROUND_PRICE, value);
                 }
                 FURI_LOG_D(APP_NAME, "Loading %s", CONF_SOUND_EFFECTS);
-                if (flipper_format_read_bool(file, CONF_SOUND_EFFECTS, &valueBool, 1)) {
+                if(flipper_format_read_bool(file, CONF_SOUND_EFFECTS, &valueBool, 1)) {
                     settings.sound_effects = valueBool;
-                    FURI_LOG_D(APP_NAME, "Loaded %s: %i", CONF_ROUND_PRICE, valueBool?1:0);
+                    FURI_LOG_D(APP_NAME, "Loaded %s: %i", CONF_ROUND_PRICE, valueBool ? 1 : 0);
                 }
             }
             flipper_format_file_close(file);
@@ -117,7 +117,7 @@ Settings load_settings() {
     }
 
     furi_string_free(string_value);
-//        flipper_format_file_close(file);
+    //        flipper_format_file_close(file);
     flipper_format_free(file);
     furi_record_close(RECORD_STORAGE);
     return settings;

+ 20 - 17
bomberduck/bomberduck.c

@@ -21,7 +21,6 @@ int min(int a, int b) {
 #define WorldSizeY 6
 #define BombRange 1
 
-
 typedef struct {
     FuriMutex* mutex;
 } BomberState;
@@ -105,7 +104,7 @@ void init() {
         }
     }
     world.running = 1;
-    world.bombs_count =0;
+    world.bombs_count = 0;
     vibration = false;
     for(int j = max(0, player.y - BombRange); j < min(WorldSizeY, player.y + BombRange + 1); j++) {
         world.matrix[j][player.x] = 0;
@@ -191,7 +190,6 @@ static const NotificationSequence vibr1 = {
     NULL,
 };
 
-
 void intToStr(int num, char* str) {
     int i = 0, sign = 0;
 
@@ -344,7 +342,7 @@ static void draw_callback(Canvas* canvas, void* ctx) {
         if(world.player->x == world.endx && world.player->y == world.endy) {
             if(world.level == 20) {
                 canvas_draw_str(canvas, 30, 35, "You win!");
-            }else{
+            } else {
                 canvas_draw_str(canvas, 30, 35, "Next level!");
                 char str[20];
                 intToStr(world.level, str);
@@ -427,24 +425,24 @@ int32_t bomberduck_app(void* p) {
                 if(world.running) {
                     if(event.key == InputKeyUp) {
                         if(world.player->y > 0 &&
-                        world.matrix[world.player->y - 1][world.player->x] == 0)
+                           world.matrix[world.player->y - 1][world.player->x] == 0)
                             world.player->y--;
                     }
                     if(event.key == InputKeyDown) {
                         if(world.player->y < WorldSizeY - 1 &&
-                        world.matrix[world.player->y + 1][world.player->x] == 0)
+                           world.matrix[world.player->y + 1][world.player->x] == 0)
                             world.player->y++;
                     }
                     if(event.key == InputKeyLeft) {
                         world.player->side = 0;
                         if(world.player->x > 0 &&
-                        world.matrix[world.player->y][world.player->x - 1] == 0)
+                           world.matrix[world.player->y][world.player->x - 1] == 0)
                             world.player->x--;
                     }
                     if(event.key == InputKeyRight) {
                         world.player->side = 1;
                         if(world.player->x < WorldSizeX - 1 &&
-                        world.matrix[world.player->y][world.player->x + 1] == 0)
+                           world.matrix[world.player->y][world.player->x + 1] == 0)
                             world.player->x++;
                     }
                 }
@@ -459,7 +457,7 @@ int32_t bomberduck_app(void* p) {
                 notification_message(notification, &end);
                 world.running = 0;
                 world.level += 1;
-                if(world.level%5==0){
+                if(world.level % 5 == 0) {
                     dolphin_deed(DolphinDeedPluginGameWin);
                 }
             }
@@ -524,13 +522,18 @@ int32_t bomberduck_app(void* p) {
                         world.bombs[j] = world.bombs[j + 1];
                     }
                     world.bombs_count--;
-                } else if(furi_get_tick() - world.bombs[i].planted > (unsigned long)max((3000 - world.level * 150)*2/3, 666)&&world.matrix[world.bombs[i].y][world.bombs[i].x]!=5) {
-                        world.matrix[world.bombs[i].y][world.bombs[i].x] = 5;
-                        vibration=true;
-
-                } else if(furi_get_tick() - world.bombs[i].planted > (unsigned long)max((3000 - world.level * 150)/3, 333)&& world.matrix[world.bombs[i].y][world.bombs[i].x]!=4) {
-                        world.matrix[world.bombs[i].y][world.bombs[i].x] = 4;
-                    
+                } else if(
+                    furi_get_tick() - world.bombs[i].planted >
+                        (unsigned long)max((3000 - world.level * 150) * 2 / 3, 666) &&
+                    world.matrix[world.bombs[i].y][world.bombs[i].x] != 5) {
+                    world.matrix[world.bombs[i].y][world.bombs[i].x] = 5;
+                    vibration = true;
+
+                } else if(
+                    furi_get_tick() - world.bombs[i].planted >
+                        (unsigned long)max((3000 - world.level * 150) / 3, 333) &&
+                    world.matrix[world.bombs[i].y][world.bombs[i].x] != 4) {
+                    world.matrix[world.bombs[i].y][world.bombs[i].x] = 4;
                 }
             }
             for(int e = 0; e < world.enemies_count; e++) {
@@ -618,7 +621,7 @@ int32_t bomberduck_app(void* p) {
                     }
                 }
             }
-            if(vibration){
+            if(vibration) {
                 notification_message(notification, &vibr1);
             }
         }

+ 21 - 9
brainfuck/brainfuck.c

@@ -27,36 +27,46 @@ BFApp* brainfuck_alloc() {
     brainfuck->scene_manager = scene_manager_alloc(&brainfuck_scene_handlers, brainfuck);
     view_dispatcher_enable_queue(brainfuck->view_dispatcher);
     view_dispatcher_set_event_callback_context(brainfuck->view_dispatcher, brainfuck);
-    view_dispatcher_set_custom_event_callback(brainfuck->view_dispatcher, brainfuck_custom_event_callback);
-    view_dispatcher_set_navigation_event_callback(brainfuck->view_dispatcher, brainfuck_back_event_callback);
+    view_dispatcher_set_custom_event_callback(
+        brainfuck->view_dispatcher, brainfuck_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        brainfuck->view_dispatcher, brainfuck_back_event_callback);
 
     // Open GUI record
     brainfuck->gui = furi_record_open(RECORD_GUI);
-    view_dispatcher_attach_to_gui(brainfuck->view_dispatcher, brainfuck->gui, ViewDispatcherTypeFullscreen);
+    view_dispatcher_attach_to_gui(
+        brainfuck->view_dispatcher, brainfuck->gui, ViewDispatcherTypeFullscreen);
 
     // Open Notification record
     brainfuck->notifications = furi_record_open(RECORD_NOTIFICATION);
 
     // Submenu
     brainfuck->submenu = submenu_alloc();
-    view_dispatcher_add_view(brainfuck->view_dispatcher, brainfuckViewMenu, submenu_get_view(brainfuck->submenu));
+    view_dispatcher_add_view(
+        brainfuck->view_dispatcher, brainfuckViewMenu, submenu_get_view(brainfuck->submenu));
 
     // Popup
     brainfuck->popup = popup_alloc();
-    view_dispatcher_add_view(brainfuck->view_dispatcher, brainfuckViewPopup, popup_get_view(brainfuck->popup));
+    view_dispatcher_add_view(
+        brainfuck->view_dispatcher, brainfuckViewPopup, popup_get_view(brainfuck->popup));
 
     // Text Input
     brainfuck->text_input = text_input_alloc();
-    view_dispatcher_add_view(brainfuck->view_dispatcher, brainfuckViewTextInput, text_input_get_view(brainfuck->text_input));
+    view_dispatcher_add_view(
+        brainfuck->view_dispatcher,
+        brainfuckViewTextInput,
+        text_input_get_view(brainfuck->text_input));
 
     // Textbox
     brainfuck->text_box = text_box_alloc();
-    view_dispatcher_add_view(brainfuck->view_dispatcher, brainfuckViewTextBox, text_box_get_view(brainfuck->text_box)); 
+    view_dispatcher_add_view(
+        brainfuck->view_dispatcher, brainfuckViewTextBox, text_box_get_view(brainfuck->text_box));
     brainfuck->text_box_store = furi_string_alloc();
 
     // Dev environment
     brainfuck->BF_dev_env = bf_dev_env_alloc(brainfuck);
-    view_dispatcher_add_view(brainfuck->view_dispatcher, brainfuckViewDev, bf_dev_env_get_view(brainfuck->BF_dev_env));
+    view_dispatcher_add_view(
+        brainfuck->view_dispatcher, brainfuckViewDev, bf_dev_env_get_view(brainfuck->BF_dev_env));
 
     // File path
     brainfuck->BF_file_path = furi_string_alloc();
@@ -122,7 +132,9 @@ void brainfuck_show_loading_popup(void* context, bool show) {
 int32_t brainfuck_app(void* p) {
     UNUSED(p);
     BFApp* brainfuck = brainfuck_alloc();
-    if(!brainfuck){ return 0; }
+    if(!brainfuck) {
+        return 0;
+    }
 
     Storage* storage = furi_record_open(RECORD_STORAGE);
     storage_common_migrate(storage, EXT_PATH("brainfuck"), STORAGE_APP_DATA_PATH_PREFIX);

+ 0 - 1
brainfuck/brainfuck_i.h

@@ -89,4 +89,3 @@ typedef enum {
     brainfuckViewDev,
     brainfuckViewExec,
 } brainfuckView;
-

+ 0 - 1
brainfuck/scenes/brainfuck_scene_dev.c

@@ -14,4 +14,3 @@ bool brainfuck_scene_dev_env_on_event(void* context, SceneManagerEvent event) {
 void brainfuck_scene_dev_env_on_exit(void* context) {
     UNUSED(context);
 }
-

+ 5 - 9
brainfuck/scenes/brainfuck_scene_file_create.c

@@ -13,12 +13,7 @@ void brainfuck_scene_file_create_on_enter(void* context) {
 
     text_input_set_header_text(text_input, "New script name");
     text_input_set_result_callback(
-        text_input,
-        file_name_text_input_callback,
-        app,
-        tmpName,
-        64,
-        true);
+        text_input, file_name_text_input_callback, app, tmpName, 64, true);
 
     view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewTextInput);
 }
@@ -26,11 +21,11 @@ void brainfuck_scene_file_create_on_enter(void* context) {
 bool brainfuck_scene_file_create_on_event(void* context, SceneManagerEvent event) {
     BFApp* app = context;
     UNUSED(app);
-    
+
     bool consumed = false;
     if(event.type == SceneManagerEventTypeCustom) {
         if(event.event == brainfuckCustomEventTextInputDone) {
-            furi_string_cat_printf(app->BF_file_path, APP_DATA_PATH("%s.b"), tmpName);
+            furi_string_cat_printf(app->BF_file_path, APP_DATA_PATH("%s.b"), tmpName);
 
             //remove old file
             Storage* storage = furi_record_open(RECORD_STORAGE);
@@ -38,7 +33,8 @@ bool brainfuck_scene_file_create_on_event(void* context, SceneManagerEvent event
 
             //save new file
             Stream* stream = buffered_file_stream_alloc(storage);
-            buffered_file_stream_open(stream, furi_string_get_cstr(app->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS);
+            buffered_file_stream_open(
+                stream, furi_string_get_cstr(app->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS);
             stream_write(stream, (const uint8_t*)empty, 1);
             buffered_file_stream_close(stream);
 

+ 2 - 3
brainfuck/scenes/brainfuck_scene_file_select.c

@@ -15,11 +15,10 @@ void brainfuck_scene_file_select_on_enter(void* context) {
 
     bool selected = dialog_file_browser_show(dialogs, path, path, &browser_options);
 
-    if(selected){
+    if(selected) {
         furi_string_set(app->BF_file_path, path);
         scene_manager_next_scene(app->scene_manager, brainfuckSceneDevEnv);
-    }
-    else{
+    } else {
         scene_manager_search_and_switch_to_previous_scene(app->scene_manager, brainfuckSceneStart);
     }
 }

+ 4 - 8
brainfuck/scenes/brainfuck_scene_set_input.c

@@ -11,23 +11,19 @@ void brainfuck_scene_set_input_on_enter(void* context) {
 
     text_input_set_header_text(text_input, "Edit input buffer");
     text_input_set_result_callback(
-        text_input,
-        set_input_text_input_callback,
-        app,
-        app->inputBuffer,
-        64,
-        true);
+        text_input, set_input_text_input_callback, app, app->inputBuffer, 64, true);
 
     view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewTextInput);
 }
 
 bool brainfuck_scene_set_input_on_event(void* context, SceneManagerEvent event) {
     BFApp* app = context;
-    
+
     bool consumed = false;
     if(event.type == SceneManagerEventTypeCustom) {
         if(event.event == brainfuckCustomEventTextInputDone) {
-            scene_manager_search_and_switch_to_previous_scene(app->scene_manager, brainfuckSceneDevEnv);
+            scene_manager_search_and_switch_to_previous_scene(
+                app->scene_manager, brainfuckSceneDevEnv);
         }
     }
     return consumed;

+ 11 - 5
brainfuck/scenes/brainfuck_scene_start.c

@@ -13,11 +13,15 @@ void brainfuck_scene_start_on_enter(void* context) {
     BFApp* brainfuck = context;
 
     Submenu* submenu = brainfuck->submenu;
-    submenu_add_item(submenu, "New", SubmenuIndexNew, brainfuck_scene_start_submenu_callback, brainfuck);
-    submenu_add_item(submenu, "Open", SubmenuIndexOpen, brainfuck_scene_start_submenu_callback, brainfuck);
-    submenu_add_item(submenu, "About", SubmenuIndexAbout, brainfuck_scene_start_submenu_callback, brainfuck);
+    submenu_add_item(
+        submenu, "New", SubmenuIndexNew, brainfuck_scene_start_submenu_callback, brainfuck);
+    submenu_add_item(
+        submenu, "Open", SubmenuIndexOpen, brainfuck_scene_start_submenu_callback, brainfuck);
+    submenu_add_item(
+        submenu, "About", SubmenuIndexAbout, brainfuck_scene_start_submenu_callback, brainfuck);
 
-    submenu_set_selected_item(submenu, scene_manager_get_scene_state(brainfuck->scene_manager, brainfuckSceneStart));
+    submenu_set_selected_item(
+        submenu, scene_manager_get_scene_state(brainfuck->scene_manager, brainfuckSceneStart));
     view_dispatcher_switch_to_view(brainfuck->view_dispatcher, brainfuckViewMenu);
 }
 
@@ -33,7 +37,9 @@ bool brainfuck_scene_start_on_event(void* context, SceneManagerEvent event) {
             scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneFileSelect);
             consumed = true;
         } else if(event.event == SubmenuIndexAbout) {
-            text_box_set_text(brainfuck->text_box, "FlipperBrainfuck\n\nAn F0 brainfuck intepretor\nBy github.com/Nymda");
+            text_box_set_text(
+                brainfuck->text_box,
+                "FlipperBrainfuck\n\nAn F0 brainfuck intepretor\nBy github.com/Nymda");
             scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneExecEnv);
             consumed = true;
         }

+ 152 - 144
brainfuck/views/bf_dev_env.c

@@ -13,12 +13,12 @@ typedef struct {
     uint32_t col;
 } BFDevEnvModel;
 
-typedef struct{
+typedef struct {
     int up;
     int down;
     int left;
     int right;
-}bMapping;
+} bMapping;
 
 static bool bf_dev_process_up(BFDevEnv* devEnv);
 static bool bf_dev_process_down(BFDevEnv* devEnv);
@@ -27,7 +27,7 @@ static bool bf_dev_process_right(BFDevEnv* devEnv);
 static bool bf_dev_process_ok(BFDevEnv* devEnv, InputEvent* event);
 
 BFApp* appDev;
-FuriThread* workerThread; 
+FuriThread* workerThread;
 
 char bfChars[9] = {'<', '>', '[', ']', '+', '-', '.', ',', 0x00};
 
@@ -35,57 +35,59 @@ int selectedButton = 0;
 int saveNotifyCountdown = 0;
 int execCountdown = 0;
 
-char dspLine0[25] = { 0x00 };
-char dspLine1[25] = { 0x00 };
-char dspLine2[25] = { 0x00 };
+char dspLine0[25] = {0x00};
+char dspLine1[25] = {0x00};
+char dspLine2[25] = {0x00};
 
 static bMapping buttonMappings[12] = {
-    { 8,  8,  7,  1},  //0
-    { 8,  8,  0,  2},  //1
-    { 9,  9,  1,  3},  //2
-    { 9,  9,  2,  4},  //3
-    {10, 10,  3,  5},  //4
-    {10, 10,  4,  6},  //5
-    {11, 11,  5,  7},  //6
-    {11, 11,  6,  0},  //7
-
-    { 0,  0, 11,  9},  //8 
-    { 3,  3,  8, 10},  //9
-    { 5,  5,  9, 11},  //10
-    { 6,  6, 10,  8}   //11
+    {8, 8, 7, 1}, //0
+    {8, 8, 0, 2}, //1
+    {9, 9, 1, 3}, //2
+    {9, 9, 2, 4}, //3
+    {10, 10, 3, 5}, //4
+    {10, 10, 4, 6}, //5
+    {11, 11, 5, 7}, //6
+    {11, 11, 6, 0}, //7
+
+    {0, 0, 11, 9}, //8
+    {3, 3, 8, 10}, //9
+    {5, 5, 9, 11}, //10
+    {6, 6, 10, 8} //11
 };
 
 #define BT_X 14
 #define BT_Y 14
-static void bf_dev_draw_button(Canvas* canvas, int x, int y, bool selected, const char* lbl){
+static void bf_dev_draw_button(Canvas* canvas, int x, int y, bool selected, const char* lbl) {
     UNUSED(lbl);
 
-    if(selected){
+    if(selected) {
         canvas_draw_rbox(canvas, x, y, BT_X, BT_Y, 3);
         canvas_invert_color(canvas);
         canvas_set_font(canvas, FontBatteryPercent);
-        canvas_draw_str_aligned(canvas, x + (BT_X/2), y + (BT_Y/2) - 1, AlignCenter, AlignCenter, lbl);
+        canvas_draw_str_aligned(
+            canvas, x + (BT_X / 2), y + (BT_Y / 2) - 1, AlignCenter, AlignCenter, lbl);
         canvas_invert_color(canvas);
-    }
-    else{
+    } else {
         canvas_draw_rbox(canvas, x, y, BT_X, BT_Y, 3);
         canvas_invert_color(canvas);
-        canvas_draw_rbox(canvas, x+2, y-1, BT_X - 2, BT_Y - 1, 3);
+        canvas_draw_rbox(canvas, x + 2, y - 1, BT_X - 2, BT_Y - 1, 3);
         canvas_invert_color(canvas);
         canvas_draw_rframe(canvas, x, y, BT_X, BT_Y, 3);
         canvas_set_font(canvas, FontBatteryPercent);
-        canvas_draw_str_aligned(canvas, x + (BT_X/2), y + (BT_Y/2) - 1, AlignCenter, AlignCenter, lbl);
+        canvas_draw_str_aligned(
+            canvas, x + (BT_X / 2), y + (BT_Y / 2) - 1, AlignCenter, AlignCenter, lbl);
     }
 }
 
-void bf_save_changes(){
+void bf_save_changes() {
     //remove old file
     Storage* storage = furi_record_open(RECORD_STORAGE);
     storage_simply_remove(storage, furi_string_get_cstr(appDev->BF_file_path));
 
     //save new file
     Stream* stream = buffered_file_stream_alloc(storage);
-    buffered_file_stream_open(stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS);
+    buffered_file_stream_open(
+        stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS);
     stream_write(stream, (const uint8_t*)appDev->dataBuffer, appDev->dataSize);
     buffered_file_stream_close(stream);
 }
@@ -93,28 +95,35 @@ void bf_save_changes(){
 static void bf_dev_draw_callback(Canvas* canvas, void* _model) {
     UNUSED(_model);
 
-    if(saveNotifyCountdown > 0){
+    if(saveNotifyCountdown > 0) {
         canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignCenter, "SAVED");
         saveNotifyCountdown--;
         return;
     }
 
-    bf_dev_draw_button(canvas, 1,   36, (selectedButton == 0), "+");  //T 0
-    bf_dev_draw_button(canvas, 17,  36, (selectedButton == 1), "-");  //T 1
-    bf_dev_draw_button(canvas, 33,  36, (selectedButton == 2), "<");  //T 2
-    bf_dev_draw_button(canvas, 49,  36, (selectedButton == 3), ">");  //T 3
-    bf_dev_draw_button(canvas, 65,  36, (selectedButton == 4), "[");  //B 0
-    bf_dev_draw_button(canvas, 81,  36, (selectedButton == 5), "]");  //B 1
-    bf_dev_draw_button(canvas, 97,  36, (selectedButton == 6), ".");  //B 2
-    bf_dev_draw_button(canvas, 113, 36, (selectedButton == 7), ",");  //B 3
+    bf_dev_draw_button(canvas, 1, 36, (selectedButton == 0), "+"); //T 0
+    bf_dev_draw_button(canvas, 17, 36, (selectedButton == 1), "-"); //T 1
+    bf_dev_draw_button(canvas, 33, 36, (selectedButton == 2), "<"); //T 2
+    bf_dev_draw_button(canvas, 49, 36, (selectedButton == 3), ">"); //T 3
+    bf_dev_draw_button(canvas, 65, 36, (selectedButton == 4), "["); //B 0
+    bf_dev_draw_button(canvas, 81, 36, (selectedButton == 5), "]"); //B 1
+    bf_dev_draw_button(canvas, 97, 36, (selectedButton == 6), "."); //B 2
+    bf_dev_draw_button(canvas, 113, 36, (selectedButton == 7), ","); //B 3
 
     //backspace, input, run, save
-    canvas_draw_icon(canvas, 1, 52, (selectedButton == 8) ? &I_KeyBackspaceSelected_24x11 : &I_KeyBackspace_24x11);
-    canvas_draw_icon(canvas, 45, 52, (selectedButton == 9) ? &I_KeyInputSelected_30x11 : &I_KeyInput_30x11);
-    canvas_draw_icon(canvas, 77, 52, (selectedButton == 10) ? &I_KeyRunSelected_24x11 : &I_KeyRun_24x11);
-    canvas_draw_icon(canvas, 103, 52, (selectedButton == 11) ? &I_KeySaveSelected_24x11 : &I_KeySave_24x11);
-
-    if(saveNotifyCountdown > 0){
+    canvas_draw_icon(
+        canvas,
+        1,
+        52,
+        (selectedButton == 8) ? &I_KeyBackspaceSelected_24x11 : &I_KeyBackspace_24x11);
+    canvas_draw_icon(
+        canvas, 45, 52, (selectedButton == 9) ? &I_KeyInputSelected_30x11 : &I_KeyInput_30x11);
+    canvas_draw_icon(
+        canvas, 77, 52, (selectedButton == 10) ? &I_KeyRunSelected_24x11 : &I_KeyRun_24x11);
+    canvas_draw_icon(
+        canvas, 103, 52, (selectedButton == 11) ? &I_KeySaveSelected_24x11 : &I_KeySave_24x11);
+
+    if(saveNotifyCountdown > 0) {
         canvas_draw_icon(canvas, 98, 54, &I_ButtonRightSmall_3x5);
         saveNotifyCountdown--;
     }
@@ -125,10 +134,10 @@ static void bf_dev_draw_callback(Canvas* canvas, void* _model) {
     canvas_set_font(canvas, FontBatteryPercent);
 
     int dbOffset = 0;
-    if(appDev->dataSize > 72){
+    if(appDev->dataSize > 72) {
         dbOffset = (appDev->dataSize - 72);
     }
- 
+
     memset(dspLine0, 0x00, 25);
     memset(dspLine1, 0x00, 25);
     memset(dspLine2, 0x00, 25);
@@ -138,28 +147,25 @@ static void bf_dev_draw_callback(Canvas* canvas, void* _model) {
     int tp1 = 0;
     int tp2 = 0;
 
-    for(int p = dbOffset; p < appDev->dataSize; p++){
-        if(tpM < 24 * 1){
+    for(int p = dbOffset; p < appDev->dataSize; p++) {
+        if(tpM < 24 * 1) {
             dspLine0[tp0] = appDev->dataBuffer[p];
             tp0++;
-        }
-        else if(tpM < 24 * 2){
+        } else if(tpM < 24 * 2) {
             dspLine1[tp1] = appDev->dataBuffer[p];
             tp1++;
-        }
-        else if(tpM < 24 * 3){
+        } else if(tpM < 24 * 3) {
             dspLine2[tp2] = appDev->dataBuffer[p];
             tp2++;
         }
         tpM++;
     }
 
-    canvas_draw_str_aligned(canvas, 3,  8, AlignLeft, AlignCenter, dspLine0);
+    canvas_draw_str_aligned(canvas, 3, 8, AlignLeft, AlignCenter, dspLine0);
     canvas_draw_str_aligned(canvas, 3, 17, AlignLeft, AlignCenter, dspLine1);
     canvas_draw_str_aligned(canvas, 3, 26, AlignLeft, AlignCenter, dspLine2);
 }
 
-
 static bool bf_dev_input_callback(InputEvent* event, void* context) {
     furi_assert(context);
     BFDevEnv* devEnv = context;
@@ -210,113 +216,112 @@ static bool bf_dev_process_ok(BFDevEnv* devEnv, InputEvent* event) {
     UNUSED(devEnv);
     UNUSED(event);
 
-    if(event->type != InputTypePress){ return false; }
+    if(event->type != InputTypePress) {
+        return false;
+    }
 
-    switch(selectedButton){
-        case 0:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '+'; 
-                appDev->dataSize++; }
-            break;
+    switch(selectedButton) {
+    case 0: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '+';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 1:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '-'; 
-                appDev->dataSize++; }
-            break;
+    case 1: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '-';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 2:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '<'; 
-                appDev->dataSize++; }
-            break;
+    case 2: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '<';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 3:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '>'; 
-                appDev->dataSize++; }
-            break;
+    case 3: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '>';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 4:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '['; 
-                appDev->dataSize++; }
-            break;
+    case 4: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '[';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 5:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = ']'; 
-                appDev->dataSize++; }
-            break;
+    case 5: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = ']';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 6:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = '.'; 
-                appDev->dataSize++; }
-            break;
+    case 6: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = '.';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 7:
-        {
-            if(appDev->dataSize < BF_INST_BUFFER_SIZE){ 
-                appDev->dataBuffer[appDev->dataSize] = ','; 
-                appDev->dataSize++; }
-            break;
+    case 7: {
+        if(appDev->dataSize < BF_INST_BUFFER_SIZE) {
+            appDev->dataBuffer[appDev->dataSize] = ',';
+            appDev->dataSize++;
         }
+        break;
+    }
 
-        case 8:
-        {
-            if(appDev->dataSize > 0){
-                appDev->dataSize--; 
-                appDev->dataBuffer[appDev->dataSize] = (uint32_t)0x00;}
-            break;
+    case 8: {
+        if(appDev->dataSize > 0) {
+            appDev->dataSize--;
+            appDev->dataBuffer[appDev->dataSize] = (uint32_t)0x00;
         }
+        break;
+    }
 
-        case 9:
-        {
-            scene_manager_next_scene(appDev->scene_manager, brainfuckSceneSetInput);
-            break;
-        }
+    case 9: {
+        scene_manager_next_scene(appDev->scene_manager, brainfuckSceneSetInput);
+        break;
+    }
 
-        case 10:
-        {
-            if(getStatus() != 0){
-                killThread();
-                furi_thread_join(workerThread);
-            }
+    case 10: {
+        if(getStatus() != 0) {
+            killThread();
+            furi_thread_join(workerThread);
+        }
 
-            bf_save_changes();
+        bf_save_changes();
 
-            initWorker(appDev);
-            text_box_set_focus(appDev->text_box, TextBoxFocusEnd);
-            text_box_set_text(appDev->text_box, workerGetOutput());
+        initWorker(appDev);
+        text_box_set_focus(appDev->text_box, TextBoxFocusEnd);
+        text_box_set_text(appDev->text_box, workerGetOutput());
 
-            workerThread = furi_thread_alloc_ex("Worker", 2048, (void*)beginWorker, NULL);
-            furi_thread_start(workerThread);
+        workerThread = furi_thread_alloc_ex("Worker", 2048, (void*)beginWorker, NULL);
+        furi_thread_start(workerThread);
 
-            scene_manager_next_scene(appDev->scene_manager, brainfuckSceneExecEnv);
-            break;
-        }
+        scene_manager_next_scene(appDev->scene_manager, brainfuckSceneExecEnv);
+        break;
+    }
 
-        case 11:
-        {
-            bf_save_changes();
-            saveNotifyCountdown = 3;
-            break;
-        }
+    case 11: {
+        bf_save_changes();
+        saveNotifyCountdown = 3;
+        break;
+    }
     }
 
     bool consumed = false;
@@ -329,7 +334,7 @@ static void bf_dev_enter_callback(void* context) {
 
     with_view_model(
         devEnv->view,
-        BFDevEnvModel* model,
+        BFDevEnvModel * model,
         {
             model->col = 0;
             model->row = 0;
@@ -340,7 +345,7 @@ static void bf_dev_enter_callback(void* context) {
     selectedButton = 0;
 
     //exit the running thread if required
-    if(getStatus() != 0){
+    if(getStatus() != 0) {
         killThread();
         furi_thread_join(workerThread);
     }
@@ -351,11 +356,12 @@ static void bf_dev_enter_callback(void* context) {
     //open the file
     Storage* storage = furi_record_open(RECORD_STORAGE);
     Stream* stream = buffered_file_stream_alloc(storage);
-    buffered_file_stream_open(stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_READ, FSOM_OPEN_EXISTING);
+    buffered_file_stream_open(
+        stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_READ, FSOM_OPEN_EXISTING);
 
     //read into the buffer
     appDev->dataSize = stream_size(stream);
-    if(appDev->dataSize > 2000){
+    if(appDev->dataSize > 2000) {
         return; //BF file is too large
     }
 
@@ -363,15 +369,17 @@ static void bf_dev_enter_callback(void* context) {
     buffered_file_stream_close(stream);
 
     //replaces any invalid characters with an underscore. strips out newlines, comments, etc
-    for(int i = 0; i < appDev->dataSize; i++){
-        if(!strchr(bfChars, appDev->dataBuffer[i])){
+    for(int i = 0; i < appDev->dataSize; i++) {
+        if(!strchr(bfChars, appDev->dataBuffer[i])) {
             appDev->dataBuffer[i] = '_';
         }
     }
 
     //find the end of the file to begin editing
     int tptr = 0;
-    while(appDev->dataBuffer[tptr] != 0x00){ tptr++; }
+    while(appDev->dataBuffer[tptr] != 0x00) {
+        tptr++;
+    }
     appDev->dataSize = tptr;
 }
 
@@ -384,7 +392,7 @@ BFDevEnv* bf_dev_env_alloc(BFApp* appDev) {
 
     with_view_model(
         devEnv->view,
-        BFDevEnvModel* model,
+        BFDevEnvModel * model,
         {
             model->col = 0;
             model->row = 0;
@@ -399,7 +407,7 @@ BFDevEnv* bf_dev_env_alloc(BFApp* appDev) {
 }
 
 void bf_dev_env_free(BFDevEnv* devEnv) {
-    if(getStatus() != 0){
+    if(getStatus() != 0) {
         killThread();
         furi_thread_join(workerThread);
     }

+ 1 - 4
brainfuck/views/bf_dev_env.h

@@ -12,7 +12,4 @@ void bf_dev_env_free(BFDevEnv* devEnv);
 
 View* bf_dev_env_get_view(BFDevEnv* devEnv);
 
-void bf_dev_env_set_ok(
-    BFDevEnv* devEnv,
-    DevEnvOkCallback callback,
-    void* context);
+void bf_dev_env_set_ok(BFDevEnv* devEnv, DevEnvOkCallback callback, void* context);

+ 127 - 93
brainfuck/worker.c

@@ -24,50 +24,54 @@ int stackSizeReal = 0;
 
 BFApp* wrkrApp = 0;
 
-void killThread(){
+void killThread() {
     killswitch = true;
 }
 
-bool validateInstPtr(){
-    if(instPtr > instCount || instPtr < 0){
+bool validateInstPtr() {
+    if(instPtr > instCount || instPtr < 0) {
         return false;
     }
     return true;
 }
 
-bool validateStackPtr(){
-    if(stackPtr > stackSize || stackPtr < 0){
+bool validateStackPtr() {
+    if(stackPtr > stackSize || stackPtr < 0) {
         return false;
     }
     return true;
 }
 
-char* workerGetOutput(){
+char* workerGetOutput() {
     return wOutput;
 }
 
-int getStackSize(){
+int getStackSize() {
     return stackSizeReal;
 }
 
-int getOpCount(){
+int getOpCount() {
     return runOpCount;
 }
 
-int getStatus(){
+int getStatus() {
     return status;
 }
 
-void initWorker(BFApp* app){
+void initWorker(BFApp* app) {
     wrkrApp = app;
 
     //rebuild output
-    if(wOutput){ free(wOutput); }
+    if(wOutput) {
+        free(wOutput);
+    }
     wOutput = (char*)malloc(BF_OUTPUT_SIZE);
     wOutputPtr = 0;
 
     //rebuild stack
-    if(bfStack){ free(bfStack); }
+    if(bfStack) {
+        free(bfStack);
+    }
     bfStack = (uint8_t*)malloc(BF_STACK_INITIAL_SIZE);
     memset(bfStack, 0x00, BF_STACK_INITIAL_SIZE);
     stackSize = BF_STACK_INITIAL_SIZE;
@@ -88,16 +92,19 @@ void initWorker(BFApp* app){
     status = 0;
 }
 
-void rShift(){
+void rShift() {
     runOpCount++;
     stackPtr++;
-    if(!validateStackPtr()){ status = 2; return; }
+    if(!validateStackPtr()) {
+        status = 2;
+        return;
+    }
 
-    while(stackPtr > stackSize){
+    while(stackPtr > stackSize) {
         stackSize += BF_STACK_STEP_SIZE;
         void* tmp = realloc(bfStack, stackSize);
 
-        if(!tmp){ 
+        if(!tmp) {
             status = 2;
             return;
         }
@@ -105,72 +112,94 @@ void rShift(){
         memset((tmp + stackSize) - BF_STACK_STEP_SIZE, 0x00, BF_STACK_STEP_SIZE);
         bfStack = (uint8_t*)tmp;
     };
-    if(stackPtr > stackSizeReal){ 
-        stackSizeReal = stackPtr; 
+    if(stackPtr > stackSizeReal) {
+        stackSizeReal = stackPtr;
     }
 }
 
-void lShift(){
+void lShift() {
     runOpCount++;
     stackPtr--;
-    if(!validateStackPtr()){ status = 2; return; }
+    if(!validateStackPtr()) {
+        status = 2;
+        return;
+    }
 }
 
-void inc(){
+void inc() {
     runOpCount++;
-    if(!validateStackPtr()){ status = 2; return; }
+    if(!validateStackPtr()) {
+        status = 2;
+        return;
+    }
     bfStack[stackPtr]++;
 }
 
-void dec(){
+void dec() {
     runOpCount++;
-    if(!validateStackPtr()){ status = 2; return; }
+    if(!validateStackPtr()) {
+        status = 2;
+        return;
+    }
     bfStack[stackPtr]--;
 }
 
-void print(){
+void print() {
     runOpCount++;
     wOutput[wOutputPtr] = bfStack[stackPtr];
     wOutputPtr++;
-    if(wOutputPtr > (BF_OUTPUT_SIZE - 1)){ wOutputPtr = 0;}
+    if(wOutputPtr > (BF_OUTPUT_SIZE - 1)) {
+        wOutputPtr = 0;
+    }
 }
 
-void input(){
+void input() {
     runOpCount++;
-    
+
     bfStack[stackPtr] = (uint8_t)wInput[wInputPtr];
-    if(wInput[wInputPtr] == 0x00 || wInputPtr >= 64){
+    if(wInput[wInputPtr] == 0x00 || wInputPtr >= 64) {
         wInputPtr = 0;
-    }
-    else{
+    } else {
         wInputPtr++;
     }
 }
 
 void loop() {
     runOpCount++;
-	if (bfStack[stackPtr] == 0) {
-		int loopCount = 1;
-		while (loopCount > 0) {
-			instPtr++;
-            if(!validateInstPtr()){ status = 2; return; }
-			if (inst[instPtr] == '[') { loopCount++; }
-			else if (inst[instPtr] == ']') { loopCount--; }
-		}
-	}
+    if(bfStack[stackPtr] == 0) {
+        int loopCount = 1;
+        while(loopCount > 0) {
+            instPtr++;
+            if(!validateInstPtr()) {
+                status = 2;
+                return;
+            }
+            if(inst[instPtr] == '[') {
+                loopCount++;
+            } else if(inst[instPtr] == ']') {
+                loopCount--;
+            }
+        }
+    }
 }
 
 void endLoop() {
     runOpCount++;
-	if (bfStack[stackPtr] != 0) {
-		int loopCount = 1;
-		while (loopCount > 0) {
-			instPtr--;
-            if(!validateInstPtr()){ status = 2; return; }
-			if (inst[instPtr] == ']') { loopCount++; }
-			else if (inst[instPtr] == '[') { loopCount--; }
-		}
-	}
+    if(bfStack[stackPtr] != 0) {
+        int loopCount = 1;
+        while(loopCount > 0) {
+            instPtr--;
+            if(!validateInstPtr()) {
+                status = 2;
+                return;
+            }
+            if(inst[instPtr] == ']') {
+                loopCount++;
+            } else if(inst[instPtr] == '[') {
+                loopCount--;
+            }
+        }
+    }
 }
 
 static const NotificationSequence led_on = {
@@ -189,66 +218,71 @@ void input_kill(void* _ctx) {
     killswitch = true;
 }
 
-void beginWorker(){
+void beginWorker() {
     status = 1;
 
     //redefined from furi_hal_resources.c
     const GpioPin gpio_button_back = {.port = GPIOC, .pin = LL_GPIO_PIN_13};
 
-    while (inst[instPtr] != 0x00) {
-
-        if(runOpCount % 500 == 0){ 
-            text_box_set_text(wrkrApp->text_box, workerGetOutput()); 
+    while(inst[instPtr] != 0x00) {
+        if(runOpCount % 500 == 0) {
+            text_box_set_text(wrkrApp->text_box, workerGetOutput());
             notification_message(wrkrApp->notifications, &led_on);
         }
 
         //status 2 indicates failure
-        if(status == 2){ status = 0; break; }
+        if(status == 2) {
+            status = 0;
+            break;
+        }
 
         //read back button directly to avoid weirdness in furi
         if(killswitch || !furi_hal_gpio_read(&gpio_button_back)) {
-            status = 0; 
-            killswitch = false; 
-            break; 
+            status = 0;
+            killswitch = false;
+            break;
         }
 
-        switch (inst[instPtr]) {
-            case '>':
-                rShift();
-                break;
-            case '<':
-                lShift();
-                break;
-
-            case '+':
-                inc();
-                break;
-                
-            case '-':
-                dec();
-                break;
-                
-            case '.':
-                print();
-                break;
-            
-            case ',':
-                input();
-                break;
-                
-            case '[':
-                loop();
-                break;
-                
-            case ']':
-                endLoop();
-                break;
-                
-            default:
-                break;
+        switch(inst[instPtr]) {
+        case '>':
+            rShift();
+            break;
+        case '<':
+            lShift();
+            break;
+
+        case '+':
+            inc();
+            break;
+
+        case '-':
+            dec();
+            break;
+
+        case '.':
+            print();
+            break;
+
+        case ',':
+            input();
+            break;
+
+        case '[':
+            loop();
+            break;
+
+        case ']':
+            endLoop();
+            break;
+
+        default:
+            break;
         }
         instPtr++;
-        if(!validateInstPtr()){ status = 0; break; }
+        if(!validateInstPtr()) {
+            status = 0;
+            break;
+        }
     }
 
     notification_message(wrkrApp->notifications, &led_off);

+ 102 - 101
caesarcipher/caesar_cipher.c

@@ -21,130 +21,131 @@ typedef struct {
 } PluginEvent;
 
 typedef struct {
-  FuriMutex* mutex;
-  ViewDispatcher* view_dispatcher;
-  TextInput* text_input;
-  TextBox* text_box;
-  char input[TEXT_BUFFER_SIZE];
-  char output[(TEXT_BUFFER_SIZE*26) + (26)]; // linebreaks
+    FuriMutex* mutex;
+    ViewDispatcher* view_dispatcher;
+    TextInput* text_input;
+    TextBox* text_box;
+    char input[TEXT_BUFFER_SIZE];
+    char output[(TEXT_BUFFER_SIZE * 26) + (26)]; // linebreaks
 } CaesarState;
 
 static void string_to_uppercase(char* input) {
-  int i;
-  for (i=0; input[i] != '\0'; i++) {
-    if (input[i] >= 'a' && input[i] <= 'z') {
-      input[i] = input[i] - 32;
-    } else {
-      input[i] = input[i];
+    int i;
+    for(i = 0; input[i] != '\0'; i++) {
+        if(input[i] >= 'a' && input[i] <= 'z') {
+            input[i] = input[i] - 32;
+        } else {
+            input[i] = input[i];
+        }
     }
-  }
 }
 
 static void build_output(char* input, char* output) {
-  int out = 0;
-  for ( int rot = 1; rot < 26; rot++) {
-    int in;
-    for(in = 0; input[in] != '\0'; in++){
-      if (input[in] >= 'A' && input[in] <= 'Z') {
-        output[out] = 65 + ( ((input[in] - 65) + rot ) % 26);
-      } else {
-        output[out] = input[in];
-      }
-      out++;
+    int out = 0;
+    for(int rot = 1; rot < 26; rot++) {
+        int in;
+        for(in = 0; input[in] != '\0'; in++) {
+            if(input[in] >= 'A' && input[in] <= 'Z') {
+                output[out] = 65 + (((input[in] - 65) + rot) % 26);
+            } else {
+                output[out] = input[in];
+            }
+            out++;
+        }
+        output[out] = '\n';
+        out++;
     }
-    output[out]= '\n';
-    out++;
-  }
-  output[out]='\0';
+    output[out] = '\0';
 }
 
 static void text_input_callback(void* ctx) {
-  furi_assert(ctx);
-  CaesarState* caesar_state = ctx;
-  furi_mutex_acquire(caesar_state->mutex, FuriWaitForever);
-  FURI_LOG_D("caesar_cipher", "Input text: %s", caesar_state->input);
-  // this is where we build the output.
-  string_to_uppercase(caesar_state->input);
-  FURI_LOG_D("caesar_cipher", "Upper text: %s", caesar_state->input);
-  build_output(caesar_state->input, caesar_state->output);
-  text_box_set_text(caesar_state->text_box, caesar_state->output);
-  view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 1);
-
-  furi_mutex_release(caesar_state->mutex);
+    furi_assert(ctx);
+    CaesarState* caesar_state = ctx;
+    furi_mutex_acquire(caesar_state->mutex, FuriWaitForever);
+    FURI_LOG_D("caesar_cipher", "Input text: %s", caesar_state->input);
+    // this is where we build the output.
+    string_to_uppercase(caesar_state->input);
+    FURI_LOG_D("caesar_cipher", "Upper text: %s", caesar_state->input);
+    build_output(caesar_state->input, caesar_state->output);
+    text_box_set_text(caesar_state->text_box, caesar_state->output);
+    view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 1);
+
+    furi_mutex_release(caesar_state->mutex);
 }
 
-
 static bool back_event_callback(void* ctx) {
-  const CaesarState* caesar_state = ctx;
-  furi_mutex_acquire(caesar_state->mutex, FuriWaitForever);
-  view_dispatcher_stop(caesar_state->view_dispatcher);
-  furi_mutex_release(caesar_state->mutex);
-  return true;
+    const CaesarState* caesar_state = ctx;
+    furi_mutex_acquire(caesar_state->mutex, FuriWaitForever);
+    view_dispatcher_stop(caesar_state->view_dispatcher);
+    furi_mutex_release(caesar_state->mutex);
+    return true;
 }
 
 static void caesar_cipher_state_init(CaesarState* const caesar_state) {
-  caesar_state->view_dispatcher = view_dispatcher_alloc();
-  caesar_state->text_input = text_input_alloc();
-  caesar_state->text_box = text_box_alloc();
-  text_box_set_font(caesar_state->text_box, TextBoxFontText);
+    caesar_state->view_dispatcher = view_dispatcher_alloc();
+    caesar_state->text_input = text_input_alloc();
+    caesar_state->text_box = text_box_alloc();
+    text_box_set_font(caesar_state->text_box, TextBoxFontText);
 }
 
 static void caesar_cipher_state_free(CaesarState* const caesar_state) {
-  text_input_free(caesar_state->text_input);
-  text_box_free(caesar_state->text_box);
-  view_dispatcher_remove_view(caesar_state->view_dispatcher, 0);
-  view_dispatcher_remove_view(caesar_state->view_dispatcher, 1);
-  view_dispatcher_free(caesar_state->view_dispatcher);
-  free(caesar_state);
+    text_input_free(caesar_state->text_input);
+    text_box_free(caesar_state->text_box);
+    view_dispatcher_remove_view(caesar_state->view_dispatcher, 0);
+    view_dispatcher_remove_view(caesar_state->view_dispatcher, 1);
+    view_dispatcher_free(caesar_state->view_dispatcher);
+    free(caesar_state);
 }
 
 int32_t caesar_cipher_app() {
+    CaesarState* caesar_state = malloc(sizeof(CaesarState));
 
-  CaesarState* caesar_state = malloc(sizeof(CaesarState));
-  
-  FURI_LOG_D("caesar_cipher", "Running caesar_cipher_state_init");
-  caesar_cipher_state_init(caesar_state);
+    FURI_LOG_D("caesar_cipher", "Running caesar_cipher_state_init");
+    caesar_cipher_state_init(caesar_state);
 
-  caesar_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
-  if(!caesar_state->mutex) {
-    FURI_LOG_E("caesar_cipher", "cannot create mutex\r\n");
-    free(caesar_state);
-    return 255;
-  }
-
-  FURI_LOG_D("caesar_cipher", "Assigning text input callback");
-  text_input_set_result_callback(
-    caesar_state->text_input,
-    text_input_callback,
-    caesar_state,
-    caesar_state->input,
-    TEXT_BUFFER_SIZE,
-    //clear default text
-    true
-  );
-  text_input_set_header_text(caesar_state->text_input, "Input");
-
-  // Open GUI and register view_port
-  Gui* gui = furi_record_open("gui");
-  //gui_add_view_port(gui, view_port, GuiLayerFullscreen);
-  
-  FURI_LOG_D("caesar_cipher", "Enabling view dispatcher queue");
-  view_dispatcher_enable_queue(caesar_state->view_dispatcher);
-
-  FURI_LOG_D("caesar_cipher", "Adding text input view to dispatcher");
-  view_dispatcher_add_view(caesar_state->view_dispatcher, 0, text_input_get_view(caesar_state->text_input)); 
-  view_dispatcher_add_view(caesar_state->view_dispatcher, 1, text_box_get_view(caesar_state->text_box)); 
-  FURI_LOG_D("caesar_cipher", "Attaching view dispatcher to GUI");
-  view_dispatcher_attach_to_gui(caesar_state->view_dispatcher, gui, ViewDispatcherTypeFullscreen);
-  FURI_LOG_D("ceasar_cipher", "starting view dispatcher");
-  view_dispatcher_set_navigation_event_callback(caesar_state->view_dispatcher, back_event_callback);
-  view_dispatcher_set_event_callback_context(caesar_state->view_dispatcher, &state_mutex);
-  view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 0);
-  view_dispatcher_run(caesar_state->view_dispatcher);
-
-  furi_record_close("gui");
-  furi_mutex_free(caesar_state->mutex);
-  caesar_cipher_state_free(caesar_state);
-
-  return 0;
+    caesar_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    if(!caesar_state->mutex) {
+        FURI_LOG_E("caesar_cipher", "cannot create mutex\r\n");
+        free(caesar_state);
+        return 255;
+    }
+
+    FURI_LOG_D("caesar_cipher", "Assigning text input callback");
+    text_input_set_result_callback(
+        caesar_state->text_input,
+        text_input_callback,
+        caesar_state,
+        caesar_state->input,
+        TEXT_BUFFER_SIZE,
+        //clear default text
+        true);
+    text_input_set_header_text(caesar_state->text_input, "Input");
+
+    // Open GUI and register view_port
+    Gui* gui = furi_record_open("gui");
+    //gui_add_view_port(gui, view_port, GuiLayerFullscreen);
+
+    FURI_LOG_D("caesar_cipher", "Enabling view dispatcher queue");
+    view_dispatcher_enable_queue(caesar_state->view_dispatcher);
+
+    FURI_LOG_D("caesar_cipher", "Adding text input view to dispatcher");
+    view_dispatcher_add_view(
+        caesar_state->view_dispatcher, 0, text_input_get_view(caesar_state->text_input));
+    view_dispatcher_add_view(
+        caesar_state->view_dispatcher, 1, text_box_get_view(caesar_state->text_box));
+    FURI_LOG_D("caesar_cipher", "Attaching view dispatcher to GUI");
+    view_dispatcher_attach_to_gui(
+        caesar_state->view_dispatcher, gui, ViewDispatcherTypeFullscreen);
+    FURI_LOG_D("ceasar_cipher", "starting view dispatcher");
+    view_dispatcher_set_navigation_event_callback(
+        caesar_state->view_dispatcher, back_event_callback);
+    view_dispatcher_set_event_callback_context(caesar_state->view_dispatcher, &state_mutex);
+    view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 0);
+    view_dispatcher_run(caesar_state->view_dispatcher);
+
+    furi_record_close("gui");
+    furi_mutex_free(caesar_state->mutex);
+    caesar_cipher_state_free(caesar_state);
+
+    return 0;
 }

+ 0 - 1
cli_bridge/console_output.c

@@ -9,5 +9,4 @@ void console_output_input_handler(CliguiApp* app, InputEvent* event) {
         char eot = 0x03;
         furi_stream_buffer_send(app->data->streams.app_tx, &eot, 1, FuriWaitForever);
     }
-    
 }

+ 2 - 1
cli_bridge/text_input.c

@@ -26,7 +26,8 @@ void text_input_input_handler(CliguiApp* app, InputEvent* event) {
         app->text_input_store[len] = ' ';
         app->text_input_store[len + 1] = 0;
     }
-    if(event->type == InputTypeLong && (event->key == InputKeyLeft || event->key == InputKeyRight)) {
+    if(event->type == InputTypeLong &&
+       (event->key == InputKeyLeft || event->key == InputKeyRight)) {
         view_dispatcher_switch_to_view(app->view_dispatcher, ViewConsoleOutput);
         app->data->state = ViewConsoleOutput;
     }

+ 1 - 1
cntdown_timer/utils/utils.h

@@ -7,6 +7,6 @@ void notification_beep_once();
 void notification_off();
 void notification_timeup();
 
-void parse_sec_to_time_str(char *buffer, size_t len, int32_t sec);
+void parse_sec_to_time_str(char* buffer, size_t len, int32_t sec);
 
 #endif // __UTILS_H__

+ 8 - 8
esubghz_chat/bgloader_api.h

@@ -4,18 +4,18 @@
 #define APP_BASE_ARGS "run_in_background"
 
 typedef enum {
-	BGLoaderMessageType_AppReattached,
-	BGLoaderMessageType_LoaderBackground,
-	BGLoaderMessageType_LoaderExit,
+    BGLoaderMessageType_AppReattached,
+    BGLoaderMessageType_LoaderBackground,
+    BGLoaderMessageType_LoaderExit,
 } BGLoaderMessageType;
 
 typedef struct {
-	BGLoaderMessageType type;
+    BGLoaderMessageType type;
 } BGLoaderMessage;
 
 typedef struct {
-	FlipperApplication *fap;
-	FuriThread *thread;
-	FuriMessageQueue *to_app;
-	FuriMessageQueue *to_loader;
+    FlipperApplication* fap;
+    FuriThread* thread;
+    FuriMessageQueue* to_app;
+    FuriMessageQueue* to_loader;
 } BGLoaderApp;

+ 251 - 294
esubghz_chat/crypto/aes.c

@@ -22,8 +22,8 @@
 
 #include "aes.h"
 
-static int aes_tables_inited = 0;   // run-once flag for performing key
-                                    // expasion table generation (see below)
+static int aes_tables_inited = 0; // run-once flag for performing key
+    // expasion table generation (see below)
 /*
  *  The following static local tables must be filled-in before the first use of
  *  the GCM or AES ciphers. They are used for the AES key expansion/scheduling
@@ -37,99 +37,94 @@ static int aes_tables_inited = 0;   // run-once flag for performing key
  *  the GCM input, we ONLY NEED AES encryption.  Thus, to save space AES
  *  decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  */
-                            // We always need our forward tables
-static uchar FSb[256];      // Forward substitution box (FSb)
-static uint32_t FT0[256];   // Forward key schedule assembly tables
+// We always need our forward tables
+static uchar FSb[256]; // Forward substitution box (FSb)
+static uint32_t FT0[256]; // Forward key schedule assembly tables
 static uint32_t FT1[256];
 static uint32_t FT2[256];
 static uint32_t FT3[256];
 
-#if AES_DECRYPTION          // We ONLY need reverse for decryption
-static uchar RSb[256];      // Reverse substitution box (RSb)
-static uint32_t RT0[256];   // Reverse key schedule assembly tables
+#if AES_DECRYPTION // We ONLY need reverse for decryption
+static uchar RSb[256]; // Reverse substitution box (RSb)
+static uint32_t RT0[256]; // Reverse key schedule assembly tables
 static uint32_t RT1[256];
 static uint32_t RT2[256];
 static uint32_t RT3[256];
-#endif                      /* AES_DECRYPTION */
+#endif /* AES_DECRYPTION */
 
-static uint32_t RCON[10];   // AES round constants
+static uint32_t RCON[10]; // AES round constants
 
 /* 
  * Platform Endianness Neutralizing Load and Store Macro definitions
  * AES wants platform-neutral Little Endian (LE) byte ordering
  */
-#define GET_UINT32_LE(n,b,i) {                  \
-    (n) = ( (uint32_t) (b)[(i)    ]       )     \
-        | ( (uint32_t) (b)[(i) + 1] <<  8 )     \
-        | ( (uint32_t) (b)[(i) + 2] << 16 )     \
-        | ( (uint32_t) (b)[(i) + 3] << 24 ); }
-
-#define PUT_UINT32_LE(n,b,i) {                  \
-    (b)[(i)    ] = (uchar) ( (n)       );       \
-    (b)[(i) + 1] = (uchar) ( (n) >>  8 );       \
-    (b)[(i) + 2] = (uchar) ( (n) >> 16 );       \
-    (b)[(i) + 3] = (uchar) ( (n) >> 24 ); }
+#define GET_UINT32_LE(n, b, i)                                                 \
+    {                                                                          \
+        (n) = ((uint32_t)(b)[(i)]) | ((uint32_t)(b)[(i) + 1] << 8) |           \
+              ((uint32_t)(b)[(i) + 2] << 16) | ((uint32_t)(b)[(i) + 3] << 24); \
+    }
+
+#define PUT_UINT32_LE(n, b, i)             \
+    {                                      \
+        (b)[(i)] = (uchar)((n));           \
+        (b)[(i) + 1] = (uchar)((n) >> 8);  \
+        (b)[(i) + 2] = (uchar)((n) >> 16); \
+        (b)[(i) + 3] = (uchar)((n) >> 24); \
+    }
 
 /*
  *  AES forward and reverse encryption round processing macros
  */
-#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)     \
-{                                               \
-    X0 = *RK++ ^ FT0[ ( Y0       ) & 0xFF ] ^   \
-                 FT1[ ( Y1 >>  8 ) & 0xFF ] ^   \
-                 FT2[ ( Y2 >> 16 ) & 0xFF ] ^   \
-                 FT3[ ( Y3 >> 24 ) & 0xFF ];    \
-                                                \
-    X1 = *RK++ ^ FT0[ ( Y1       ) & 0xFF ] ^   \
-                 FT1[ ( Y2 >>  8 ) & 0xFF ] ^   \
-                 FT2[ ( Y3 >> 16 ) & 0xFF ] ^   \
-                 FT3[ ( Y0 >> 24 ) & 0xFF ];    \
-                                                \
-    X2 = *RK++ ^ FT0[ ( Y2       ) & 0xFF ] ^   \
-                 FT1[ ( Y3 >>  8 ) & 0xFF ] ^   \
-                 FT2[ ( Y0 >> 16 ) & 0xFF ] ^   \
-                 FT3[ ( Y1 >> 24 ) & 0xFF ];    \
-                                                \
-    X3 = *RK++ ^ FT0[ ( Y3       ) & 0xFF ] ^   \
-                 FT1[ ( Y0 >>  8 ) & 0xFF ] ^   \
-                 FT2[ ( Y1 >> 16 ) & 0xFF ] ^   \
-                 FT3[ ( Y2 >> 24 ) & 0xFF ];    \
-}
+#define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3)                                     \
+    {                                                                                  \
+        X0 = *RK++ ^ FT0[(Y0)&0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ FT2[(Y2 >> 16) & 0xFF] ^ \
+             FT3[(Y3 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X1 = *RK++ ^ FT0[(Y1)&0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ FT2[(Y3 >> 16) & 0xFF] ^ \
+             FT3[(Y0 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X2 = *RK++ ^ FT0[(Y2)&0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ FT2[(Y0 >> 16) & 0xFF] ^ \
+             FT3[(Y1 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X3 = *RK++ ^ FT0[(Y3)&0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ FT2[(Y1 >> 16) & 0xFF] ^ \
+             FT3[(Y2 >> 24) & 0xFF];                                                   \
+    }
 
-#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)     \
-{                                               \
-    X0 = *RK++ ^ RT0[ ( Y0       ) & 0xFF ] ^   \
-                 RT1[ ( Y3 >>  8 ) & 0xFF ] ^   \
-                 RT2[ ( Y2 >> 16 ) & 0xFF ] ^   \
-                 RT3[ ( Y1 >> 24 ) & 0xFF ];    \
-                                                \
-    X1 = *RK++ ^ RT0[ ( Y1       ) & 0xFF ] ^   \
-                 RT1[ ( Y0 >>  8 ) & 0xFF ] ^   \
-                 RT2[ ( Y3 >> 16 ) & 0xFF ] ^   \
-                 RT3[ ( Y2 >> 24 ) & 0xFF ];    \
-                                                \
-    X2 = *RK++ ^ RT0[ ( Y2       ) & 0xFF ] ^   \
-                 RT1[ ( Y1 >>  8 ) & 0xFF ] ^   \
-                 RT2[ ( Y0 >> 16 ) & 0xFF ] ^   \
-                 RT3[ ( Y3 >> 24 ) & 0xFF ];    \
-                                                \
-    X3 = *RK++ ^ RT0[ ( Y3       ) & 0xFF ] ^   \
-                 RT1[ ( Y2 >>  8 ) & 0xFF ] ^   \
-                 RT2[ ( Y1 >> 16 ) & 0xFF ] ^   \
-                 RT3[ ( Y0 >> 24 ) & 0xFF ];    \
-}
+#define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3)                                     \
+    {                                                                                  \
+        X0 = *RK++ ^ RT0[(Y0)&0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ RT2[(Y2 >> 16) & 0xFF] ^ \
+             RT3[(Y1 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X1 = *RK++ ^ RT0[(Y1)&0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ RT2[(Y3 >> 16) & 0xFF] ^ \
+             RT3[(Y2 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X2 = *RK++ ^ RT0[(Y2)&0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ RT2[(Y0 >> 16) & 0xFF] ^ \
+             RT3[(Y3 >> 24) & 0xFF];                                                   \
+                                                                                       \
+        X3 = *RK++ ^ RT0[(Y3)&0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ RT2[(Y1 >> 16) & 0xFF] ^ \
+             RT3[(Y0 >> 24) & 0xFF];                                                   \
+    }
 
 /*
  *  These macros improve the readability of the key
  *  generation initialization code by collapsing
  *  repetitive common operations into logical pieces.
  */
-#define ROTL8(x) ( ( x << 8 ) & 0xFFFFFFFF ) | ( x >> 24 )
-#define XTIME(x) ( ( x << 1 ) ^ ( ( x & 0x80 ) ? 0x1B : 0x00 ) )
-#define MUL(x,y) ( ( x && y ) ? pow[(log[x]+log[y]) % 255] : 0 )
-#define MIX(x,y) { y = ( (y << 1) | (y >> 7) ) & 0xFF; x ^= y; }
-#define CPY128   { *RK++ = *SK++; *RK++ = *SK++; \
-                   *RK++ = *SK++; *RK++ = *SK++; }
+#define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
+#define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
+#define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
+#define MIX(x, y)                         \
+    {                                     \
+        y = ((y << 1) | (y >> 7)) & 0xFF; \
+        x ^= y;                           \
+    }
+#define CPY128         \
+    {                  \
+        *RK++ = *SK++; \
+        *RK++ = *SK++; \
+        *RK++ = *SK++; \
+        *RK++ = *SK++; \
+    }
 
 /******************************************************************************
  *
@@ -141,71 +136,66 @@ static uint32_t RCON[10];   // AES round constants
  *  at system initialization to setup the tables for all subsequent use.
  *
  ******************************************************************************/
-void aes_init_keygen_tables( void )
-{
-    int i, x, y, z;     // general purpose iteration and computation locals
+void aes_init_keygen_tables(void) {
+    int i, x, y, z; // general purpose iteration and computation locals
     int pow[256];
     int log[256];
 
-    if (aes_tables_inited) return;
+    if(aes_tables_inited) return;
 
     // fill the 'pow' and 'log' tables over GF(2^8)
-    for( i = 0, x = 1; i < 256; i++ )   {
+    for(i = 0, x = 1; i < 256; i++) {
         pow[i] = x;
         log[x] = i;
-        x = ( x ^ XTIME( x ) ) & 0xFF;
+        x = (x ^ XTIME(x)) & 0xFF;
     }
     // compute the round constants
-    for( i = 0, x = 1; i < 10; i++ )    {
-        RCON[i] = (uint32_t) x;
-        x = XTIME( x ) & 0xFF;
+    for(i = 0, x = 1; i < 10; i++) {
+        RCON[i] = (uint32_t)x;
+        x = XTIME(x) & 0xFF;
     }
     // fill the forward and reverse substitution boxes
     FSb[0x00] = 0x63;
-#if AES_DECRYPTION  // whether AES decryption is supported
+#if AES_DECRYPTION // whether AES decryption is supported
     RSb[0x63] = 0x00;
 #endif /* AES_DECRYPTION */
 
-    for( i = 1; i < 256; i++ )          {
+    for(i = 1; i < 256; i++) {
         x = y = pow[255 - log[i]];
-        MIX(x,y);
-        MIX(x,y);
-        MIX(x,y);
-        MIX(x,y); 
-        FSb[i] = (uchar) ( x ^= 0x63 );
-#if AES_DECRYPTION  // whether AES decryption is supported
-        RSb[x] = (uchar) i;
+        MIX(x, y);
+        MIX(x, y);
+        MIX(x, y);
+        MIX(x, y);
+        FSb[i] = (uchar)(x ^= 0x63);
+#if AES_DECRYPTION // whether AES decryption is supported
+        RSb[x] = (uchar)i;
 #endif /* AES_DECRYPTION */
-
     }
     // generate the forward and reverse key expansion tables
-    for( i = 0; i < 256; i++ )          {
+    for(i = 0; i < 256; i++) {
         x = FSb[i];
-        y = XTIME( x ) & 0xFF;
-        z =  ( y ^ x ) & 0xFF;
+        y = XTIME(x) & 0xFF;
+        z = (y ^ x) & 0xFF;
 
-        FT0[i] = ( (uint32_t) y       ) ^ ( (uint32_t) x <<  8 ) ^
-                 ( (uint32_t) x << 16 ) ^ ( (uint32_t) z << 24 );
+        FT0[i] = ((uint32_t)y) ^ ((uint32_t)x << 8) ^ ((uint32_t)x << 16) ^ ((uint32_t)z << 24);
 
-        FT1[i] = ROTL8( FT0[i] );
-        FT2[i] = ROTL8( FT1[i] );
-        FT3[i] = ROTL8( FT2[i] );
+        FT1[i] = ROTL8(FT0[i]);
+        FT2[i] = ROTL8(FT1[i]);
+        FT3[i] = ROTL8(FT2[i]);
 
-#if AES_DECRYPTION  // whether AES decryption is supported
+#if AES_DECRYPTION // whether AES decryption is supported
         x = RSb[i];
 
-        RT0[i] = ( (uint32_t) MUL( 0x0E, x )       ) ^
-                 ( (uint32_t) MUL( 0x09, x ) <<  8 ) ^
-                 ( (uint32_t) MUL( 0x0D, x ) << 16 ) ^
-                 ( (uint32_t) MUL( 0x0B, x ) << 24 );
+        RT0[i] = ((uint32_t)MUL(0x0E, x)) ^ ((uint32_t)MUL(0x09, x) << 8) ^
+                 ((uint32_t)MUL(0x0D, x) << 16) ^ ((uint32_t)MUL(0x0B, x) << 24);
 
-        RT1[i] = ROTL8( RT0[i] );
-        RT2[i] = ROTL8( RT1[i] );
-        RT3[i] = ROTL8( RT2[i] );
+        RT1[i] = ROTL8(RT0[i]);
+        RT2[i] = ROTL8(RT1[i]);
+        RT3[i] = ROTL8(RT2[i]);
 #endif /* AES_DECRYPTION */
     }
-    aes_tables_inited = 1;  // flag that the tables have been generated
-}                           // to permit subsequent use of the AES cipher
+    aes_tables_inited = 1; // flag that the tables have been generated
+} // to permit subsequent use of the AES cipher
 
 /******************************************************************************
  *
@@ -217,80 +207,72 @@ void aes_init_keygen_tables( void )
  *  Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  *
  ******************************************************************************/
-int aes_set_encryption_key( aes_context *ctx,
-                            const uchar *key,
-                            uint keysize )
-{
-    uint i;                 // general purpose iteration local
-    uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
+int aes_set_encryption_key(aes_context* ctx, const uchar* key, uint keysize) {
+    uint i; // general purpose iteration local
+    uint32_t* RK = ctx->rk; // initialize our RoundKey buffer pointer
 
-    for( i = 0; i < (keysize >> 2); i++ ) {
-        GET_UINT32_LE( RK[i], key, i << 2 );
+    for(i = 0; i < (keysize >> 2); i++) {
+        GET_UINT32_LE(RK[i], key, i << 2);
     }
 
-    switch( ctx->rounds )
-    {
-        case 10:
-            for( i = 0; i < 10; i++, RK += 4 ) {
-                RK[4]  = RK[0] ^ RCON[i] ^
-                ( (uint32_t) FSb[ ( RK[3] >>  8 ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( RK[3] >> 16 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( RK[3]       ) & 0xFF ] << 24 );
-
-                RK[5]  = RK[1] ^ RK[4];
-                RK[6]  = RK[2] ^ RK[5];
-                RK[7]  = RK[3] ^ RK[6];
-            }
-            break;
-
-        case 12:
-            for( i = 0; i < 8; i++, RK += 6 ) {
-                RK[6]  = RK[0] ^ RCON[i] ^
-                ( (uint32_t) FSb[ ( RK[5] >>  8 ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( RK[5] >> 16 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( RK[5]       ) & 0xFF ] << 24 );
-
-                RK[7]  = RK[1] ^ RK[6];
-                RK[8]  = RK[2] ^ RK[7];
-                RK[9]  = RK[3] ^ RK[8];
-                RK[10] = RK[4] ^ RK[9];
-                RK[11] = RK[5] ^ RK[10];
-            }
-            break;
-
-        case 14:
-            for( i = 0; i < 7; i++, RK += 8 ) {
-                RK[8]  = RK[0] ^ RCON[i] ^
-                ( (uint32_t) FSb[ ( RK[7] >>  8 ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( RK[7] >> 16 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( RK[7]       ) & 0xFF ] << 24 );
-
-                RK[9]  = RK[1] ^ RK[8];
-                RK[10] = RK[2] ^ RK[9];
-                RK[11] = RK[3] ^ RK[10];
-
-                RK[12] = RK[4] ^
-                ( (uint32_t) FSb[ ( RK[11]       ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( RK[11] >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 );
-
-                RK[13] = RK[5] ^ RK[12];
-                RK[14] = RK[6] ^ RK[13];
-                RK[15] = RK[7] ^ RK[14];
-            }
-            break;
-
-	default:
-	    return -1;
+    switch(ctx->rounds) {
+    case 10:
+        for(i = 0; i < 10; i++, RK += 4) {
+            RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t)FSb[(RK[3] >> 8) & 0xFF]) ^
+                    ((uint32_t)FSb[(RK[3] >> 16) & 0xFF] << 8) ^
+                    ((uint32_t)FSb[(RK[3] >> 24) & 0xFF] << 16) ^
+                    ((uint32_t)FSb[(RK[3]) & 0xFF] << 24);
+
+            RK[5] = RK[1] ^ RK[4];
+            RK[6] = RK[2] ^ RK[5];
+            RK[7] = RK[3] ^ RK[6];
+        }
+        break;
+
+    case 12:
+        for(i = 0; i < 8; i++, RK += 6) {
+            RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t)FSb[(RK[5] >> 8) & 0xFF]) ^
+                    ((uint32_t)FSb[(RK[5] >> 16) & 0xFF] << 8) ^
+                    ((uint32_t)FSb[(RK[5] >> 24) & 0xFF] << 16) ^
+                    ((uint32_t)FSb[(RK[5]) & 0xFF] << 24);
+
+            RK[7] = RK[1] ^ RK[6];
+            RK[8] = RK[2] ^ RK[7];
+            RK[9] = RK[3] ^ RK[8];
+            RK[10] = RK[4] ^ RK[9];
+            RK[11] = RK[5] ^ RK[10];
+        }
+        break;
+
+    case 14:
+        for(i = 0; i < 7; i++, RK += 8) {
+            RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t)FSb[(RK[7] >> 8) & 0xFF]) ^
+                    ((uint32_t)FSb[(RK[7] >> 16) & 0xFF] << 8) ^
+                    ((uint32_t)FSb[(RK[7] >> 24) & 0xFF] << 16) ^
+                    ((uint32_t)FSb[(RK[7]) & 0xFF] << 24);
+
+            RK[9] = RK[1] ^ RK[8];
+            RK[10] = RK[2] ^ RK[9];
+            RK[11] = RK[3] ^ RK[10];
+
+            RK[12] = RK[4] ^ ((uint32_t)FSb[(RK[11]) & 0xFF]) ^
+                     ((uint32_t)FSb[(RK[11] >> 8) & 0xFF] << 8) ^
+                     ((uint32_t)FSb[(RK[11] >> 16) & 0xFF] << 16) ^
+                     ((uint32_t)FSb[(RK[11] >> 24) & 0xFF] << 24);
+
+            RK[13] = RK[5] ^ RK[12];
+            RK[14] = RK[6] ^ RK[13];
+            RK[15] = RK[7] ^ RK[14];
+        }
+        break;
+
+    default:
+        return -1;
     }
-    return( 0 );
+    return (0);
 }
 
-#if AES_DECRYPTION  // whether AES decryption is supported
+#if AES_DECRYPTION // whether AES decryption is supported
 
 /******************************************************************************
  *
@@ -302,37 +284,31 @@ int aes_set_encryption_key( aes_context *ctx,
  *  length in bits. Valid lengths are: 128, 192, or 256 bits.
  *
  ******************************************************************************/
-int aes_set_decryption_key( aes_context *ctx,
-                            const uchar *key,
-                            uint keysize )
-{
+int aes_set_decryption_key(aes_context* ctx, const uchar* key, uint keysize) {
     int i, j;
-    aes_context cty;            // a calling aes context for set_encryption_key
-    uint32_t *RK = ctx->rk;     // initialize our RoundKey buffer pointer
-    uint32_t *SK;
+    aes_context cty; // a calling aes context for set_encryption_key
+    uint32_t* RK = ctx->rk; // initialize our RoundKey buffer pointer
+    uint32_t* SK;
     int ret;
 
-    cty.rounds = ctx->rounds;   // initialize our local aes context
-    cty.rk = cty.buf;           // round count and key buf pointer
+    cty.rounds = ctx->rounds; // initialize our local aes context
+    cty.rk = cty.buf; // round count and key buf pointer
 
-    if (( ret = aes_set_encryption_key( &cty, key, keysize )) != 0 )
-        return( ret );
+    if((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
 
     SK = cty.rk + cty.rounds * 4;
 
-    CPY128  // copy a 128-bit block from *SK to *RK
+    CPY128 // copy a 128-bit block from *SK to *RK
 
-    for( i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8 ) {
-        for( j = 0; j < 4; j++, SK++ ) {
-            *RK++ = RT0[ FSb[ ( *SK       ) & 0xFF ] ] ^
-                    RT1[ FSb[ ( *SK >>  8 ) & 0xFF ] ] ^
-                    RT2[ FSb[ ( *SK >> 16 ) & 0xFF ] ] ^
-                    RT3[ FSb[ ( *SK >> 24 ) & 0xFF ] ];
+        for(i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
+        for(j = 0; j < 4; j++, SK++) {
+            *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
+                    RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
         }
     }
-    CPY128  // copy a 128-bit block from *SK to *RK
-    memset( &cty, 0, sizeof( aes_context ) );   // clear local aes context
-    return( 0 );
+    CPY128 // copy a 128-bit block from *SK to *RK
+        memset(&cty, 0, sizeof(aes_context)); // clear local aes context
+    return (0);
 }
 
 #endif /* AES_DECRYPTION */
@@ -344,34 +320,42 @@ int aes_set_decryption_key( aes_context *ctx,
  *  Invoked to establish the key schedule for subsequent encryption/decryption
  *
  ******************************************************************************/
-int aes_setkey( aes_context *ctx,   // AES context provided by our caller
-                int mode,           // ENCRYPT or DECRYPT flag
-                const uchar *key,   // pointer to the key
-                uint keysize )      // key length in bytes
+int aes_setkey(
+    aes_context* ctx, // AES context provided by our caller
+    int mode, // ENCRYPT or DECRYPT flag
+    const uchar* key, // pointer to the key
+    uint keysize) // key length in bytes
 {
     // since table initialization is not thread safe, we could either add
     // system-specific mutexes and init the AES key generation tables on
     // demand, or ask the developer to simply call "gcm_initialize" once during
     // application startup before threading begins. That's what we choose.
-    if( !aes_tables_inited ) return ( -1 );  // fail the call when not inited.
-    
-    ctx->mode = mode;       // capture the key type we're creating
-    ctx->rk = ctx->buf;     // initialize our round key pointer
+    if(!aes_tables_inited) return (-1); // fail the call when not inited.
+
+    ctx->mode = mode; // capture the key type we're creating
+    ctx->rk = ctx->buf; // initialize our round key pointer
 
-    switch( keysize )       // set the rounds count based upon the keysize
+    switch(keysize) // set the rounds count based upon the keysize
     {
-        case 16: ctx->rounds = 10; break;   // 16-byte, 128-bit key
-        case 24: ctx->rounds = 12; break;   // 24-byte, 192-bit key
-        case 32: ctx->rounds = 14; break;   // 32-byte, 256-bit key
-	default: return(-1);
+    case 16:
+        ctx->rounds = 10;
+        break; // 16-byte, 128-bit key
+    case 24:
+        ctx->rounds = 12;
+        break; // 24-byte, 192-bit key
+    case 32:
+        ctx->rounds = 14;
+        break; // 32-byte, 256-bit key
+    default:
+        return (-1);
     }
 
 #if AES_DECRYPTION
-    if( mode == DECRYPT )   // expand our key for encryption or decryption
-        return( aes_set_decryption_key( ctx, key, keysize ) );
-    else     /* ENCRYPT */
+    if(mode == DECRYPT) // expand our key for encryption or decryption
+        return (aes_set_decryption_key(ctx, key, keysize));
+    else /* ENCRYPT */
 #endif /* AES_DECRYPTION */
-        return( aes_set_encryption_key( ctx, key, keysize ) );
+        return (aes_set_encryption_key(ctx, key, keysize));
 }
 
 /******************************************************************************
@@ -383,101 +367,74 @@ int aes_setkey( aes_context *ctx,   // AES context provided by our caller
  *  and all keying information appropriate for the task.
  *
  ******************************************************************************/
-int aes_cipher( aes_context *ctx,
-                    const uchar input[16],
-                    uchar output[16] )
-{
+int aes_cipher(aes_context* ctx, const uchar input[16], uchar output[16]) {
     int i;
-    uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;   // general purpose locals
+    uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
 
     RK = ctx->rk;
 
-    GET_UINT32_LE( X0, input,  0 ); X0 ^= *RK++;    // load our 128-bit
-    GET_UINT32_LE( X1, input,  4 ); X1 ^= *RK++;    // input buffer in a storage
-    GET_UINT32_LE( X2, input,  8 ); X2 ^= *RK++;    // memory endian-neutral way
-    GET_UINT32_LE( X3, input, 12 ); X3 ^= *RK++;
+    GET_UINT32_LE(X0, input, 0);
+    X0 ^= *RK++; // load our 128-bit
+    GET_UINT32_LE(X1, input, 4);
+    X1 ^= *RK++; // input buffer in a storage
+    GET_UINT32_LE(X2, input, 8);
+    X2 ^= *RK++; // memory endian-neutral way
+    GET_UINT32_LE(X3, input, 12);
+    X3 ^= *RK++;
+
+#if AES_DECRYPTION // whether AES decryption is supported
+
+    if(ctx->mode == DECRYPT) {
+        for(i = (ctx->rounds >> 1) - 1; i > 0; i--) {
+            AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
+            AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
+        }
 
-#if AES_DECRYPTION  // whether AES decryption is supported
+        AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
 
-    if( ctx->mode == DECRYPT )
-    {
-        for( i = (ctx->rounds >> 1) - 1; i > 0; i-- )
-        {
-            AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
-            AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
-        }
+        X0 = *RK++ ^ ((uint32_t)RSb[(Y0)&0xFF]) ^ ((uint32_t)RSb[(Y3 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)RSb[(Y2 >> 16) & 0xFF] << 16) ^ ((uint32_t)RSb[(Y1 >> 24) & 0xFF] << 24);
 
-        AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
-
-        X0 = *RK++ ^ \
-                ( (uint32_t) RSb[ ( Y0       ) & 0xFF ]       ) ^
-                ( (uint32_t) RSb[ ( Y3 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) RSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );
-
-        X1 = *RK++ ^ \
-                ( (uint32_t) RSb[ ( Y1       ) & 0xFF ]       ) ^
-                ( (uint32_t) RSb[ ( Y0 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) RSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );
-
-        X2 = *RK++ ^ \
-                ( (uint32_t) RSb[ ( Y2       ) & 0xFF ]       ) ^
-                ( (uint32_t) RSb[ ( Y1 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) RSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );
-
-        X3 = *RK++ ^ \
-                ( (uint32_t) RSb[ ( Y3       ) & 0xFF ]       ) ^
-                ( (uint32_t) RSb[ ( Y2 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) RSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );
-    }
-    else /* ENCRYPT */
+        X1 = *RK++ ^ ((uint32_t)RSb[(Y1)&0xFF]) ^ ((uint32_t)RSb[(Y0 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)RSb[(Y3 >> 16) & 0xFF] << 16) ^ ((uint32_t)RSb[(Y2 >> 24) & 0xFF] << 24);
+
+        X2 = *RK++ ^ ((uint32_t)RSb[(Y2)&0xFF]) ^ ((uint32_t)RSb[(Y1 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)RSb[(Y0 >> 16) & 0xFF] << 16) ^ ((uint32_t)RSb[(Y3 >> 24) & 0xFF] << 24);
+
+        X3 = *RK++ ^ ((uint32_t)RSb[(Y3)&0xFF]) ^ ((uint32_t)RSb[(Y2 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)RSb[(Y1 >> 16) & 0xFF] << 16) ^ ((uint32_t)RSb[(Y0 >> 24) & 0xFF] << 24);
+    } else /* ENCRYPT */
     {
 #endif /* AES_DECRYPTION */
 
-        for( i = (ctx->rounds >> 1) - 1; i > 0; i-- )
-        {
-            AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
-            AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
+        for(i = (ctx->rounds >> 1) - 1; i > 0; i--) {
+            AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
+            AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
         }
 
-        AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
-
-        X0 = *RK++ ^ \
-                ( (uint32_t) FSb[ ( Y0       ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( Y1 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );
-
-        X1 = *RK++ ^ \
-                ( (uint32_t) FSb[ ( Y1       ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( Y2 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );
-
-        X2 = *RK++ ^ \
-                ( (uint32_t) FSb[ ( Y2       ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( Y3 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );
-
-        X3 = *RK++ ^ \
-                ( (uint32_t) FSb[ ( Y3       ) & 0xFF ]       ) ^
-                ( (uint32_t) FSb[ ( Y0 >>  8 ) & 0xFF ] <<  8 ) ^
-                ( (uint32_t) FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
-                ( (uint32_t) FSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );
-
-#if AES_DECRYPTION  // whether AES decryption is supported
+        AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
+
+        X0 = *RK++ ^ ((uint32_t)FSb[(Y0)&0xFF]) ^ ((uint32_t)FSb[(Y1 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)FSb[(Y2 >> 16) & 0xFF] << 16) ^ ((uint32_t)FSb[(Y3 >> 24) & 0xFF] << 24);
+
+        X1 = *RK++ ^ ((uint32_t)FSb[(Y1)&0xFF]) ^ ((uint32_t)FSb[(Y2 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)FSb[(Y3 >> 16) & 0xFF] << 16) ^ ((uint32_t)FSb[(Y0 >> 24) & 0xFF] << 24);
+
+        X2 = *RK++ ^ ((uint32_t)FSb[(Y2)&0xFF]) ^ ((uint32_t)FSb[(Y3 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)FSb[(Y0 >> 16) & 0xFF] << 16) ^ ((uint32_t)FSb[(Y1 >> 24) & 0xFF] << 24);
+
+        X3 = *RK++ ^ ((uint32_t)FSb[(Y3)&0xFF]) ^ ((uint32_t)FSb[(Y0 >> 8) & 0xFF] << 8) ^
+             ((uint32_t)FSb[(Y1 >> 16) & 0xFF] << 16) ^ ((uint32_t)FSb[(Y2 >> 24) & 0xFF] << 24);
+
+#if AES_DECRYPTION // whether AES decryption is supported
     }
 #endif /* AES_DECRYPTION */
 
-    PUT_UINT32_LE( X0, output,  0 );
-    PUT_UINT32_LE( X1, output,  4 );
-    PUT_UINT32_LE( X2, output,  8 );
-    PUT_UINT32_LE( X3, output, 12 );
+    PUT_UINT32_LE(X0, output, 0);
+    PUT_UINT32_LE(X1, output, 4);
+    PUT_UINT32_LE(X2, output, 8);
+    PUT_UINT32_LE(X3, output, 12);
 
-    return( 0 );
+    return (0);
 }
 /* end of aes.c */

+ 24 - 25
esubghz_chat/crypto/aes.h

@@ -24,58 +24,57 @@
 #define AES_HEADER
 
 /******************************************************************************/
-#define AES_DECRYPTION  0       // whether AES decryption is supported
+#define AES_DECRYPTION 0 // whether AES decryption is supported
 /******************************************************************************/
 
 #include <string.h>
 
-#define ENCRYPT         1       // specify whether we're encrypting
-#define DECRYPT         0       // or decrypting
+#define ENCRYPT 1 // specify whether we're encrypting
+#define DECRYPT 0 // or decrypting
 
 #if defined(_MSC_VER)
-    #include <basetsd.h>
-    typedef UINT32 uint32_t;
+#include <basetsd.h>
+typedef UINT32 uint32_t;
 #else
-    #include <inttypes.h>
+#include <inttypes.h>
 #endif
 
-typedef unsigned char uchar;    // add some convienent shorter types
+typedef unsigned char uchar; // add some convienent shorter types
 typedef unsigned int uint;
 
-
 /******************************************************************************
  *  AES_INIT_KEYGEN_TABLES : MUST be called once before any AES use
  ******************************************************************************/
-void aes_init_keygen_tables( void );
-
+void aes_init_keygen_tables(void);
 
 /******************************************************************************
  *  AES_CONTEXT : cipher context / holds inter-call data
  ******************************************************************************/
 typedef struct {
-    int mode;           // 1 for Encryption, 0 for Decryption
-    int rounds;         // keysize-based rounds count
-    uint32_t *rk;       // pointer to current round key
-    uint32_t buf[68];   // key expansion buffer
+    int mode; // 1 for Encryption, 0 for Decryption
+    int rounds; // keysize-based rounds count
+    uint32_t* rk; // pointer to current round key
+    uint32_t buf[68]; // key expansion buffer
 } aes_context;
 
-
 /******************************************************************************
  *  AES_SETKEY : called to expand the key for encryption or decryption
  ******************************************************************************/
-int aes_setkey( aes_context *ctx,       // pointer to context
-                int mode,               // 1 or 0 for Encrypt/Decrypt
-                const uchar *key,       // AES input key
-                uint keysize );         // size in bytes (must be 16, 24, 32 for
-		                        // 128, 192 or 256-bit keys respectively)
-                                        // returns 0 for success
+int aes_setkey(
+    aes_context* ctx, // pointer to context
+    int mode, // 1 or 0 for Encrypt/Decrypt
+    const uchar* key, // AES input key
+    uint keysize); // size in bytes (must be 16, 24, 32 for
+// 128, 192 or 256-bit keys respectively)
+// returns 0 for success
 
 /******************************************************************************
  *  AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data
  ******************************************************************************/
-int aes_cipher( aes_context *ctx,       // pointer to context
-                const uchar input[16],  // 128-bit block to en/decipher
-                uchar output[16] );     // 128-bit output result block
-                                        // returns 0 for success
+int aes_cipher(
+    aes_context* ctx, // pointer to context
+    const uchar input[16], // 128-bit block to en/decipher
+    uchar output[16]); // 128-bit output result block
+// returns 0 for success
 
 #endif /* AES_HEADER */

+ 196 - 191
esubghz_chat/crypto/gcm.c

@@ -76,25 +76,40 @@
  *  significantly slower 128x128 bit multiple within GF(2^128).
  */
 static const uint64_t last4[16] = {
-    0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
-    0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0  };
+    0x0000,
+    0x1c20,
+    0x3840,
+    0x2460,
+    0x7080,
+    0x6ca0,
+    0x48c0,
+    0x54e0,
+    0xe100,
+    0xfd20,
+    0xd940,
+    0xc560,
+    0x9180,
+    0x8da0,
+    0xa9c0,
+    0xb5e0};
 
 /*
  * Platform Endianness Neutralizing Load and Store Macro definitions
  * GCM wants platform-neutral Big Endian (BE) byte ordering
  */
-#define GET_UINT32_BE(n,b,i) {                      \
-    (n) = ( (uint32_t) (b)[(i)    ] << 24 )         \
-        | ( (uint32_t) (b)[(i) + 1] << 16 )         \
-        | ( (uint32_t) (b)[(i) + 2] <<  8 )         \
-        | ( (uint32_t) (b)[(i) + 3]       ); }
-
-#define PUT_UINT32_BE(n,b,i) {                      \
-    (b)[(i)    ] = (uchar) ( (n) >> 24 );   \
-    (b)[(i) + 1] = (uchar) ( (n) >> 16 );   \
-    (b)[(i) + 2] = (uchar) ( (n) >>  8 );   \
-    (b)[(i) + 3] = (uchar) ( (n)       ); }
+#define GET_UINT32_BE(n, b, i)                                              \
+    {                                                                       \
+        (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | \
+              ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]);     \
+    }
 
+#define PUT_UINT32_BE(n, b, i)             \
+    {                                      \
+        (b)[(i)] = (uchar)((n) >> 24);     \
+        (b)[(i) + 1] = (uchar)((n) >> 16); \
+        (b)[(i) + 2] = (uchar)((n) >> 8);  \
+        (b)[(i) + 3] = (uchar)((n));       \
+    }
 
 /******************************************************************************
  *
@@ -108,13 +123,11 @@ static const uint64_t last4[16] = {
  *  environment is running.
  *
  ******************************************************************************/
-int gcm_initialize( void )
-{
+int gcm_initialize(void) {
     aes_init_keygen_tables();
-    return( 0 );
+    return (0);
 }
 
-
 /******************************************************************************
  *
  *  GCM_MULT
@@ -124,45 +137,45 @@ int gcm_initialize( void )
  *  'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  *
  ******************************************************************************/
-static void gcm_mult( gcm_context *ctx,     // pointer to established context
-                      const uchar x[16],    // pointer to 128-bit input vector
-                      uchar output[16] )    // pointer to 128-bit output vector
+static void gcm_mult(
+    gcm_context* ctx, // pointer to established context
+    const uchar x[16], // pointer to 128-bit input vector
+    uchar output[16]) // pointer to 128-bit output vector
 {
     int i;
     uchar lo, hi, rem;
     uint64_t zh, zl;
 
-    lo = (uchar)( x[15] & 0x0f );
-    hi = (uchar)( x[15] >> 4 );
+    lo = (uchar)(x[15] & 0x0f);
+    hi = (uchar)(x[15] >> 4);
     zh = ctx->HH[lo];
     zl = ctx->HL[lo];
 
-    for( i = 15; i >= 0; i-- ) {
-        lo = (uchar) ( x[i] & 0x0f );
-        hi = (uchar) ( x[i] >> 4 );
+    for(i = 15; i >= 0; i--) {
+        lo = (uchar)(x[i] & 0x0f);
+        hi = (uchar)(x[i] >> 4);
 
-        if( i != 15 ) {
-            rem = (uchar) ( zl & 0x0f );
-            zl = ( zh << 60 ) | ( zl >> 4 );
-            zh = ( zh >> 4 );
-            zh ^= (uint64_t) last4[rem] << 48;
+        if(i != 15) {
+            rem = (uchar)(zl & 0x0f);
+            zl = (zh << 60) | (zl >> 4);
+            zh = (zh >> 4);
+            zh ^= (uint64_t)last4[rem] << 48;
             zh ^= ctx->HH[lo];
             zl ^= ctx->HL[lo];
         }
-        rem = (uchar) ( zl & 0x0f );
-        zl = ( zh << 60 ) | ( zl >> 4 );
-        zh = ( zh >> 4 );
-        zh ^= (uint64_t) last4[rem] << 48;
+        rem = (uchar)(zl & 0x0f);
+        zl = (zh << 60) | (zl >> 4);
+        zh = (zh >> 4);
+        zh ^= (uint64_t)last4[rem] << 48;
         zh ^= ctx->HH[hi];
         zl ^= ctx->HL[hi];
     }
-    PUT_UINT32_BE( zh >> 32, output, 0 );
-    PUT_UINT32_BE( zh, output, 4 );
-    PUT_UINT32_BE( zl >> 32, output, 8 );
-    PUT_UINT32_BE( zl, output, 12 );
+    PUT_UINT32_BE(zh >> 32, output, 0);
+    PUT_UINT32_BE(zh, output, 4);
+    PUT_UINT32_BE(zl >> 32, output, 8);
+    PUT_UINT32_BE(zl, output, 12);
 }
 
-
 /******************************************************************************
  *
  *  GCM_SETKEY
@@ -171,59 +184,57 @@ static void gcm_mult( gcm_context *ctx,     // pointer to established context
  *  and populates the gcm context's pre-calculated HTables.
  *
  ******************************************************************************/
-int gcm_setkey( gcm_context *ctx,   // pointer to caller-provided gcm context
-                const uchar *key,   // pointer to the AES encryption key
-                const uint keysize) // size in bytes (must be 16, 24, 32 for
-		                    // 128, 192 or 256-bit keys respectively)
+int gcm_setkey(
+    gcm_context* ctx, // pointer to caller-provided gcm context
+    const uchar* key, // pointer to the AES encryption key
+    const uint keysize) // size in bytes (must be 16, 24, 32 for
+// 128, 192 or 256-bit keys respectively)
 {
     int ret, i, j;
     uint64_t hi, lo;
     uint64_t vl, vh;
     unsigned char h[16];
 
-    memset( ctx, 0, sizeof(gcm_context) );  // zero caller-provided GCM context
-    memset( h, 0, 16 );                     // initialize the block to encrypt
+    memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
+    memset(h, 0, 16); // initialize the block to encrypt
 
     // encrypt the null 128-bit block to generate a key-based value
     // which is then used to initialize our GHASH lookup tables
-    if(( ret = aes_setkey( &ctx->aes_ctx, ENCRYPT, key, keysize )) != 0 )
-        return( ret );
-    if(( ret = aes_cipher( &ctx->aes_ctx, h, h )) != 0 )
-        return( ret );
+    if((ret = aes_setkey(&ctx->aes_ctx, ENCRYPT, key, keysize)) != 0) return (ret);
+    if((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
 
-    GET_UINT32_BE( hi, h,  0  );    // pack h as two 64-bit ints, big-endian
-    GET_UINT32_BE( lo, h,  4  );
-    vh = (uint64_t) hi << 32 | lo;
+    GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
+    GET_UINT32_BE(lo, h, 4);
+    vh = (uint64_t)hi << 32 | lo;
 
-    GET_UINT32_BE( hi, h,  8  );
-    GET_UINT32_BE( lo, h,  12 );
-    vl = (uint64_t) hi << 32 | lo;
+    GET_UINT32_BE(hi, h, 8);
+    GET_UINT32_BE(lo, h, 12);
+    vl = (uint64_t)hi << 32 | lo;
 
-    ctx->HL[8] = vl;                // 8 = 1000 corresponds to 1 in GF(2^128)
+    ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
     ctx->HH[8] = vh;
-    ctx->HH[0] = 0;                 // 0 corresponds to 0 in GF(2^128)
+    ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
     ctx->HL[0] = 0;
 
-    for( i = 4; i > 0; i >>= 1 ) {
-        uint32_t T = (uint32_t) ( vl & 1 ) * 0xe1000000U;
-        vl  = ( vh << 63 ) | ( vl >> 1 );
-        vh  = ( vh >> 1 ) ^ ( (uint64_t) T << 32);
+    for(i = 4; i > 0; i >>= 1) {
+        uint32_t T = (uint32_t)(vl & 1) * 0xe1000000U;
+        vl = (vh << 63) | (vl >> 1);
+        vh = (vh >> 1) ^ ((uint64_t)T << 32);
         ctx->HL[i] = vl;
         ctx->HH[i] = vh;
     }
-    for (i = 2; i < 16; i <<= 1 ) {
+    for(i = 2; i < 16; i <<= 1) {
         uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
         vh = *HiH;
         vl = *HiL;
-        for( j = 1; j < i; j++ ) {
+        for(j = 1; j < i; j++) {
             HiH[j] = vh ^ ctx->HH[j];
             HiL[j] = vl ^ ctx->HL[j];
         }
     }
-    return( 0 );
+    return (0);
 }
 
-
 /******************************************************************************
  *
  *    GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
@@ -245,62 +256,61 @@ int gcm_setkey( gcm_context *ctx,   // pointer to caller-provided gcm context
  *  mode, and preprocesses the initialization vector and additional AEAD data.
  *
  ******************************************************************************/
-int gcm_start( gcm_context *ctx,    // pointer to user-provided GCM context
-               int mode,            // GCM_ENCRYPT or GCM_DECRYPT
-               const uchar *iv,     // pointer to initialization vector
-               size_t iv_len,       // IV length in bytes (should == 12)
-               const uchar *add,    // ptr to additional AEAD data (NULL if none)
-               size_t add_len )     // length of additional AEAD data (bytes)
+int gcm_start(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    int mode, // GCM_ENCRYPT or GCM_DECRYPT
+    const uchar* iv, // pointer to initialization vector
+    size_t iv_len, // IV length in bytes (should == 12)
+    const uchar* add, // ptr to additional AEAD data (NULL if none)
+    size_t add_len) // length of additional AEAD data (bytes)
 {
-    int ret;            // our error return if the AES encrypt fails
+    int ret; // our error return if the AES encrypt fails
     uchar work_buf[16]; // XOR source built from provided IV if len != 16
-    const uchar *p;     // general purpose array pointer
-    size_t use_len;     // byte count to process, up to 16 bytes
-    size_t i;           // local loop iterator
+    const uchar* p; // general purpose array pointer
+    size_t use_len; // byte count to process, up to 16 bytes
+    size_t i; // local loop iterator
 
     // since the context might be reused under the same key
     // we zero the working buffers for this next new process
-    memset( ctx->y,   0x00, sizeof(ctx->y  ) );
-    memset( ctx->buf, 0x00, sizeof(ctx->buf) );
+    memset(ctx->y, 0x00, sizeof(ctx->y));
+    memset(ctx->buf, 0x00, sizeof(ctx->buf));
     ctx->len = 0;
     ctx->add_len = 0;
 
-    ctx->mode = mode;               // set the GCM encryption/decryption mode
-    ctx->aes_ctx.mode = ENCRYPT;    // GCM *always* runs AES in ENCRYPTION mode
+    ctx->mode = mode; // set the GCM encryption/decryption mode
+    ctx->aes_ctx.mode = ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
 
-    if( iv_len == 12 ) {                // GCM natively uses a 12-byte, 96-bit IV
-        memcpy( ctx->y, iv, iv_len );   // copy the IV to the top of the 'y' buff
-        ctx->y[15] = 1;                 // start "counting" from 1 (not 0)
-    }
-    else    // if we don't have a 12-byte IV, we GHASH whatever we've been given
-    {   
-        memset( work_buf, 0x00, 16 );               // clear the working buffer
-        PUT_UINT32_BE( iv_len * 8, work_buf, 12 );  // place the IV into buffer
+    if(iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
+        memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
+        ctx->y[15] = 1; // start "counting" from 1 (not 0)
+    } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
+    {
+        memset(work_buf, 0x00, 16); // clear the working buffer
+        PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
 
         p = iv;
-        while( iv_len > 0 ) {
-            use_len = ( iv_len < 16 ) ? iv_len : 16;
-            for( i = 0; i < use_len; i++ ) ctx->y[i] ^= p[i];
-            gcm_mult( ctx, ctx->y, ctx->y );
+        while(iv_len > 0) {
+            use_len = (iv_len < 16) ? iv_len : 16;
+            for(i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
+            gcm_mult(ctx, ctx->y, ctx->y);
             iv_len -= use_len;
             p += use_len;
         }
-        for( i = 0; i < 16; i++ ) ctx->y[i] ^= work_buf[i];
-        gcm_mult( ctx, ctx->y, ctx->y );
+        for(i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
+        gcm_mult(ctx, ctx->y, ctx->y);
     }
-    if( ( ret = aes_cipher( &ctx->aes_ctx, ctx->y, ctx->base_ectr ) ) != 0 )
-        return( ret );
+    if((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0) return (ret);
 
     ctx->add_len = add_len;
     p = add;
-    while( add_len > 0 ) {
-        use_len = ( add_len < 16 ) ? add_len : 16;
-        for( i = 0; i < use_len; i++ ) ctx->buf[i] ^= p[i];
-        gcm_mult( ctx, ctx->buf, ctx->buf );
+    while(add_len > 0) {
+        use_len = (add_len < 16) ? add_len : 16;
+        for(i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
+        gcm_mult(ctx, ctx->buf, ctx->buf);
         add_len -= use_len;
         p += use_len;
     }
-    return( 0 );
+    return (0);
 }
 
 /******************************************************************************
@@ -314,63 +324,61 @@ int gcm_start( gcm_context *ctx,    // pointer to user-provided GCM context
  *  have a partial block length of < 128 bits.)
  *
  ******************************************************************************/
-int gcm_update( gcm_context *ctx,       // pointer to user-provided GCM context
-                size_t length,          // length, in bytes, of data to process
-                const uchar *input,     // pointer to source data
-                uchar *output )         // pointer to destination data
+int gcm_update(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    size_t length, // length, in bytes, of data to process
+    const uchar* input, // pointer to source data
+    uchar* output) // pointer to destination data
 {
-    int ret;            // our error return if the AES encrypt fails
-    uchar ectr[16];     // counter-mode cipher output for XORing
-    size_t use_len;     // byte count to process, up to 16 bytes
-    size_t i;           // local loop iterator
+    int ret; // our error return if the AES encrypt fails
+    uchar ectr[16]; // counter-mode cipher output for XORing
+    size_t use_len; // byte count to process, up to 16 bytes
+    size_t i; // local loop iterator
 
     ctx->len += length; // bump the GCM context's running length count
 
-    while( length > 0 ) {
+    while(length > 0) {
         // clamp the length to process at 16 bytes
-        use_len = ( length < 16 ) ? length : 16;
+        use_len = (length < 16) ? length : 16;
 
         // increment the context's 128-bit IV||Counter 'y' vector
-        for( i = 16; i > 12; i-- ) if( ++ctx->y[i - 1] != 0 ) break;
+        for(i = 16; i > 12; i--)
+            if(++ctx->y[i - 1] != 0) break;
 
         // encrypt the context's 'y' vector under the established key
-        if( ( ret = aes_cipher( &ctx->aes_ctx, ctx->y, ectr ) ) != 0 )
-            return( ret );
+        if((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
 
         // encrypt or decrypt the input to the output
-        if( ctx->mode == ENCRYPT )  
-        {
-             for( i = 0; i < use_len; i++ ) {
+        if(ctx->mode == ENCRYPT) {
+            for(i = 0; i < use_len; i++) {
                 // XOR the cipher's ouptut vector (ectr) with our input
-                output[i] = (uchar) ( ectr[i] ^ input[i] );
+                output[i] = (uchar)(ectr[i] ^ input[i]);
                 // now we mix in our data into the authentication hash.
-                // if we're ENcrypting we XOR in the post-XOR (output) 
-                // results, but if we're DEcrypting we XOR in the input 
+                // if we're ENcrypting we XOR in the post-XOR (output)
+                // results, but if we're DEcrypting we XOR in the input
                 // data
                 ctx->buf[i] ^= output[i];
             }
-        }
-            else                        
-        {
-            for( i = 0; i < use_len; i++ ) {
-                // but if we're DEcrypting we XOR in the input data first, 
-                // i.e. before saving to ouput data, otherwise if the input 
-                // and output buffer are the same (inplace decryption) we 
+        } else {
+            for(i = 0; i < use_len; i++) {
+                // but if we're DEcrypting we XOR in the input data first,
+                // i.e. before saving to ouput data, otherwise if the input
+                // and output buffer are the same (inplace decryption) we
                 // would not get the correct auth tag
 
-       	        ctx->buf[i] ^= input[i];
+                ctx->buf[i] ^= input[i];
 
                 // XOR the cipher's ouptut vector (ectr) with our input
-                output[i] = (uchar) ( ectr[i] ^ input[i] );
-             }
+                output[i] = (uchar)(ectr[i] ^ input[i]);
+            }
         }
-        gcm_mult( ctx, ctx->buf, ctx->buf );    // perform a GHASH operation
+        gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
 
-        length -= use_len;  // drop the remaining byte count to process
-        input  += use_len;  // bump our input pointer forward
-        output += use_len;  // bump our output pointer forward
+        length -= use_len; // drop the remaining byte count to process
+        input += use_len; // bump our input pointer forward
+        output += use_len; // bump our output pointer forward
     }
-    return( 0 );
+    return (0);
 }
 
 /******************************************************************************
@@ -381,33 +389,33 @@ int gcm_update( gcm_context *ctx,       // pointer to user-provided GCM context
  *  It performs the final GHASH to produce the resulting authentication TAG.
  *
  ******************************************************************************/
-int gcm_finish( gcm_context *ctx,   // pointer to user-provided GCM context
-                uchar *tag,         // pointer to buffer which receives the tag
-                size_t tag_len )    // length, in bytes, of the tag-receiving buf
+int gcm_finish(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    uchar* tag, // pointer to buffer which receives the tag
+    size_t tag_len) // length, in bytes, of the tag-receiving buf
 {
     uchar work_buf[16];
-    uint64_t orig_len     = ctx->len * 8;
+    uint64_t orig_len = ctx->len * 8;
     uint64_t orig_add_len = ctx->add_len * 8;
     size_t i;
 
-    if( tag_len != 0 ) memcpy( tag, ctx->base_ectr, tag_len );
+    if(tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
 
-    if( orig_len || orig_add_len ) {
-        memset( work_buf, 0x00, 16 );
+    if(orig_len || orig_add_len) {
+        memset(work_buf, 0x00, 16);
 
-        PUT_UINT32_BE( ( orig_add_len >> 32 ), work_buf, 0  );
-        PUT_UINT32_BE( ( orig_add_len       ), work_buf, 4  );
-        PUT_UINT32_BE( ( orig_len     >> 32 ), work_buf, 8  );
-        PUT_UINT32_BE( ( orig_len           ), work_buf, 12 );
+        PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
+        PUT_UINT32_BE((orig_add_len), work_buf, 4);
+        PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
+        PUT_UINT32_BE((orig_len), work_buf, 12);
 
-        for( i = 0; i < 16; i++ ) ctx->buf[i] ^= work_buf[i];
-        gcm_mult( ctx, ctx->buf, ctx->buf );
-        for( i = 0; i < tag_len; i++ ) tag[i] ^= ctx->buf[i];
+        for(i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
+        gcm_mult(ctx, ctx->buf, ctx->buf);
+        for(i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
     }
-    return( 0 );
+    return (0);
 }
 
-
 /******************************************************************************
  *
  *  GCM_CRYPT_AND_TAG
@@ -426,29 +434,28 @@ int gcm_finish( gcm_context *ctx,   // pointer to user-provided GCM context
  *
  ******************************************************************************/
 int gcm_crypt_and_tag(
-        gcm_context *ctx,       // gcm context with key already setup
-        int mode,               // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
-        const uchar *iv,        // pointer to the 12-byte initialization vector
-        size_t iv_len,          // byte length if the IV. should always be 12
-        const uchar *add,       // pointer to the non-ciphered additional data
-        size_t add_len,         // byte length of the additional AEAD data
-        const uchar *input,     // pointer to the cipher data source
-        uchar *output,          // pointer to the cipher data destination
-        size_t length,          // byte length of the cipher data
-        uchar *tag,             // pointer to the tag to be generated
-        size_t tag_len )        // byte length of the tag to be generated
-{   /*
+    gcm_context* ctx, // gcm context with key already setup
+    int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
+    const uchar* iv, // pointer to the 12-byte initialization vector
+    size_t iv_len, // byte length if the IV. should always be 12
+    const uchar* add, // pointer to the non-ciphered additional data
+    size_t add_len, // byte length of the additional AEAD data
+    const uchar* input, // pointer to the cipher data source
+    uchar* output, // pointer to the cipher data destination
+    size_t length, // byte length of the cipher data
+    uchar* tag, // pointer to the tag to be generated
+    size_t tag_len) // byte length of the tag to be generated
+{ /*
        assuming that the caller has already invoked gcm_setkey to
        prepare the gcm context with the keying material, we simply
        invoke each of the three GCM sub-functions in turn...
     */
-    gcm_start  ( ctx, mode, iv, iv_len, add, add_len );
-    gcm_update ( ctx, length, input, output );
-    gcm_finish ( ctx, tag, tag_len );
-    return( 0 );
+    gcm_start(ctx, mode, iv, iv_len, add, add_len);
+    gcm_update(ctx, length, input, output);
+    gcm_finish(ctx, tag, tag_len);
+    return (0);
 }
 
-
 /******************************************************************************
  *
  *  GCM_AUTH_DECRYPT
@@ -462,37 +469,36 @@ int gcm_crypt_and_tag(
  *
  ******************************************************************************/
 int gcm_auth_decrypt(
-        gcm_context *ctx,       // gcm context with key already setup
-        const uchar *iv,        // pointer to the 12-byte initialization vector
-        size_t iv_len,          // byte length if the IV. should always be 12
-        const uchar *add,       // pointer to the non-ciphered additional data
-        size_t add_len,         // byte length of the additional AEAD data
-        const uchar *input,     // pointer to the cipher data source
-        uchar *output,          // pointer to the cipher data destination
-        size_t length,          // byte length of the cipher data
-        const uchar *tag,       // pointer to the tag to be authenticated
-        size_t tag_len )        // byte length of the tag <= 16
+    gcm_context* ctx, // gcm context with key already setup
+    const uchar* iv, // pointer to the 12-byte initialization vector
+    size_t iv_len, // byte length if the IV. should always be 12
+    const uchar* add, // pointer to the non-ciphered additional data
+    size_t add_len, // byte length of the additional AEAD data
+    const uchar* input, // pointer to the cipher data source
+    uchar* output, // pointer to the cipher data destination
+    size_t length, // byte length of the cipher data
+    const uchar* tag, // pointer to the tag to be authenticated
+    size_t tag_len) // byte length of the tag <= 16
 {
-    uchar check_tag[16];        // the tag generated and returned by decryption
-    int diff;                   // an ORed flag to detect authentication errors
-    size_t i;                   // our local iterator
+    uchar check_tag[16]; // the tag generated and returned by decryption
+    int diff; // an ORed flag to detect authentication errors
+    size_t i; // our local iterator
     /*
        we use GCM_DECRYPT_AND_TAG (above) to perform our decryption
        (which is an identical XORing to reverse the previous one)
        and also to re-generate the matching authentication tag
     */
-    gcm_crypt_and_tag(  ctx, DECRYPT, iv, iv_len, add, add_len,
-                        input, output, length, check_tag, tag_len );
+    gcm_crypt_and_tag(
+        ctx, DECRYPT, iv, iv_len, add, add_len, input, output, length, check_tag, tag_len);
 
     // now we verify the authentication tag in 'constant time'
-    for( diff = 0, i = 0; i < tag_len; i++ )
-        diff |= tag[i] ^ check_tag[i];
+    for(diff = 0, i = 0; i < tag_len; i++) diff |= tag[i] ^ check_tag[i];
 
-    if( diff != 0 ) {                   // see whether any bits differed?
-        memset( output, 0, length );    // if so... wipe the output data
-        return( GCM_AUTH_FAILURE );     // return GCM_AUTH_FAILURE
+    if(diff != 0) { // see whether any bits differed?
+        memset(output, 0, length); // if so... wipe the output data
+        return (GCM_AUTH_FAILURE); // return GCM_AUTH_FAILURE
     }
-    return( 0 );
+    return (0);
 }
 
 /******************************************************************************
@@ -504,8 +510,7 @@ int gcm_auth_decrypt(
  *  sensitive, so it MUST be zeroed after use. This function does that.
  *
  ******************************************************************************/
-void gcm_zero_ctx( gcm_context *ctx )
-{
+void gcm_zero_ctx(gcm_context* ctx) {
     // zero the context originally provided to us
-    memset( ctx, 0, sizeof( gcm_context ) );
+    memset(ctx, 0, sizeof(gcm_context));
 }

+ 60 - 66
esubghz_chat/crypto/gcm.h

@@ -24,52 +24,49 @@
 #ifndef GCM_HEADER
 #define GCM_HEADER
 
-#define GCM_AUTH_FAILURE    0x55555555  // authentication failure
+#define GCM_AUTH_FAILURE 0x55555555 // authentication failure
 
-#include "aes.h"                        // gcm_context includes aes_context
+#include "aes.h" // gcm_context includes aes_context
 
 #if defined(_MSC_VER)
-    #include <basetsd.h>
-    typedef unsigned int size_t;// use the right type for length declarations
-    typedef UINT32 uint32_t;
-    typedef UINT64 uint64_t;
+#include <basetsd.h>
+typedef unsigned int size_t; // use the right type for length declarations
+typedef UINT32 uint32_t;
+typedef UINT64 uint64_t;
 #else
-    #include <stdint.h>
+#include <stdint.h>
 #endif
 
-
 /******************************************************************************
  *  GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx
  ******************************************************************************/
 typedef struct {
-    int mode;               // cipher direction: encrypt/decrypt
-    uint64_t len;           // cipher data length processed so far
-    uint64_t add_len;       // total add data length
-    uint64_t HL[16];        // precalculated lo-half HTable
-    uint64_t HH[16];        // precalculated hi-half HTable
-    uchar base_ectr[16];    // first counter-mode cipher output for tag
-    uchar y[16];            // the current cipher-input IV|Counter value
-    uchar buf[16];          // buf working value
-    aes_context aes_ctx;    // cipher context used
+    int mode; // cipher direction: encrypt/decrypt
+    uint64_t len; // cipher data length processed so far
+    uint64_t add_len; // total add data length
+    uint64_t HL[16]; // precalculated lo-half HTable
+    uint64_t HH[16]; // precalculated hi-half HTable
+    uchar base_ectr[16]; // first counter-mode cipher output for tag
+    uchar y[16]; // the current cipher-input IV|Counter value
+    uchar buf[16]; // buf working value
+    aes_context aes_ctx; // cipher context used
 } gcm_context;
 
-
 /******************************************************************************
  *  GCM_CONTEXT : MUST be called once before ANY use of this library
  ******************************************************************************/
-int gcm_initialize( void );
-
+int gcm_initialize(void);
 
 /******************************************************************************
  *  GCM_SETKEY : sets the GCM (and AES) keying material for use
  ******************************************************************************/
-int gcm_setkey( gcm_context *ctx,   // caller-provided context ptr
-                const uchar *key,   // pointer to cipher key
-                const uint keysize  // size in bytes (must be 16, 24, 32 for
-		                    // 128, 192 or 256-bit keys respectively)
+int gcm_setkey(
+    gcm_context* ctx, // caller-provided context ptr
+    const uchar* key, // pointer to cipher key
+    const uint keysize // size in bytes (must be 16, 24, 32 for
+    // 128, 192 or 256-bit keys respectively)
 ); // returns 0 for success
 
-
 /******************************************************************************
  *
  *  GCM_CRYPT_AND_TAG
@@ -88,18 +85,17 @@ int gcm_setkey( gcm_context *ctx,   // caller-provided context ptr
  *
  ******************************************************************************/
 int gcm_crypt_and_tag(
-        gcm_context *ctx,       // gcm context with key already setup
-        int mode,               // cipher direction: ENCRYPT (1) or DECRYPT (0)
-        const uchar *iv,        // pointer to the 12-byte initialization vector
-        size_t iv_len,          // byte length if the IV. should always be 12
-        const uchar *add,       // pointer to the non-ciphered additional data
-        size_t add_len,         // byte length of the additional AEAD data
-        const uchar *input,     // pointer to the cipher data source
-        uchar *output,          // pointer to the cipher data destination
-        size_t length,          // byte length of the cipher data
-        uchar *tag,             // pointer to the tag to be generated
-        size_t tag_len );       // byte length of the tag to be generated
-
+    gcm_context* ctx, // gcm context with key already setup
+    int mode, // cipher direction: ENCRYPT (1) or DECRYPT (0)
+    const uchar* iv, // pointer to the 12-byte initialization vector
+    size_t iv_len, // byte length if the IV. should always be 12
+    const uchar* add, // pointer to the non-ciphered additional data
+    size_t add_len, // byte length of the additional AEAD data
+    const uchar* input, // pointer to the cipher data source
+    uchar* output, // pointer to the cipher data destination
+    size_t length, // byte length of the cipher data
+    uchar* tag, // pointer to the tag to be generated
+    size_t tag_len); // byte length of the tag to be generated
 
 /******************************************************************************
  *
@@ -114,17 +110,16 @@ int gcm_crypt_and_tag(
  *
  ******************************************************************************/
 int gcm_auth_decrypt(
-        gcm_context *ctx,       // gcm context with key already setup
-        const uchar *iv,        // pointer to the 12-byte initialization vector
-        size_t iv_len,          // byte length if the IV. should always be 12
-        const uchar *add,       // pointer to the non-ciphered additional data
-        size_t add_len,         // byte length of the additional AEAD data
-        const uchar *input,     // pointer to the cipher data source
-        uchar *output,          // pointer to the cipher data destination
-        size_t length,          // byte length of the cipher data
-        const uchar *tag,       // pointer to the tag to be authenticated
-        size_t tag_len );       // byte length of the tag <= 16
-
+    gcm_context* ctx, // gcm context with key already setup
+    const uchar* iv, // pointer to the 12-byte initialization vector
+    size_t iv_len, // byte length if the IV. should always be 12
+    const uchar* add, // pointer to the non-ciphered additional data
+    size_t add_len, // byte length of the additional AEAD data
+    const uchar* input, // pointer to the cipher data source
+    uchar* output, // pointer to the cipher data destination
+    size_t length, // byte length of the cipher data
+    const uchar* tag, // pointer to the tag to be authenticated
+    size_t tag_len); // byte length of the tag <= 16
 
 /******************************************************************************
  *
@@ -134,13 +129,13 @@ int gcm_auth_decrypt(
  *  mode, and preprocesses the initialization vector and additional AEAD data.
  *
  ******************************************************************************/
-int gcm_start( gcm_context *ctx,    // pointer to user-provided GCM context
-               int mode,            // ENCRYPT (1) or DECRYPT (0)
-               const uchar *iv,     // pointer to initialization vector
-               size_t iv_len,       // IV length in bytes (should == 12)
-               const uchar *add,    // pointer to additional AEAD data (NULL if none)
-               size_t add_len );    // length of additional AEAD data (bytes)
-
+int gcm_start(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    int mode, // ENCRYPT (1) or DECRYPT (0)
+    const uchar* iv, // pointer to initialization vector
+    size_t iv_len, // IV length in bytes (should == 12)
+    const uchar* add, // pointer to additional AEAD data (NULL if none)
+    size_t add_len); // length of additional AEAD data (bytes)
 
 /******************************************************************************
  *
@@ -153,11 +148,11 @@ int gcm_start( gcm_context *ctx,    // pointer to user-provided GCM context
  *  have a partial block length of < 128 bits.)
  *
  ******************************************************************************/
-int gcm_update( gcm_context *ctx,       // pointer to user-provided GCM context
-                size_t length,          // length, in bytes, of data to process
-                const uchar *input,     // pointer to source data
-                uchar *output );        // pointer to destination data
-
+int gcm_update(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    size_t length, // length, in bytes, of data to process
+    const uchar* input, // pointer to source data
+    uchar* output); // pointer to destination data
 
 /******************************************************************************
  *
@@ -167,10 +162,10 @@ int gcm_update( gcm_context *ctx,       // pointer to user-provided GCM context
  *  It performs the final GHASH to produce the resulting authentication TAG.
  *
  ******************************************************************************/
-int gcm_finish( gcm_context *ctx,   // pointer to user-provided GCM context
-                uchar *tag,         // ptr to tag buffer - NULL if tag_len = 0
-                size_t tag_len );   // length, in bytes, of the tag-receiving buf
-
+int gcm_finish(
+    gcm_context* ctx, // pointer to user-provided GCM context
+    uchar* tag, // ptr to tag buffer - NULL if tag_len = 0
+    size_t tag_len); // length, in bytes, of the tag-receiving buf
 
 /******************************************************************************
  *
@@ -181,7 +176,6 @@ int gcm_finish( gcm_context *ctx,   // pointer to user-provided GCM context
  *  sensitive, so it MUST be zeroed after use. This function does that.
  *
  ******************************************************************************/
-void gcm_zero_ctx( gcm_context *ctx );
-
+void gcm_zero_ctx(gcm_context* ctx);
 
 #endif /* GCM_HEADER */

+ 167 - 159
esubghz_chat/crypto_wrapper.c

@@ -11,219 +11,227 @@
 DICT_DEF2(ESubGhzChatReplayDict, uint64_t, uint32_t)
 
 struct ESugGhzChatCryptoCtx {
-	uint8_t key[KEY_BITS / 8];
+    uint8_t key[KEY_BITS / 8];
 #ifndef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	gcm_context gcm_ctx;
+    gcm_context gcm_ctx;
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
-	ESubGhzChatReplayDict_t replay_dict;
-	uint64_t run_id;
-	uint32_t counter;
+    ESubGhzChatReplayDict_t replay_dict;
+    uint64_t run_id;
+    uint32_t counter;
 };
 
 struct ESubGhzChatCryptoMsg {
-	uint64_t run_id;
-	uint32_t counter;
-	uint8_t iv[IV_BYTES];
-	uint8_t tag[TAG_BYTES];
-	uint8_t data[0];
-} __attribute__ ((packed));
-
-void crypto_init(void)
-{
+    uint64_t run_id;
+    uint32_t counter;
+    uint8_t iv[IV_BYTES];
+    uint8_t tag[TAG_BYTES];
+    uint8_t data[0];
+} __attribute__((packed));
+
+void crypto_init(void) {
 #ifndef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	/* init the GCM and AES tables */
-	gcm_initialize();
+    /* init the GCM and AES tables */
+    gcm_initialize();
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
 }
 
-void crypto_explicit_bzero(void *s, size_t len)
-{
-	memset(s, 0, len);
-	asm volatile("" ::: "memory");
+void crypto_explicit_bzero(void* s, size_t len) {
+    memset(s, 0, len);
+    asm volatile("" ::: "memory");
 }
 
-ESubGhzChatCryptoCtx *crypto_ctx_alloc(void)
-{
-	ESubGhzChatCryptoCtx *ret = malloc(sizeof(ESubGhzChatCryptoCtx));
+ESubGhzChatCryptoCtx* crypto_ctx_alloc(void) {
+    ESubGhzChatCryptoCtx* ret = malloc(sizeof(ESubGhzChatCryptoCtx));
 
-	if (ret != NULL) {
-		memset(ret, 0, sizeof(ESubGhzChatCryptoCtx));
-		ESubGhzChatReplayDict_init(ret->replay_dict);
-		ret->run_id = 0;
-		ret->counter = 1;
-	}
+    if(ret != NULL) {
+        memset(ret, 0, sizeof(ESubGhzChatCryptoCtx));
+        ESubGhzChatReplayDict_init(ret->replay_dict);
+        ret->run_id = 0;
+        ret->counter = 1;
+    }
 
-	return ret;
+    return ret;
 }
 
-void crypto_ctx_free(ESubGhzChatCryptoCtx *ctx)
-{
-	crypto_ctx_clear(ctx);
-	ESubGhzChatReplayDict_clear(ctx->replay_dict);
-	free(ctx);
+void crypto_ctx_free(ESubGhzChatCryptoCtx* ctx) {
+    crypto_ctx_clear(ctx);
+    ESubGhzChatReplayDict_clear(ctx->replay_dict);
+    free(ctx);
 }
 
-void crypto_ctx_clear(ESubGhzChatCryptoCtx *ctx)
-{
-	crypto_explicit_bzero(ctx->key, sizeof(ctx->key));
+void crypto_ctx_clear(ESubGhzChatCryptoCtx* ctx) {
+    crypto_explicit_bzero(ctx->key, sizeof(ctx->key));
 #ifndef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	crypto_explicit_bzero(&(ctx->gcm_ctx), sizeof(ctx->gcm_ctx));
+    crypto_explicit_bzero(&(ctx->gcm_ctx), sizeof(ctx->gcm_ctx));
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
-	ESubGhzChatReplayDict_reset(ctx->replay_dict);
-	ctx->run_id = 0;
-	ctx->counter = 1;
+    ESubGhzChatReplayDict_reset(ctx->replay_dict);
+    ctx->run_id = 0;
+    ctx->counter = 1;
 }
 
-static uint64_t crypto_calc_run_id(FuriString *flipper_name, uint32_t tick)
-{
-	const char *fn = furi_string_get_cstr(flipper_name);
-	size_t fn_len = strlen(fn);
+static uint64_t crypto_calc_run_id(FuriString* flipper_name, uint32_t tick) {
+    const char* fn = furi_string_get_cstr(flipper_name);
+    size_t fn_len = strlen(fn);
 
-	uint8_t h_in[fn_len + sizeof(uint32_t)];
-	memcpy(h_in, fn, fn_len);
-	memcpy(h_in + fn_len, &tick, sizeof(uint32_t));
+    uint8_t h_in[fn_len + sizeof(uint32_t)];
+    memcpy(h_in, fn, fn_len);
+    memcpy(h_in + fn_len, &tick, sizeof(uint32_t));
 
-	uint8_t h_out[256];
-	sha256(h_in, fn_len + sizeof(uint32_t), h_out);
+    uint8_t h_out[256];
+    sha256(h_in, fn_len + sizeof(uint32_t), h_out);
 
-	uint64_t run_id;
-	memcpy(&run_id, h_out, sizeof(uint64_t));
+    uint64_t run_id;
+    memcpy(&run_id, h_out, sizeof(uint64_t));
 
-	return run_id;
+    return run_id;
 }
 
-bool crypto_ctx_set_key(ESubGhzChatCryptoCtx *ctx, const uint8_t *key,
-		FuriString *flipper_name, uint32_t tick)
-{
-	ctx->run_id = crypto_calc_run_id(flipper_name, tick);
-	ctx->counter = 1;
+bool crypto_ctx_set_key(
+    ESubGhzChatCryptoCtx* ctx,
+    const uint8_t* key,
+    FuriString* flipper_name,
+    uint32_t tick) {
+    ctx->run_id = crypto_calc_run_id(flipper_name, tick);
+    ctx->counter = 1;
 
-	memcpy(ctx->key, key, KEY_BITS / 8);
+    memcpy(ctx->key, key, KEY_BITS / 8);
 #ifdef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	return true;
+    return true;
 #else /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
-	return (gcm_setkey(&(ctx->gcm_ctx), key, KEY_BITS / 8) == 0);
+    return (gcm_setkey(&(ctx->gcm_ctx), key, KEY_BITS / 8) == 0);
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
 }
 
-void crypto_ctx_get_key(ESubGhzChatCryptoCtx *ctx, uint8_t *key)
-{
-	memcpy(key, ctx->key, KEY_BITS / 8);
+void crypto_ctx_get_key(ESubGhzChatCryptoCtx* ctx, uint8_t* key) {
+    memcpy(key, ctx->key, KEY_BITS / 8);
 }
 
-bool crypto_ctx_decrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
-		uint8_t *out)
-{
-	if (in_len < MSG_OVERHEAD + 1) {
-		return false;
-	}
-
-	struct ESubGhzChatCryptoMsg *msg = (struct ESubGhzChatCryptoMsg *) in;
-
-	// check if message is stale, if yes, discard
-	uint32_t *counter = ESubGhzChatReplayDict_get(ctx->replay_dict,
-			msg->run_id);
-	if (counter != NULL) {
-		if (*counter >= __ntohl(msg->counter)) {
-			return false;
-		}
-	}
-
-	// decrypt and auth message
+bool crypto_ctx_decrypt(ESubGhzChatCryptoCtx* ctx, uint8_t* in, size_t in_len, uint8_t* out) {
+    if(in_len < MSG_OVERHEAD + 1) {
+        return false;
+    }
+
+    struct ESubGhzChatCryptoMsg* msg = (struct ESubGhzChatCryptoMsg*)in;
+
+    // check if message is stale, if yes, discard
+    uint32_t* counter = ESubGhzChatReplayDict_get(ctx->replay_dict, msg->run_id);
+    if(counter != NULL) {
+        if(*counter >= __ntohl(msg->counter)) {
+            return false;
+        }
+    }
+
+    // decrypt and auth message
 #ifdef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	bool ret = (furi_hal_crypto_gcm_decrypt_and_verify(ctx->key,
-			msg->iv,
-			(uint8_t *) msg, RUN_ID_BYTES + COUNTER_BYTES,
-			msg->data, out,
-			in_len - MSG_OVERHEAD,
-			msg->tag) == FuriHalCryptoGCMStateOk);
+    bool ret =
+        (furi_hal_crypto_gcm_decrypt_and_verify(
+             ctx->key,
+             msg->iv,
+             (uint8_t*)msg,
+             RUN_ID_BYTES + COUNTER_BYTES,
+             msg->data,
+             out,
+             in_len - MSG_OVERHEAD,
+             msg->tag) == FuriHalCryptoGCMStateOk);
 #else /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
-	bool ret = (gcm_auth_decrypt(&(ctx->gcm_ctx),
-			msg->iv, IV_BYTES,
-			(uint8_t *) msg, RUN_ID_BYTES + COUNTER_BYTES,
-			msg->data, out,
-			in_len - MSG_OVERHEAD,
-			msg->tag, TAG_BYTES) == 0);
+    bool ret =
+        (gcm_auth_decrypt(
+             &(ctx->gcm_ctx),
+             msg->iv,
+             IV_BYTES,
+             (uint8_t*)msg,
+             RUN_ID_BYTES + COUNTER_BYTES,
+             msg->data,
+             out,
+             in_len - MSG_OVERHEAD,
+             msg->tag,
+             TAG_BYTES) == 0);
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
 
-	// if auth was successful update replay dict
-	if (ret) {
-		ESubGhzChatReplayDict_set_at(ctx->replay_dict, msg->run_id,
-				__ntohl(msg->counter));
-	}
+    // if auth was successful update replay dict
+    if(ret) {
+        ESubGhzChatReplayDict_set_at(ctx->replay_dict, msg->run_id, __ntohl(msg->counter));
+    }
 
-	return ret;
+    return ret;
 }
 
-bool crypto_ctx_encrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
-		uint8_t *out)
-{
-	struct ESubGhzChatCryptoMsg *msg = (struct ESubGhzChatCryptoMsg *) out;
+bool crypto_ctx_encrypt(ESubGhzChatCryptoCtx* ctx, uint8_t* in, size_t in_len, uint8_t* out) {
+    struct ESubGhzChatCryptoMsg* msg = (struct ESubGhzChatCryptoMsg*)out;
 
-	// fill message header
-	msg->run_id = ctx->run_id;
-	msg->counter = __htonl(ctx->counter);
-	furi_hal_random_fill_buf(msg->iv, IV_BYTES);
+    // fill message header
+    msg->run_id = ctx->run_id;
+    msg->counter = __htonl(ctx->counter);
+    furi_hal_random_fill_buf(msg->iv, IV_BYTES);
 
-	// encrypt message and store tag in header
+    // encrypt message and store tag in header
 #ifdef FURI_HAL_CRYPTO_ADVANCED_AVAIL
-	bool ret = (furi_hal_crypto_gcm_encrypt_and_tag(ctx->key,
-			msg->iv,
-			(uint8_t *) msg, RUN_ID_BYTES + COUNTER_BYTES,
-			in, msg->data,
-			in_len,
-			msg->tag) == FuriHalCryptoGCMStateOk);
+    bool ret =
+        (furi_hal_crypto_gcm_encrypt_and_tag(
+             ctx->key,
+             msg->iv,
+             (uint8_t*)msg,
+             RUN_ID_BYTES + COUNTER_BYTES,
+             in,
+             msg->data,
+             in_len,
+             msg->tag) == FuriHalCryptoGCMStateOk);
 #else /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
-	bool ret = (gcm_crypt_and_tag(&(ctx->gcm_ctx), ENCRYPT,
-			msg->iv, IV_BYTES,
-			(uint8_t *) msg, RUN_ID_BYTES + COUNTER_BYTES,
-			in, msg->data,
-			in_len,
-			msg->tag, TAG_BYTES) == 0);
+    bool ret =
+        (gcm_crypt_and_tag(
+             &(ctx->gcm_ctx),
+             ENCRYPT,
+             msg->iv,
+             IV_BYTES,
+             (uint8_t*)msg,
+             RUN_ID_BYTES + COUNTER_BYTES,
+             in,
+             msg->data,
+             in_len,
+             msg->tag,
+             TAG_BYTES) == 0);
 #endif /* FURI_HAL_CRYPTO_ADVANCED_AVAIL */
 
-	// update replay dict and increase internal counter
-	if (ret) {
-		ESubGhzChatReplayDict_set_at(ctx->replay_dict, ctx->run_id,
-				ctx->counter);
-		ctx->counter++;
-	}
+    // update replay dict and increase internal counter
+    if(ret) {
+        ESubGhzChatReplayDict_set_at(ctx->replay_dict, ctx->run_id, ctx->counter);
+        ctx->counter++;
+    }
 
-	return ret;
+    return ret;
 }
 
-size_t crypto_ctx_dump_replay_dict(ESubGhzChatCryptoCtx *ctx,
-		CryptoCtxReplayDictWriter writer, void *writer_ctx)
-{
-	size_t ret = 0;
-	ESubGhzChatReplayDict_it_t i;
-
-	for (ESubGhzChatReplayDict_it(i, ctx->replay_dict);
-			!ESubGhzChatReplayDict_end_p(i);
-			ESubGhzChatReplayDict_next(i), ret++) {
-		ESubGhzChatReplayDict_itref_t *ref =
-			ESubGhzChatReplayDict_ref(i);
-		if (!writer(ref->key, ref->value, writer_ctx)) {
-			break;
-		}
-	}
-
-	return ret;
+size_t crypto_ctx_dump_replay_dict(
+    ESubGhzChatCryptoCtx* ctx,
+    CryptoCtxReplayDictWriter writer,
+    void* writer_ctx) {
+    size_t ret = 0;
+    ESubGhzChatReplayDict_it_t i;
+
+    for(ESubGhzChatReplayDict_it(i, ctx->replay_dict); !ESubGhzChatReplayDict_end_p(i);
+        ESubGhzChatReplayDict_next(i), ret++) {
+        ESubGhzChatReplayDict_itref_t* ref = ESubGhzChatReplayDict_ref(i);
+        if(!writer(ref->key, ref->value, writer_ctx)) {
+            break;
+        }
+    }
+
+    return ret;
 }
 
-size_t crypto_ctx_read_replay_dict(ESubGhzChatCryptoCtx *ctx,
-		CryptoCtxReplayDictReader reader, void *reader_ctx)
-{
-	size_t ret = 0;
+size_t crypto_ctx_read_replay_dict(
+    ESubGhzChatCryptoCtx* ctx,
+    CryptoCtxReplayDictReader reader,
+    void* reader_ctx) {
+    size_t ret = 0;
 
-	uint64_t run_id;
-	uint32_t counter;
+    uint64_t run_id;
+    uint32_t counter;
 
-	while (reader(&run_id, &counter, reader_ctx)) {
-		ESubGhzChatReplayDict_set_at(ctx->replay_dict, run_id,
-				counter);
-		ret++;
-	}
+    while(reader(&run_id, &counter, reader_ctx)) {
+        ESubGhzChatReplayDict_set_at(ctx->replay_dict, run_id, counter);
+        ret++;
+    }
 
-	return ret;
+    return ret;
 }

+ 28 - 25
esubghz_chat/crypto_wrapper.h

@@ -17,31 +17,34 @@ typedef struct ESugGhzChatCryptoCtx ESubGhzChatCryptoCtx;
 void crypto_init(void);
 
 /* Function to clear sensitive memory. */
-void crypto_explicit_bzero(void *s, size_t len);
-
-ESubGhzChatCryptoCtx *crypto_ctx_alloc(void);
-void crypto_ctx_free(ESubGhzChatCryptoCtx *ctx);
-
-void crypto_ctx_clear(ESubGhzChatCryptoCtx *ctx);
-
-bool crypto_ctx_set_key(ESubGhzChatCryptoCtx *ctx, const uint8_t *key,
-		FuriString *flipper_name, uint32_t tick);
-void crypto_ctx_get_key(ESubGhzChatCryptoCtx *ctx, uint8_t *key);
-
-bool crypto_ctx_decrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
-		uint8_t *out);
-bool crypto_ctx_encrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
-		uint8_t *out);
-
-typedef bool (*CryptoCtxReplayDictWriter)(uint64_t run_id, uint32_t counter,
-		void *context);
-typedef bool (*CryptoCtxReplayDictReader)(uint64_t *run_id, uint32_t *counter,
-		void *context);
-
-size_t crypto_ctx_dump_replay_dict(ESubGhzChatCryptoCtx *ctx,
-		CryptoCtxReplayDictWriter writer, void *writer_ctx);
-size_t crypto_ctx_read_replay_dict(ESubGhzChatCryptoCtx *ctx,
-		CryptoCtxReplayDictReader reader, void *reader_ctx);
+void crypto_explicit_bzero(void* s, size_t len);
+
+ESubGhzChatCryptoCtx* crypto_ctx_alloc(void);
+void crypto_ctx_free(ESubGhzChatCryptoCtx* ctx);
+
+void crypto_ctx_clear(ESubGhzChatCryptoCtx* ctx);
+
+bool crypto_ctx_set_key(
+    ESubGhzChatCryptoCtx* ctx,
+    const uint8_t* key,
+    FuriString* flipper_name,
+    uint32_t tick);
+void crypto_ctx_get_key(ESubGhzChatCryptoCtx* ctx, uint8_t* key);
+
+bool crypto_ctx_decrypt(ESubGhzChatCryptoCtx* ctx, uint8_t* in, size_t in_len, uint8_t* out);
+bool crypto_ctx_encrypt(ESubGhzChatCryptoCtx* ctx, uint8_t* in, size_t in_len, uint8_t* out);
+
+typedef bool (*CryptoCtxReplayDictWriter)(uint64_t run_id, uint32_t counter, void* context);
+typedef bool (*CryptoCtxReplayDictReader)(uint64_t* run_id, uint32_t* counter, void* context);
+
+size_t crypto_ctx_dump_replay_dict(
+    ESubGhzChatCryptoCtx* ctx,
+    CryptoCtxReplayDictWriter writer,
+    void* writer_ctx);
+size_t crypto_ctx_read_replay_dict(
+    ESubGhzChatCryptoCtx* ctx,
+    CryptoCtxReplayDictReader reader,
+    void* reader_ctx);
 
 #ifdef __cplusplus
 }

+ 622 - 689
esubghz_chat/esubghz_chat.c

@@ -16,859 +16,792 @@
 
 /* Callback for RX events from the Sub-GHz worker. Records the current ticks as
  * the time of the last reception. */
-static void have_read_cb(void* context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static void have_read_cb(void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	state->last_time_rx_data = furi_get_tick();
+    state->last_time_rx_data = furi_get_tick();
 }
 
 /* Sets the header for the chat input field depending on whether or not a
  * message preview exists. */
-void set_chat_input_header(ESubGhzChatState *state)
-{
-	if (strlen(state->msg_preview) == 0) {
-		text_input_set_header_text(state->text_input, "Message");
-	} else {
-		text_input_set_header_text(state->text_input,
-				state->msg_preview);
-	}
+void set_chat_input_header(ESubGhzChatState* state) {
+    if(strlen(state->msg_preview) == 0) {
+        text_input_set_header_text(state->text_input, "Message");
+    } else {
+        text_input_set_header_text(state->text_input, state->msg_preview);
+    }
 }
 
 /* Appends the latest message to the chat box and prepares the message preview.
  */
-void append_msg(ESubGhzChatState *state, const char *msg)
-{
-	/* append message to text box */
-	furi_string_cat_printf(state->chat_box_store, "\n%s", msg);
-
-	/* prepare message preview */
-	strncpy(state->msg_preview, msg, MSG_PREVIEW_SIZE);
-	state->msg_preview[MSG_PREVIEW_SIZE] = 0;
-	set_chat_input_header(state);
-
-	/* reset text box contents and focus */
-	text_box_set_text(state->chat_box,
-			furi_string_get_cstr(state->chat_box_store));
-	text_box_set_focus(state->chat_box, TextBoxFocusEnd);
+void append_msg(ESubGhzChatState* state, const char* msg) {
+    /* append message to text box */
+    furi_string_cat_printf(state->chat_box_store, "\n%s", msg);
+
+    /* prepare message preview */
+    strncpy(state->msg_preview, msg, MSG_PREVIEW_SIZE);
+    state->msg_preview[MSG_PREVIEW_SIZE] = 0;
+    set_chat_input_header(state);
+
+    /* reset text box contents and focus */
+    text_box_set_text(state->chat_box, furi_string_get_cstr(state->chat_box_store));
+    text_box_set_focus(state->chat_box, TextBoxFocusEnd);
 }
 
 /* Decrypts a message for post_rx(). */
-static bool post_rx_decrypt(ESubGhzChatState *state, size_t rx_size)
-{
-	bool ret = crypto_ctx_decrypt(state->crypto_ctx,
-			state->rx_buffer, rx_size,
-			(uint8_t*) state->rx_str_buffer);
-
-	if (ret) {
-		state->rx_str_buffer[rx_size - (MSG_OVERHEAD)] = 0;
-	} else {
-		state->rx_str_buffer[0] = 0;
-	}
-
-	return ret;
+static bool post_rx_decrypt(ESubGhzChatState* state, size_t rx_size) {
+    bool ret = crypto_ctx_decrypt(
+        state->crypto_ctx, state->rx_buffer, rx_size, (uint8_t*)state->rx_str_buffer);
+
+    if(ret) {
+        state->rx_str_buffer[rx_size - (MSG_OVERHEAD)] = 0;
+    } else {
+        state->rx_str_buffer[0] = 0;
+    }
+
+    return ret;
 }
 
 /* Post RX handler, decrypts received messages and calls append_msg(). */
-static void post_rx(ESubGhzChatState *state, size_t rx_size)
-{
-	furi_assert(state);
+static void post_rx(ESubGhzChatState* state, size_t rx_size) {
+    furi_assert(state);
 
-	if (rx_size == 0) {
-		return;
-	}
+    if(rx_size == 0) {
+        return;
+    }
 
-	furi_check(rx_size <= RX_TX_BUFFER_SIZE);
+    furi_check(rx_size <= RX_TX_BUFFER_SIZE);
 
-	/* decrypt if necessary */
-	if (!state->encrypted) {
-		memcpy(state->rx_str_buffer, state->rx_buffer, rx_size);
-		state->rx_str_buffer[rx_size] = 0;
+    /* decrypt if necessary */
+    if(!state->encrypted) {
+        memcpy(state->rx_str_buffer, state->rx_buffer, rx_size);
+        state->rx_str_buffer[rx_size] = 0;
 
-		/* remove trailing newline if it is there, for compat with CLI
+        /* remove trailing newline if it is there, for compat with CLI
 		 * Sub-GHz chat */
-		if (state->rx_str_buffer[rx_size - 1] == '\n') {
-			state->rx_str_buffer[rx_size - 1] = 0;
-		}
-	} else {
-		/* if decryption fails output an error message */
-		if (!post_rx_decrypt(state, rx_size)) {
-			strcpy(state->rx_str_buffer, "ERR: Decryption failed!");
-		}
-	}
-
-	/* append message to text box and prepare message preview */
-	append_msg(state, state->rx_str_buffer);
-
-	/* send notification (make the flipper vibrate) */
-	notification_message(state->notification, &sequence_single_vibro);
+        if(state->rx_str_buffer[rx_size - 1] == '\n') {
+            state->rx_str_buffer[rx_size - 1] = 0;
+        }
+    } else {
+        /* if decryption fails output an error message */
+        if(!post_rx_decrypt(state, rx_size)) {
+            strcpy(state->rx_str_buffer, "ERR: Decryption failed!");
+        }
+    }
+
+    /* append message to text box and prepare message preview */
+    append_msg(state, state->rx_str_buffer);
+
+    /* send notification (make the flipper vibrate) */
+    notification_message(state->notification, &sequence_single_vibro);
 }
 
 /* Reads the message from msg_input, encrypts it if necessary and then
  * transmits it. */
-void tx_msg_input(ESubGhzChatState *state)
-{
-	/* encrypt message if necessary */
-	size_t msg_len = strlen(furi_string_get_cstr(state->msg_input));
-	size_t tx_size = msg_len;
-	if (state->encrypted) {
-		tx_size += MSG_OVERHEAD;
-		furi_check(tx_size <= sizeof(state->tx_buffer));
-
-		crypto_ctx_encrypt(state->crypto_ctx,
-				(uint8_t *)
-				furi_string_get_cstr(state->msg_input),
-				msg_len,
-				state->tx_buffer);
-	} else {
-		tx_size += 2;
-		furi_check(tx_size <= sizeof(state->tx_buffer));
-		memcpy(state->tx_buffer,
-				furi_string_get_cstr(state->msg_input),
-				msg_len);
-
-		/* append \r\n for compat with Sub-GHz CLI chat */
-		state->tx_buffer[msg_len] = '\r';
-		state->tx_buffer[msg_len + 1] = '\n';
-	}
-
-	/* transmit */
-	subghz_tx_rx_worker_write(state->subghz_worker, state->tx_buffer,
-			tx_size);
+void tx_msg_input(ESubGhzChatState* state) {
+    /* encrypt message if necessary */
+    size_t msg_len = strlen(furi_string_get_cstr(state->msg_input));
+    size_t tx_size = msg_len;
+    if(state->encrypted) {
+        tx_size += MSG_OVERHEAD;
+        furi_check(tx_size <= sizeof(state->tx_buffer));
+
+        crypto_ctx_encrypt(
+            state->crypto_ctx,
+            (uint8_t*)furi_string_get_cstr(state->msg_input),
+            msg_len,
+            state->tx_buffer);
+    } else {
+        tx_size += 2;
+        furi_check(tx_size <= sizeof(state->tx_buffer));
+        memcpy(state->tx_buffer, furi_string_get_cstr(state->msg_input), msg_len);
+
+        /* append \r\n for compat with Sub-GHz CLI chat */
+        state->tx_buffer[msg_len] = '\r';
+        state->tx_buffer[msg_len + 1] = '\n';
+    }
+
+    /* transmit */
+    subghz_tx_rx_worker_write(state->subghz_worker, state->tx_buffer, tx_size);
 }
 
 /* Displays information on frequency, encryption and radio type in the text
  * box. Also clears the text input buffer to remove the password and starts the
  * Sub-GHz worker. After starting the worker a join message is transmitted. */
-void enter_chat(ESubGhzChatState *state)
-{
-	furi_string_cat_printf(state->chat_box_store, "Frequency: %lu",
-			state->frequency);
-
-	furi_string_cat_printf(state->chat_box_store, "\nEncrypted: %s",
-			(state->encrypted ? "yes" : "no"));
+void enter_chat(ESubGhzChatState* state) {
+    furi_string_cat_printf(state->chat_box_store, "Frequency: %lu", state->frequency);
 
-	subghz_tx_rx_worker_start(state->subghz_worker, state->subghz_device,
-			state->frequency);
+    furi_string_cat_printf(
+        state->chat_box_store, "\nEncrypted: %s", (state->encrypted ? "yes" : "no"));
 
-	if (strcmp(state->subghz_device->name, "cc1101_ext") == 0) {
-		furi_string_cat_printf(state->chat_box_store,
-				"\nRadio: External");
-	} else {
-		furi_string_cat_printf(state->chat_box_store,
-				"\nRadio: Internal");
-	}
+    subghz_tx_rx_worker_start(state->subghz_worker, state->subghz_device, state->frequency);
 
+    if(strcmp(state->subghz_device->name, "cc1101_ext") == 0) {
+        furi_string_cat_printf(state->chat_box_store, "\nRadio: External");
+    } else {
+        furi_string_cat_printf(state->chat_box_store, "\nRadio: Internal");
+    }
 
-	/* concatenate the name prefix and join message */
-	furi_string_set(state->msg_input, state->name_prefix);
-	furi_string_cat_str(state->msg_input, " joined chat.");
+    /* concatenate the name prefix and join message */
+    furi_string_set(state->msg_input, state->name_prefix);
+    furi_string_cat_str(state->msg_input, " joined chat.");
 
-	/* encrypt and transmit message */
-	tx_msg_input(state);
+    /* encrypt and transmit message */
+    tx_msg_input(state);
 
-	/* clear message input buffer */
-	furi_string_set_char(state->msg_input, 0, 0);
+    /* clear message input buffer */
+    furi_string_set_char(state->msg_input, 0, 0);
 }
 
 /* Sends a leave message */
-void exit_chat(ESubGhzChatState *state)
-{
-	/* concatenate the name prefix and leave message */
-	furi_string_set(state->msg_input, state->name_prefix);
-	furi_string_cat_str(state->msg_input, " left chat.");
+void exit_chat(ESubGhzChatState* state) {
+    /* concatenate the name prefix and leave message */
+    furi_string_set(state->msg_input, state->name_prefix);
+    furi_string_cat_str(state->msg_input, " left chat.");
 
-	/* encrypt and transmit message */
-	tx_msg_input(state);
+    /* encrypt and transmit message */
+    tx_msg_input(state);
 
-	/* clear message input buffer */
-	furi_string_set_char(state->msg_input, 0, 0);
+    /* clear message input buffer */
+    furi_string_set_char(state->msg_input, 0, 0);
 
-	/* wait for leave message to be delivered */
-	furi_delay_ms(CHAT_LEAVE_DELAY);
+    /* wait for leave message to be delivered */
+    furi_delay_ms(CHAT_LEAVE_DELAY);
 }
 
 /* Whether or not to display the locked message. */
-static bool kbd_lock_msg_display(ESubGhzChatState *state)
-{
-	return (state->kbd_lock_msg_ticks != 0);
+static bool kbd_lock_msg_display(ESubGhzChatState* state) {
+    return (state->kbd_lock_msg_ticks != 0);
 }
 
 /* Whether or not to hide the locked message again. */
-static bool kbd_lock_msg_reset_timeout(ESubGhzChatState *state)
-{
-	if (state->kbd_lock_msg_ticks == 0) {
-		return false;
-	}
+static bool kbd_lock_msg_reset_timeout(ESubGhzChatState* state) {
+    if(state->kbd_lock_msg_ticks == 0) {
+        return false;
+    }
 
-	if (furi_get_tick() - state->kbd_lock_msg_ticks > KBD_UNLOCK_TIMEOUT) {
-		return true;
-	}
+    if(furi_get_tick() - state->kbd_lock_msg_ticks > KBD_UNLOCK_TIMEOUT) {
+        return true;
+    }
 
-	return false;
+    return false;
 }
 
 /* Resets the timeout for the locked message and turns off the backlight if
  * specified. */
-static void kbd_lock_msg_reset(ESubGhzChatState *state, bool backlight_off)
-{
-	state->kbd_lock_msg_ticks = 0;
-	state->kbd_lock_count = 0;
-
-	if (backlight_off) {
-		notification_message(state->notification,
-				&sequence_display_backlight_off);
-	}
+static void kbd_lock_msg_reset(ESubGhzChatState* state, bool backlight_off) {
+    state->kbd_lock_msg_ticks = 0;
+    state->kbd_lock_count = 0;
+
+    if(backlight_off) {
+        notification_message(state->notification, &sequence_display_backlight_off);
+    }
 }
 
 /* Locks the keyboard. */
-static void kbd_lock(ESubGhzChatState *state)
-{
-	state->kbd_locked = true;
-	kbd_lock_msg_reset(state, true);
+static void kbd_lock(ESubGhzChatState* state) {
+    state->kbd_locked = true;
+    kbd_lock_msg_reset(state, true);
 }
 
 /* Unlocks the keyboard. */
-static void kbd_unlock(ESubGhzChatState *state)
-{
-	state->kbd_locked = false;
-	kbd_lock_msg_reset(state, false);
+static void kbd_unlock(ESubGhzChatState* state) {
+    state->kbd_locked = false;
+    kbd_lock_msg_reset(state, false);
 }
 
 /* Custom event callback for view dispatcher. Just calls scene manager. */
-static bool esubghz_chat_custom_event_callback(void* context, uint32_t event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_custom_event_callback");
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-	return scene_manager_handle_custom_event(state->scene_manager, event);
+static bool esubghz_chat_custom_event_callback(void* context, uint32_t event) {
+    FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_custom_event_callback");
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+    return scene_manager_handle_custom_event(state->scene_manager, event);
 }
 
 /* Navigation event callback for view dispatcher. Just calls scene manager. */
-static bool esubghz_chat_navigation_event_callback(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_navigation_event_callback");
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-	return scene_manager_handle_back_event(state->scene_manager);
+static bool esubghz_chat_navigation_event_callback(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_navigation_event_callback");
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+    return scene_manager_handle_back_event(state->scene_manager);
 }
 
-static void esubghz_chat_check_messages(ESubGhzChatState *state)
-{
-	/* if the maximum message size was reached or the
+static void esubghz_chat_check_messages(ESubGhzChatState* state) {
+    /* if the maximum message size was reached or the
 	 * MESSAGE_COMPLETION_TIMEOUT has expired, retrieve a message and call
 	 * post_rx() */
-	size_t avail = 0;
-	while ((avail = subghz_tx_rx_worker_available(state->subghz_worker)) >
-			0) {
-		volatile uint32_t since_last_rx = furi_get_tick() -
-			state->last_time_rx_data;
-		if (avail < RX_TX_BUFFER_SIZE && since_last_rx <
-				MESSAGE_COMPLETION_TIMEOUT) {
-			break;
-		}
-
-		size_t rx_size = subghz_tx_rx_worker_read(state->subghz_worker,
-				state->rx_buffer, RX_TX_BUFFER_SIZE);
-		post_rx(state, rx_size);
-	}
+    size_t avail = 0;
+    while((avail = subghz_tx_rx_worker_available(state->subghz_worker)) > 0) {
+        volatile uint32_t since_last_rx = furi_get_tick() - state->last_time_rx_data;
+        if(avail < RX_TX_BUFFER_SIZE && since_last_rx < MESSAGE_COMPLETION_TIMEOUT) {
+            break;
+        }
+
+        size_t rx_size =
+            subghz_tx_rx_worker_read(state->subghz_worker, state->rx_buffer, RX_TX_BUFFER_SIZE);
+        post_rx(state, rx_size);
+    }
 }
 
 /* Tick event callback for view dispatcher. Called every TICK_INTERVAL. Resets
  * the locked message if necessary. Retrieves a received message from the
  * Sub-GHz worker and calls post_rx(). Then calls the scene manager. */
-static void esubghz_chat_tick_event_callback(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_tick_event_callback");
+static void esubghz_chat_tick_event_callback(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "esubghz_chat_tick_event_callback");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	/* reset locked message if necessary */
-	if (kbd_lock_msg_reset_timeout(state)) {
-		kbd_lock_msg_reset(state, true);
-	}
+    /* reset locked message if necessary */
+    if(kbd_lock_msg_reset_timeout(state)) {
+        kbd_lock_msg_reset(state, true);
+    }
 
-	esubghz_chat_check_messages(state);
+    esubghz_chat_check_messages(state);
 
-	/* call scene manager */
-	scene_manager_handle_tick_event(state->scene_manager);
+    /* call scene manager */
+    scene_manager_handle_tick_event(state->scene_manager);
 }
 
 /* Hooks into the view port's draw callback to overlay the keyboard locked
  * message. */
-static void esubghz_hooked_draw_callback(Canvas* canvas, void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "esubghz_hooked_draw_callback");
-
-	furi_assert(canvas);
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	/* call original callback */
-	state->orig_draw_cb(canvas, state->view_dispatcher);
-
-	/* display if the keyboard is locked */
-	if (state->kbd_locked) {
-		canvas_set_font(canvas, FontPrimary);
-		elements_multiline_text_framed(canvas, 42, 30, "Locked");
-	}
-
-	/* display the unlock message if necessary */
-	if (kbd_lock_msg_display(state)) {
-		canvas_set_font(canvas, FontSecondary);
-		elements_bold_rounded_frame(canvas, 14, 8, 99, 48);
-		elements_multiline_text(canvas, 65, 26, "To unlock\npress:");
-		canvas_draw_icon(canvas, 65, 42, &I_Pin_back_arrow_10x8);
-		canvas_draw_icon(canvas, 80, 42, &I_Pin_back_arrow_10x8);
-		canvas_draw_icon(canvas, 95, 42, &I_Pin_back_arrow_10x8);
-		canvas_draw_icon(canvas, 16, 13, &I_WarningDolphin_45x42);
-	}
+static void esubghz_hooked_draw_callback(Canvas* canvas, void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "esubghz_hooked_draw_callback");
+
+    furi_assert(canvas);
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    /* call original callback */
+    state->orig_draw_cb(canvas, state->view_dispatcher);
+
+    /* display if the keyboard is locked */
+    if(state->kbd_locked) {
+        canvas_set_font(canvas, FontPrimary);
+        elements_multiline_text_framed(canvas, 42, 30, "Locked");
+    }
+
+    /* display the unlock message if necessary */
+    if(kbd_lock_msg_display(state)) {
+        canvas_set_font(canvas, FontSecondary);
+        elements_bold_rounded_frame(canvas, 14, 8, 99, 48);
+        elements_multiline_text(canvas, 65, 26, "To unlock\npress:");
+        canvas_draw_icon(canvas, 65, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 80, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 95, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 16, 13, &I_WarningDolphin_45x42);
+    }
 }
 
 /* Hooks into the view port's input callback to handle the user locking the
  * keyboard. */
-static void esubghz_hooked_input_callback(InputEvent* event, void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "esubghz_hooked_input_callback");
+static void esubghz_hooked_input_callback(InputEvent* event, void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "esubghz_hooked_input_callback");
 
-	furi_assert(event);
+    furi_assert(event);
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	/* if the keyboard is locked no key presses are forwarded */
-	if (state->kbd_locked) {
-		/* key has been pressed, display the unlock message and
+    /* if the keyboard is locked no key presses are forwarded */
+    if(state->kbd_locked) {
+        /* key has been pressed, display the unlock message and
 		 * initiate the timer */
-		if (state->kbd_lock_count == 0) {
-			state->kbd_lock_msg_ticks = furi_get_tick();
-		}
-
-		/* back button has been pressed, increase the lock counter */
-		if (event->key == InputKeyBack && event->type ==
-				InputTypeShort) {
-			state->kbd_lock_count++;
-		}
-
-		/* unlock the keyboard */
-		if (state->kbd_lock_count >= KBD_UNLOCK_CNT) {
-			kbd_unlock(state);
-		}
-
-		/* do not handle the event */
-		return;
-	}
-
-	/* handle long press of back key to exit for real */
-	if (event->key == InputKeyBack) {
-		if (state->view_dispatcher->current_view ==
-				text_input_get_view(state->text_input)) {
-			if (event->type == InputTypeLong) {
-				state->exit_for_real = true;
-				view_dispatcher_stop(state->view_dispatcher);
-				return;
-			}
-		}
-	}
-
-	if (event->key == InputKeyOk) {
-		/* if we are in the chat view and no input is ongoing, allow
+        if(state->kbd_lock_count == 0) {
+            state->kbd_lock_msg_ticks = furi_get_tick();
+        }
+
+        /* back button has been pressed, increase the lock counter */
+        if(event->key == InputKeyBack && event->type == InputTypeShort) {
+            state->kbd_lock_count++;
+        }
+
+        /* unlock the keyboard */
+        if(state->kbd_lock_count >= KBD_UNLOCK_CNT) {
+            kbd_unlock(state);
+        }
+
+        /* do not handle the event */
+        return;
+    }
+
+    /* handle long press of back key to exit for real */
+    if(event->key == InputKeyBack) {
+        if(state->view_dispatcher->current_view == text_input_get_view(state->text_input)) {
+            if(event->type == InputTypeLong) {
+                state->exit_for_real = true;
+                view_dispatcher_stop(state->view_dispatcher);
+                return;
+            }
+        }
+    }
+
+    if(event->key == InputKeyOk) {
+        /* if we are in the chat view and no input is ongoing, allow
 		 * locking */
-		if (state->view_dispatcher->current_view ==
-				text_box_get_view(state->chat_box) &&
-				!(state->kbd_ok_input_ongoing)) {
-			/* lock keyboard upon long press of Ok button */
-			if (event->type == InputTypeLong) {
-				kbd_lock(state);
-			}
-
-			/* do not handle any Ok key events to prevent blocking
+        if(state->view_dispatcher->current_view == text_box_get_view(state->chat_box) &&
+           !(state->kbd_ok_input_ongoing)) {
+            /* lock keyboard upon long press of Ok button */
+            if(event->type == InputTypeLong) {
+                kbd_lock(state);
+            }
+
+            /* do not handle any Ok key events to prevent blocking
 			 * of other keys */
-			return;
-		}
-
-		/* handle ongoing inputs when changing to chat view */
-		if (event->type == InputTypePress) {
-			state->kbd_ok_input_ongoing = true;
-		} else if (event->type == InputTypeRelease) {
-			state->kbd_ok_input_ongoing = false;
-		}
-	}
-
-	if (event->key == InputKeyLeft) {
-		/* if we are in the chat view and no input is ongoing, allow
+            return;
+        }
+
+        /* handle ongoing inputs when changing to chat view */
+        if(event->type == InputTypePress) {
+            state->kbd_ok_input_ongoing = true;
+        } else if(event->type == InputTypeRelease) {
+            state->kbd_ok_input_ongoing = false;
+        }
+    }
+
+    if(event->key == InputKeyLeft) {
+        /* if we are in the chat view and no input is ongoing, allow
 		 * switching to msg input */
-		if (state->view_dispatcher->current_view ==
-				text_box_get_view(state->chat_box) &&
-				!(state->kbd_left_input_ongoing)) {
-			/* go to msg input upon short press of Left button */
-			if (event->type == InputTypeShort) {
-				view_dispatcher_send_custom_event(state->view_dispatcher,
-						ESubGhzChatEvent_GotoMsgInput);
-			}
-
-			/* do not handle any Left key events to prevent
+        if(state->view_dispatcher->current_view == text_box_get_view(state->chat_box) &&
+           !(state->kbd_left_input_ongoing)) {
+            /* go to msg input upon short press of Left button */
+            if(event->type == InputTypeShort) {
+                view_dispatcher_send_custom_event(
+                    state->view_dispatcher, ESubGhzChatEvent_GotoMsgInput);
+            }
+
+            /* do not handle any Left key events to prevent
 			 * blocking of other keys */
-			return;
-		}
-
-		/* handle ongoing inputs when changing to chat view */
-		if (event->type == InputTypePress) {
-			state->kbd_left_input_ongoing = true;
-		} else if (event->type == InputTypeRelease) {
-			state->kbd_left_input_ongoing = false;
-		}
-	}
-
-	if (event->key == InputKeyRight) {
-		/* if we are in the chat view and no input is ongoing, allow
+            return;
+        }
+
+        /* handle ongoing inputs when changing to chat view */
+        if(event->type == InputTypePress) {
+            state->kbd_left_input_ongoing = true;
+        } else if(event->type == InputTypeRelease) {
+            state->kbd_left_input_ongoing = false;
+        }
+    }
+
+    if(event->key == InputKeyRight) {
+        /* if we are in the chat view and no input is ongoing, allow
 		 * switching to key display */
-		if (state->view_dispatcher->current_view ==
-				text_box_get_view(state->chat_box) &&
-				!(state->kbd_right_input_ongoing)) {
-			/* go to key display upon short press of Right button
+        if(state->view_dispatcher->current_view == text_box_get_view(state->chat_box) &&
+           !(state->kbd_right_input_ongoing)) {
+            /* go to key display upon short press of Right button
 			 */
-			if (event->type == InputTypeShort) {
-				view_dispatcher_send_custom_event(state->view_dispatcher,
-						ESubGhzChatEvent_GotoKeyDisplay);
-			}
+            if(event->type == InputTypeShort) {
+                view_dispatcher_send_custom_event(
+                    state->view_dispatcher, ESubGhzChatEvent_GotoKeyDisplay);
+            }
 
-			/* do not handle any Right key events to prevent
+            /* do not handle any Right key events to prevent
 			 * blocking of other keys */
-			return;
-		}
-
-		/* handle ongoing inputs when changing to chat view */
-		if (event->type == InputTypePress) {
-			state->kbd_right_input_ongoing = true;
-		} else if (event->type == InputTypeRelease) {
-			state->kbd_right_input_ongoing = false;
-		}
-	}
-
-	/* call original callback */
-	state->orig_input_cb(event, state->view_dispatcher);
+            return;
+        }
+
+        /* handle ongoing inputs when changing to chat view */
+        if(event->type == InputTypePress) {
+            state->kbd_right_input_ongoing = true;
+        } else if(event->type == InputTypeRelease) {
+            state->kbd_right_input_ongoing = false;
+        }
+    }
+
+    /* call original callback */
+    state->orig_input_cb(event, state->view_dispatcher);
 }
 
-static const char *esubghz_get_bgloader_app_path(const char *args)
-{
-	size_t base_args_len = strlen(APP_BASE_ARGS);
+static const char* esubghz_get_bgloader_app_path(const char* args) {
+    size_t base_args_len = strlen(APP_BASE_ARGS);
 
-	return (args + base_args_len + 1);
+    return (args + base_args_len + 1);
 }
 
-static bool esubghz_run_with_bgloader(const char *args)
-{
-	size_t base_args_len = strlen(APP_BASE_ARGS);
+static bool esubghz_run_with_bgloader(const char* args) {
+    size_t base_args_len = strlen(APP_BASE_ARGS);
 
-	if (args == NULL) {
-		return false;
-	}
+    if(args == NULL) {
+        return false;
+    }
 
-	if (strncmp(args, APP_BASE_ARGS, base_args_len) != 0) {
-		return false;
-	}
+    if(strncmp(args, APP_BASE_ARGS, base_args_len) != 0) {
+        return false;
+    }
 
-	if (strlen(args) < base_args_len + 2) {
-		return false;
-	}
+    if(strlen(args) < base_args_len + 2) {
+        return false;
+    }
 
-	if (args[base_args_len] != ':') {
-		return false;
-	}
+    if(args[base_args_len] != ':') {
+        return false;
+    }
 
-	const char *app_path = esubghz_get_bgloader_app_path(args);
-	return furi_record_exists(app_path);
+    const char* app_path = esubghz_get_bgloader_app_path(args);
+    return furi_record_exists(app_path);
 }
 
-static void esubghz_attach_to_gui(ESubGhzChatState *state)
-{
-	Gui *gui = furi_record_open(RECORD_GUI);
-	view_dispatcher_attach_to_gui(state->view_dispatcher, gui,
-			ViewDispatcherTypeFullscreen);
+static void esubghz_attach_to_gui(ESubGhzChatState* state) {
+    Gui* gui = furi_record_open(RECORD_GUI);
+    view_dispatcher_attach_to_gui(state->view_dispatcher, gui, ViewDispatcherTypeFullscreen);
 }
 
-static void esubghz_detach_from_gui(ESubGhzChatState *state)
-{
-	gui_remove_view_port(state->view_dispatcher->gui,
-			state->view_dispatcher->view_port);
-	state->view_dispatcher->gui = NULL;
-	furi_record_close(RECORD_GUI);
+static void esubghz_detach_from_gui(ESubGhzChatState* state) {
+    gui_remove_view_port(state->view_dispatcher->gui, state->view_dispatcher->view_port);
+    state->view_dispatcher->gui = NULL;
+    furi_record_close(RECORD_GUI);
 }
 
-static void esubghz_bgloader_loop(ESubGhzChatState *state, const char
-		*bg_app_path)
-{
-	while (true) {
-		view_dispatcher_run(state->view_dispatcher);
-		
-		if (state->exit_for_real) {
-			/* exit for real */
-			break;
-		}
-		
-		BGLoaderApp *bg_app = furi_record_open(bg_app_path);
-		
-		/* signal loader that we're ready to go to background */
-		BGLoaderMessage msg;
-		msg.type = BGLoaderMessageType_LoaderBackground;
-		furi_check(furi_message_queue_put(bg_app->to_loader, &msg,
-					FuriWaitForever) == FuriStatusOk);
-		
-		esubghz_detach_from_gui(state);
-
-		while (true) {
-			/* wait for loader to wake us up again */
-			if (furi_message_queue_get(bg_app->to_app, &msg,
-						TICK_INTERVAL) != FuriStatusOk)
-			{
-				/* check for messages on timeout */
-				esubghz_chat_check_messages(state);
-				continue;
-			}
-			if (msg.type == BGLoaderMessageType_AppReattached) {
-				break;
-			} else {
-				furi_check(0);
-			}
-		}
-		
-		furi_record_close(bg_app_path);
-		
-		esubghz_attach_to_gui(state);
+static void esubghz_bgloader_loop(ESubGhzChatState* state, const char* bg_app_path) {
+    while(true) {
+        view_dispatcher_run(state->view_dispatcher);
+
+        if(state->exit_for_real) {
+            /* exit for real */
+            break;
+        }
+
+        BGLoaderApp* bg_app = furi_record_open(bg_app_path);
+
+        /* signal loader that we're ready to go to background */
+        BGLoaderMessage msg;
+        msg.type = BGLoaderMessageType_LoaderBackground;
+        furi_check(
+            furi_message_queue_put(bg_app->to_loader, &msg, FuriWaitForever) == FuriStatusOk);
+
+        esubghz_detach_from_gui(state);
+
+        while(true) {
+            /* wait for loader to wake us up again */
+            if(furi_message_queue_get(bg_app->to_app, &msg, TICK_INTERVAL) != FuriStatusOk) {
+                /* check for messages on timeout */
+                esubghz_chat_check_messages(state);
+                continue;
+            }
+            if(msg.type == BGLoaderMessageType_AppReattached) {
+                break;
+            } else {
+                furi_check(0);
+            }
         }
+
+        furi_record_close(bg_app_path);
+
+        esubghz_attach_to_gui(state);
+    }
 }
 
-static bool helper_strings_alloc(ESubGhzChatState *state)
-{
-	furi_assert(state);
+static bool helper_strings_alloc(ESubGhzChatState* state) {
+    furi_assert(state);
 
-	state->name_prefix = furi_string_alloc();
-	if (state->name_prefix == NULL) {
-		return false;
-	}
+    state->name_prefix = furi_string_alloc();
+    if(state->name_prefix == NULL) {
+        return false;
+    }
 
-	state->msg_input = furi_string_alloc();
-	if (state->msg_input == NULL) {
-		furi_string_free(state->name_prefix);
-		return false;
-	}
+    state->msg_input = furi_string_alloc();
+    if(state->msg_input == NULL) {
+        furi_string_free(state->name_prefix);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
-static void helper_strings_free(ESubGhzChatState *state)
-{
-	furi_assert(state);
+static void helper_strings_free(ESubGhzChatState* state) {
+    furi_assert(state);
 
-	furi_string_free(state->name_prefix);
-	furi_string_free(state->msg_input);
+    furi_string_free(state->name_prefix);
+    furi_string_free(state->msg_input);
 }
 
-static bool chat_box_alloc(ESubGhzChatState *state)
-{
-	furi_assert(state);
+static bool chat_box_alloc(ESubGhzChatState* state) {
+    furi_assert(state);
 
-	state->chat_box = text_box_alloc();
-	if (state->chat_box == NULL) {
-		return false;
-	}
+    state->chat_box = text_box_alloc();
+    if(state->chat_box == NULL) {
+        return false;
+    }
 
-	state->chat_box_store = furi_string_alloc();
-	if (state->chat_box_store == NULL) {
-		text_box_free(state->chat_box);
-		return false;
-	}
+    state->chat_box_store = furi_string_alloc();
+    if(state->chat_box_store == NULL) {
+        text_box_free(state->chat_box);
+        return false;
+    }
 
-	furi_string_reserve(state->chat_box_store, CHAT_BOX_STORE_SIZE);
-	furi_string_set_char(state->chat_box_store, 0, 0);
-	text_box_set_text(state->chat_box,
-			furi_string_get_cstr(state->chat_box_store));
-	text_box_set_focus(state->chat_box, TextBoxFocusEnd);
+    furi_string_reserve(state->chat_box_store, CHAT_BOX_STORE_SIZE);
+    furi_string_set_char(state->chat_box_store, 0, 0);
+    text_box_set_text(state->chat_box, furi_string_get_cstr(state->chat_box_store));
+    text_box_set_focus(state->chat_box, TextBoxFocusEnd);
 
-	return true;
+    return true;
 }
 
-static void chat_box_free(ESubGhzChatState *state)
-{
-	furi_assert(state);
+static void chat_box_free(ESubGhzChatState* state) {
+    furi_assert(state);
 
-	text_box_free(state->chat_box);
-	furi_string_free(state->chat_box_store);
+    text_box_free(state->chat_box);
+    furi_string_free(state->chat_box_store);
 }
 
-int32_t esubghz_chat(const char *args)
-{
-	/* init the crypto system */
-	crypto_init();
+int32_t esubghz_chat(const char* args) {
+    /* init the crypto system */
+    crypto_init();
+
+    int32_t err = -1;
+
+    FURI_LOG_I(APPLICATION_NAME, "Starting...");
+
+    /* allocate necessary structs and buffers */
+
+    ESubGhzChatState* state = malloc(sizeof(ESubGhzChatState));
+    if(state == NULL) {
+        goto err_alloc;
+    }
+    memset(state, 0, sizeof(*state));
 
-	int32_t err = -1;
-
-	FURI_LOG_I(APPLICATION_NAME, "Starting...");
+    state->scene_manager = scene_manager_alloc(&esubghz_chat_scene_event_handlers, state);
+    if(state->scene_manager == NULL) {
+        goto err_alloc_sm;
+    }
 
-	/* allocate necessary structs and buffers */
-
-	ESubGhzChatState *state = malloc(sizeof(ESubGhzChatState));
-	if (state == NULL) {
-		goto err_alloc;
-	}
-	memset(state, 0, sizeof(*state));
-
-	state->scene_manager = scene_manager_alloc(
-			&esubghz_chat_scene_event_handlers, state);
-	if (state->scene_manager == NULL) {
-		goto err_alloc_sm;
-	}
-
-	state->view_dispatcher = view_dispatcher_alloc();
-	if (state->view_dispatcher == NULL) {
-		goto err_alloc_vd;
-	}
-
-	if (!helper_strings_alloc(state)) {
-		goto err_alloc_hs;
-	}
-
-	state->menu = menu_alloc();
-	if (state->menu == NULL) {
-		goto err_alloc_menu;
-	}
-
-	state->text_input = text_input_alloc();
-	if (state->text_input == NULL) {
-		goto err_alloc_ti;
-	}
-
-	state->hex_key_input = byte_input_alloc();
-	if (state->hex_key_input == NULL) {
-		goto err_alloc_hki;
-	}
-
-	if (!chat_box_alloc(state)) {
-		goto err_alloc_cb;
-	}
-
-	state->key_display = dialog_ex_alloc();
-	if (state->key_display == NULL) {
-		goto err_alloc_kd;
-	}
-
-	state->nfc_popup = popup_alloc();
-	if (state->nfc_popup == NULL) {
-		goto err_alloc_np;
-	}
-
-	state->subghz_worker = subghz_tx_rx_worker_alloc();
-	if (state->subghz_worker == NULL) {
-		goto err_alloc_worker;
-	}
-
-	state->nfc_worker = nfc_worker_alloc();
-	if (state->nfc_worker == NULL) {
-		goto err_alloc_nworker;
-	}
-
-	state->nfc_dev_data = malloc(sizeof(NfcDeviceData));
-	if (state->nfc_dev_data == NULL) {
-		goto err_alloc_ndevdata;
-	}
-	memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
-
-	state->crypto_ctx = crypto_ctx_alloc();
-	if (state->crypto_ctx == NULL) {
-		goto err_alloc_crypto;
-	}
-
-	/* set the default frequency */
-	state->frequency = DEFAULT_FREQ;
-
-	/* in the first few views there is no background support */
-	state->exit_for_real = true;
-
-	/* set the have_read callback of the Sub-GHz worker */
-	subghz_tx_rx_worker_set_callback_have_read(state->subghz_worker,
-			have_read_cb, state);
-
-	/* enter suppress charge mode */
-	furi_hal_power_suppress_charge_enter();
-
-	/* init internal device */
-	subghz_devices_init();
-
-	state->subghz_device = radio_device_loader_set(state->subghz_device,
-			SubGhzRadioDeviceTypeExternalCC1101);
-
-	subghz_devices_reset(state->subghz_device);
-	subghz_devices_idle(state->subghz_device);
-
-	/* set chat name prefix */
-	furi_string_printf(state->name_prefix, "%s",
-			furi_hal_version_get_name_ptr());
-
-	/* get notification record, we use this to make the flipper vibrate */
-	/* no error handling here, don't know how */
-	state->notification = furi_record_open(RECORD_NOTIFICATION);
-
-	/* hook into the view port's draw and input callbacks */
-	state->orig_draw_cb = state->view_dispatcher->view_port->draw_callback;
-	state->orig_input_cb = state->view_dispatcher->view_port->input_callback;
-	view_port_draw_callback_set(state->view_dispatcher->view_port,
-			esubghz_hooked_draw_callback, state);
-	view_port_input_callback_set(state->view_dispatcher->view_port,
-			esubghz_hooked_input_callback, state);
-
-	view_dispatcher_enable_queue(state->view_dispatcher);
-
-	/* set callbacks for view dispatcher */
-	view_dispatcher_set_event_callback_context(state->view_dispatcher, state);
-	view_dispatcher_set_custom_event_callback(
-			state->view_dispatcher,
-			esubghz_chat_custom_event_callback);
-	view_dispatcher_set_navigation_event_callback(
-			state->view_dispatcher,
-			esubghz_chat_navigation_event_callback);
-	view_dispatcher_set_tick_event_callback(
-			state->view_dispatcher,
-			esubghz_chat_tick_event_callback,
-			TICK_INTERVAL);
-
-	/* add our two views to the view dispatcher */
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_Menu,
-			menu_get_view(state->menu));
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_Input,
-			text_input_get_view(state->text_input));
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_HexKeyInput,
-			byte_input_get_view(state->hex_key_input));
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_ChatBox,
-			text_box_get_view(state->chat_box));
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_KeyDisplay,
-			dialog_ex_get_view(state->key_display));
-	view_dispatcher_add_view(state->view_dispatcher, ESubGhzChatView_NfcPopup,
-			popup_get_view(state->nfc_popup));
-
-	/* get the GUI record and attach the view dispatcher to the GUI */
-	/* no error handling here, don't know how */
-	Gui *gui = furi_record_open(RECORD_GUI);
-	view_dispatcher_attach_to_gui(state->view_dispatcher, gui,
-			ViewDispatcherTypeFullscreen);
-
-	/* switch to the key menu scene */
-	scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_KeyMenu);
-
-	/* run the view dispatcher, this call only returns when we close the
+    state->view_dispatcher = view_dispatcher_alloc();
+    if(state->view_dispatcher == NULL) {
+        goto err_alloc_vd;
+    }
+
+    if(!helper_strings_alloc(state)) {
+        goto err_alloc_hs;
+    }
+
+    state->menu = menu_alloc();
+    if(state->menu == NULL) {
+        goto err_alloc_menu;
+    }
+
+    state->text_input = text_input_alloc();
+    if(state->text_input == NULL) {
+        goto err_alloc_ti;
+    }
+
+    state->hex_key_input = byte_input_alloc();
+    if(state->hex_key_input == NULL) {
+        goto err_alloc_hki;
+    }
+
+    if(!chat_box_alloc(state)) {
+        goto err_alloc_cb;
+    }
+
+    state->key_display = dialog_ex_alloc();
+    if(state->key_display == NULL) {
+        goto err_alloc_kd;
+    }
+
+    state->nfc_popup = popup_alloc();
+    if(state->nfc_popup == NULL) {
+        goto err_alloc_np;
+    }
+
+    state->subghz_worker = subghz_tx_rx_worker_alloc();
+    if(state->subghz_worker == NULL) {
+        goto err_alloc_worker;
+    }
+
+    state->nfc_worker = nfc_worker_alloc();
+    if(state->nfc_worker == NULL) {
+        goto err_alloc_nworker;
+    }
+
+    state->nfc_dev_data = malloc(sizeof(NfcDeviceData));
+    if(state->nfc_dev_data == NULL) {
+        goto err_alloc_ndevdata;
+    }
+    memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
+
+    state->crypto_ctx = crypto_ctx_alloc();
+    if(state->crypto_ctx == NULL) {
+        goto err_alloc_crypto;
+    }
+
+    /* set the default frequency */
+    state->frequency = DEFAULT_FREQ;
+
+    /* in the first few views there is no background support */
+    state->exit_for_real = true;
+
+    /* set the have_read callback of the Sub-GHz worker */
+    subghz_tx_rx_worker_set_callback_have_read(state->subghz_worker, have_read_cb, state);
+
+    /* enter suppress charge mode */
+    furi_hal_power_suppress_charge_enter();
+
+    /* init internal device */
+    subghz_devices_init();
+
+    state->subghz_device =
+        radio_device_loader_set(state->subghz_device, SubGhzRadioDeviceTypeExternalCC1101);
+
+    subghz_devices_reset(state->subghz_device);
+    subghz_devices_idle(state->subghz_device);
+
+    /* set chat name prefix */
+    furi_string_printf(state->name_prefix, "%s", furi_hal_version_get_name_ptr());
+
+    /* get notification record, we use this to make the flipper vibrate */
+    /* no error handling here, don't know how */
+    state->notification = furi_record_open(RECORD_NOTIFICATION);
+
+    /* hook into the view port's draw and input callbacks */
+    state->orig_draw_cb = state->view_dispatcher->view_port->draw_callback;
+    state->orig_input_cb = state->view_dispatcher->view_port->input_callback;
+    view_port_draw_callback_set(
+        state->view_dispatcher->view_port, esubghz_hooked_draw_callback, state);
+    view_port_input_callback_set(
+        state->view_dispatcher->view_port, esubghz_hooked_input_callback, state);
+
+    view_dispatcher_enable_queue(state->view_dispatcher);
+
+    /* set callbacks for view dispatcher */
+    view_dispatcher_set_event_callback_context(state->view_dispatcher, state);
+    view_dispatcher_set_custom_event_callback(
+        state->view_dispatcher, esubghz_chat_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        state->view_dispatcher, esubghz_chat_navigation_event_callback);
+    view_dispatcher_set_tick_event_callback(
+        state->view_dispatcher, esubghz_chat_tick_event_callback, TICK_INTERVAL);
+
+    /* add our two views to the view dispatcher */
+    view_dispatcher_add_view(
+        state->view_dispatcher, ESubGhzChatView_Menu, menu_get_view(state->menu));
+    view_dispatcher_add_view(
+        state->view_dispatcher, ESubGhzChatView_Input, text_input_get_view(state->text_input));
+    view_dispatcher_add_view(
+        state->view_dispatcher,
+        ESubGhzChatView_HexKeyInput,
+        byte_input_get_view(state->hex_key_input));
+    view_dispatcher_add_view(
+        state->view_dispatcher, ESubGhzChatView_ChatBox, text_box_get_view(state->chat_box));
+    view_dispatcher_add_view(
+        state->view_dispatcher,
+        ESubGhzChatView_KeyDisplay,
+        dialog_ex_get_view(state->key_display));
+    view_dispatcher_add_view(
+        state->view_dispatcher, ESubGhzChatView_NfcPopup, popup_get_view(state->nfc_popup));
+
+    /* get the GUI record and attach the view dispatcher to the GUI */
+    /* no error handling here, don't know how */
+    Gui* gui = furi_record_open(RECORD_GUI);
+    view_dispatcher_attach_to_gui(state->view_dispatcher, gui, ViewDispatcherTypeFullscreen);
+
+    /* switch to the key menu scene */
+    scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_KeyMenu);
+
+    /* run the view dispatcher, this call only returns when we close the
 	 * application */
-	if (!esubghz_run_with_bgloader(args)) {
-		view_dispatcher_run(state->view_dispatcher);
-	} else {
-		const char *bg_app_path = esubghz_get_bgloader_app_path(args);
-		esubghz_bgloader_loop(state, bg_app_path);
-	}
-
-	/* if it is running, stop the Sub-GHz worker */
-	if (subghz_tx_rx_worker_is_running(state->subghz_worker)) {
-		exit_chat(state);
-		subghz_tx_rx_worker_stop(state->subghz_worker);
-	}
-
-	/* if it is running, stop the NFC worker */
-	nfc_worker_stop(state->nfc_worker);
-
-	err = 0;
-
-	/* close GUI record */
-	furi_record_close(RECORD_GUI);
-
-	/* remove our two views from the view dispatcher */
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_Menu);
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_Input);
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_HexKeyInput);
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_ChatBox);
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_KeyDisplay);
-	view_dispatcher_remove_view(state->view_dispatcher,
-			ESubGhzChatView_NfcPopup);
-
-	/* close notification record */
-	furi_record_close(RECORD_NOTIFICATION);
-
-	/* clear the key and potential password */
-	crypto_explicit_bzero(state->text_input_store,
-			sizeof(state->text_input_store));
-	crypto_explicit_bzero(state->hex_key_input_store,
-			sizeof(state->hex_key_input_store));
-	crypto_explicit_bzero(state->key_hex_str, sizeof(state->key_hex_str));
-	crypto_ctx_clear(state->crypto_ctx);
-
-	/* clear nfc data */
-	if (state->nfc_dev_data->parsed_data != NULL) {
-		furi_string_free(state->nfc_dev_data->parsed_data);
-	}
-	crypto_explicit_bzero(state->nfc_dev_data, sizeof(NfcDeviceData));
-
-	/* deinit devices */
-	radio_device_loader_end(state->subghz_device);
-
-	subghz_devices_deinit();
-
-	/* exit suppress charge mode */
-	furi_hal_power_suppress_charge_exit();
-
-	/* free everything we allocated */
-
-	crypto_ctx_free(state->crypto_ctx);
+    if(!esubghz_run_with_bgloader(args)) {
+        view_dispatcher_run(state->view_dispatcher);
+    } else {
+        const char* bg_app_path = esubghz_get_bgloader_app_path(args);
+        esubghz_bgloader_loop(state, bg_app_path);
+    }
+
+    /* if it is running, stop the Sub-GHz worker */
+    if(subghz_tx_rx_worker_is_running(state->subghz_worker)) {
+        exit_chat(state);
+        subghz_tx_rx_worker_stop(state->subghz_worker);
+    }
+
+    /* if it is running, stop the NFC worker */
+    nfc_worker_stop(state->nfc_worker);
+
+    err = 0;
+
+    /* close GUI record */
+    furi_record_close(RECORD_GUI);
+
+    /* remove our two views from the view dispatcher */
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_Menu);
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_Input);
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_HexKeyInput);
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_ChatBox);
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_KeyDisplay);
+    view_dispatcher_remove_view(state->view_dispatcher, ESubGhzChatView_NfcPopup);
+
+    /* close notification record */
+    furi_record_close(RECORD_NOTIFICATION);
+
+    /* clear the key and potential password */
+    crypto_explicit_bzero(state->text_input_store, sizeof(state->text_input_store));
+    crypto_explicit_bzero(state->hex_key_input_store, sizeof(state->hex_key_input_store));
+    crypto_explicit_bzero(state->key_hex_str, sizeof(state->key_hex_str));
+    crypto_ctx_clear(state->crypto_ctx);
+
+    /* clear nfc data */
+    if(state->nfc_dev_data->parsed_data != NULL) {
+        furi_string_free(state->nfc_dev_data->parsed_data);
+    }
+    crypto_explicit_bzero(state->nfc_dev_data, sizeof(NfcDeviceData));
+
+    /* deinit devices */
+    radio_device_loader_end(state->subghz_device);
+
+    subghz_devices_deinit();
+
+    /* exit suppress charge mode */
+    furi_hal_power_suppress_charge_exit();
+
+    /* free everything we allocated */
+
+    crypto_ctx_free(state->crypto_ctx);
 
 err_alloc_crypto:
-	free(state->nfc_dev_data);
+    free(state->nfc_dev_data);
 
 err_alloc_ndevdata:
-	nfc_worker_free(state->nfc_worker);
+    nfc_worker_free(state->nfc_worker);
 
 err_alloc_nworker:
-	subghz_tx_rx_worker_free(state->subghz_worker);
+    subghz_tx_rx_worker_free(state->subghz_worker);
 
 err_alloc_worker:
-	popup_free(state->nfc_popup);
+    popup_free(state->nfc_popup);
 
 err_alloc_np:
-	dialog_ex_free(state->key_display);
+    dialog_ex_free(state->key_display);
 
 err_alloc_kd:
-	chat_box_free(state);
+    chat_box_free(state);
 
 err_alloc_cb:
-	byte_input_free(state->hex_key_input);
+    byte_input_free(state->hex_key_input);
 
 err_alloc_hki:
-	text_input_free(state->text_input);
+    text_input_free(state->text_input);
 
 err_alloc_ti:
-	menu_free(state->menu);
+    menu_free(state->menu);
 
 err_alloc_menu:
-	helper_strings_free(state);
+    helper_strings_free(state);
 
 err_alloc_hs:
-	view_dispatcher_free(state->view_dispatcher);
+    view_dispatcher_free(state->view_dispatcher);
 
 err_alloc_vd:
-	scene_manager_free(state->scene_manager);
+    scene_manager_free(state->scene_manager);
 
 err_alloc_sm:
-	free(state);
+    free(state);
 
 err_alloc:
-	if (err != 0) {
-		FURI_LOG_E(APPLICATION_NAME, "Failed to launch (alloc error)!");
-	} else {
-		FURI_LOG_I(APPLICATION_NAME, "Clean exit.");
-	}
+    if(err != 0) {
+        FURI_LOG_E(APPLICATION_NAME, "Failed to launch (alloc error)!");
+    } else {
+        FURI_LOG_I(APPLICATION_NAME, "Clean exit.");
+    }
 
-	return err;
+    return err;
 }

+ 81 - 81
esubghz_chat/esubghz_chat_i.h

@@ -37,92 +37,92 @@
 #define KEY_HEX_STR_SIZE ((KEY_BITS / 8) * 3)
 
 typedef struct {
-	SceneManager *scene_manager;
-	ViewDispatcher *view_dispatcher;
-	NotificationApp *notification;
-
-	// UI elements
-	Menu *menu;
-	TextBox *chat_box;
-	FuriString *chat_box_store;
-	TextInput *text_input;
-	char text_input_store[TEXT_INPUT_STORE_SIZE + 1];
-	ByteInput *hex_key_input;
-	uint8_t hex_key_input_store[KEY_BITS / 8];
-	DialogEx *key_display;
-	char key_hex_str[KEY_HEX_STR_SIZE + 1];
-	Popup *nfc_popup;
-
-	// for Sub-GHz
-	uint32_t frequency;
-	SubGhzTxRxWorker *subghz_worker;
-	const SubGhzDevice *subghz_device;
-
-	// for NFC
-	NfcWorker *nfc_worker;
-	NfcDeviceData *nfc_dev_data;
-
-	// message assembly before TX
-	FuriString *name_prefix;
-	FuriString *msg_input;
-
-	// message preview
-	char msg_preview[MSG_PREVIEW_SIZE + 1];
-
-	// encryption
-	bool encrypted;
-	ESubGhzChatCryptoCtx *crypto_ctx;
-
-	// RX and TX buffers
-	uint8_t rx_buffer[RX_TX_BUFFER_SIZE];
-	uint8_t tx_buffer[RX_TX_BUFFER_SIZE];
-	char rx_str_buffer[RX_TX_BUFFER_SIZE + 1];
-	volatile uint32_t last_time_rx_data;
-
-	// for locking
-	ViewPortDrawCallback orig_draw_cb;
-	ViewPortInputCallback orig_input_cb;
-	bool kbd_locked;
-	uint32_t kbd_lock_msg_ticks;
-	uint8_t kbd_lock_count;
-
-	// for ongoing inputs
-	bool kbd_ok_input_ongoing;
-	bool kbd_left_input_ongoing;
-	bool kbd_right_input_ongoing;
-
-	// for background support
-	bool exit_for_real;
+    SceneManager* scene_manager;
+    ViewDispatcher* view_dispatcher;
+    NotificationApp* notification;
+
+    // UI elements
+    Menu* menu;
+    TextBox* chat_box;
+    FuriString* chat_box_store;
+    TextInput* text_input;
+    char text_input_store[TEXT_INPUT_STORE_SIZE + 1];
+    ByteInput* hex_key_input;
+    uint8_t hex_key_input_store[KEY_BITS / 8];
+    DialogEx* key_display;
+    char key_hex_str[KEY_HEX_STR_SIZE + 1];
+    Popup* nfc_popup;
+
+    // for Sub-GHz
+    uint32_t frequency;
+    SubGhzTxRxWorker* subghz_worker;
+    const SubGhzDevice* subghz_device;
+
+    // for NFC
+    NfcWorker* nfc_worker;
+    NfcDeviceData* nfc_dev_data;
+
+    // message assembly before TX
+    FuriString* name_prefix;
+    FuriString* msg_input;
+
+    // message preview
+    char msg_preview[MSG_PREVIEW_SIZE + 1];
+
+    // encryption
+    bool encrypted;
+    ESubGhzChatCryptoCtx* crypto_ctx;
+
+    // RX and TX buffers
+    uint8_t rx_buffer[RX_TX_BUFFER_SIZE];
+    uint8_t tx_buffer[RX_TX_BUFFER_SIZE];
+    char rx_str_buffer[RX_TX_BUFFER_SIZE + 1];
+    volatile uint32_t last_time_rx_data;
+
+    // for locking
+    ViewPortDrawCallback orig_draw_cb;
+    ViewPortInputCallback orig_input_cb;
+    bool kbd_locked;
+    uint32_t kbd_lock_msg_ticks;
+    uint8_t kbd_lock_count;
+
+    // for ongoing inputs
+    bool kbd_ok_input_ongoing;
+    bool kbd_left_input_ongoing;
+    bool kbd_right_input_ongoing;
+
+    // for background support
+    bool exit_for_real;
 } ESubGhzChatState;
 
 typedef enum {
-	ESubGhzChatEvent_FreqEntered,
-	ESubGhzChatEvent_KeyMenuNoEncryption,
-	ESubGhzChatEvent_KeyMenuPassword,
-	ESubGhzChatEvent_KeyMenuHexKey,
-	ESubGhzChatEvent_KeyMenuGenKey,
-	ESubGhzChatEvent_KeyMenuReadKeyFromNfc,
-	ESubGhzChatEvent_KeyReadPopupFailed,
-	ESubGhzChatEvent_KeyReadPopupSucceeded,
-	ESubGhzChatEvent_PassEntered,
-	ESubGhzChatEvent_HexKeyEntered,
-	ESubGhzChatEvent_MsgEntered,
-	ESubGhzChatEvent_GotoMsgInput,
-	ESubGhzChatEvent_GotoKeyDisplay,
-	ESubGhzChatEvent_KeyDisplayBack,
-	ESubGhzChatEvent_KeyDisplayShare,
+    ESubGhzChatEvent_FreqEntered,
+    ESubGhzChatEvent_KeyMenuNoEncryption,
+    ESubGhzChatEvent_KeyMenuPassword,
+    ESubGhzChatEvent_KeyMenuHexKey,
+    ESubGhzChatEvent_KeyMenuGenKey,
+    ESubGhzChatEvent_KeyMenuReadKeyFromNfc,
+    ESubGhzChatEvent_KeyReadPopupFailed,
+    ESubGhzChatEvent_KeyReadPopupSucceeded,
+    ESubGhzChatEvent_PassEntered,
+    ESubGhzChatEvent_HexKeyEntered,
+    ESubGhzChatEvent_MsgEntered,
+    ESubGhzChatEvent_GotoMsgInput,
+    ESubGhzChatEvent_GotoKeyDisplay,
+    ESubGhzChatEvent_KeyDisplayBack,
+    ESubGhzChatEvent_KeyDisplayShare,
 } ESubGhzChatEvent;
 
 typedef enum {
-	ESubGhzChatView_Menu,
-	ESubGhzChatView_Input,
-	ESubGhzChatView_HexKeyInput,
-	ESubGhzChatView_ChatBox,
-	ESubGhzChatView_KeyDisplay,
-	ESubGhzChatView_NfcPopup,
+    ESubGhzChatView_Menu,
+    ESubGhzChatView_Input,
+    ESubGhzChatView_HexKeyInput,
+    ESubGhzChatView_ChatBox,
+    ESubGhzChatView_KeyDisplay,
+    ESubGhzChatView_NfcPopup,
 } ESubGhzChatView;
 
-void set_chat_input_header(ESubGhzChatState *state);
-void append_msg(ESubGhzChatState *state, const char *msg);
-void tx_msg_input(ESubGhzChatState *state);
-void enter_chat(ESubGhzChatState *state);
+void set_chat_input_header(ESubGhzChatState* state);
+void append_msg(ESubGhzChatState* state, const char* msg);
+void tx_msg_input(ESubGhzChatState* state);
+void enter_chat(ESubGhzChatState* state);

+ 9 - 9
esubghz_chat/helpers/nfc_helpers.h

@@ -8,17 +8,17 @@ extern "C" {
 #define NFC_CONFIG_PAGES 4
 
 struct FreqNfcEntry {
-	uint32_t frequency;
-	uint32_t unused1;
-	uint32_t unused2;
-	uint32_t unused3;
-} __attribute__ ((packed));
+    uint32_t frequency;
+    uint32_t unused1;
+    uint32_t unused2;
+    uint32_t unused3;
+} __attribute__((packed));
 
 struct ReplayDictNfcEntry {
-	uint64_t run_id;
-	uint32_t counter;
-	uint32_t unused;
-} __attribute__ ((packed));
+    uint64_t run_id;
+    uint32_t counter;
+    uint32_t unused;
+} __attribute__((packed));
 
 #ifdef __cplusplus
 }

+ 46 - 52
esubghz_chat/scenes/esubghz_chat_chat_box.c

@@ -1,67 +1,61 @@
 #include "../esubghz_chat_i.h"
 
 /* Prepares the text box scene. */
-void scene_on_enter_chat_box(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_chat_box");
+void scene_on_enter_chat_box(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_chat_box");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	text_box_reset(state->chat_box);
-	text_box_set_text(state->chat_box,
-			furi_string_get_cstr(state->chat_box_store));
-	text_box_set_focus(state->chat_box, TextBoxFocusEnd);
+    text_box_reset(state->chat_box);
+    text_box_set_text(state->chat_box, furi_string_get_cstr(state->chat_box_store));
+    text_box_set_focus(state->chat_box, TextBoxFocusEnd);
 
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_ChatBox);
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_ChatBox);
 }
 
 /* Handles scene manager events for the text box scene. */
-bool scene_on_event_chat_box(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_chat_box");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to message input scene */
-		case ESubGhzChatEvent_GotoMsgInput:
-			if (!scene_manager_previous_scene(
-						state->scene_manager)) {
-				/* error condition, exit for real */
-				state->exit_for_real = true;
-				view_dispatcher_stop(state->view_dispatcher);
-			}
-			consumed = true;
-			break;
-		case ESubGhzChatEvent_GotoKeyDisplay:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_KeyDisplay);
-			consumed = true;
-			break;
-		}
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_chat_box(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_chat_box");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to message input scene */
+        case ESubGhzChatEvent_GotoMsgInput:
+            if(!scene_manager_previous_scene(state->scene_manager)) {
+                /* error condition, exit for real */
+                state->exit_for_real = true;
+                view_dispatcher_stop(state->view_dispatcher);
+            }
+            consumed = true;
+            break;
+        case ESubGhzChatEvent_GotoKeyDisplay:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_KeyDisplay);
+            consumed = true;
+            break;
+        }
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the text box scene. */
-void scene_on_exit_chat_box(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_chat_box");
+void scene_on_exit_chat_box(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_chat_box");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	text_box_reset(state->chat_box);
+    text_box_reset(state->chat_box);
 }

+ 76 - 87
esubghz_chat/scenes/esubghz_chat_chat_input.c

@@ -6,113 +6,102 @@
  * then copied into the TX buffer. The contents of the TX buffer are then
  * transmitted. The sent message is appended to the text box and a MsgEntered
  * event is sent to the scene manager to switch to the text box view. */
-static bool chat_input_validator(const char *text, FuriString *error,
-		void *context)
-{
-	UNUSED(error);
+static bool chat_input_validator(const char* text, FuriString* error, void* context) {
+    UNUSED(error);
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	/* no message, just switch to the text box view */
-	if (strlen(text) == 0) {
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_MsgEntered);
-		return true;
-	}
+    /* no message, just switch to the text box view */
+    if(strlen(text) == 0) {
+        view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_MsgEntered);
+        return true;
+    }
 
-	/* concatenate the name prefix and the actual message */
-	furi_string_set(state->msg_input, state->name_prefix);
-	furi_string_cat_str(state->msg_input, ": ");
-	furi_string_cat_str(state->msg_input, text);
+    /* concatenate the name prefix and the actual message */
+    furi_string_set(state->msg_input, state->name_prefix);
+    furi_string_cat_str(state->msg_input, ": ");
+    furi_string_cat_str(state->msg_input, text);
 
-	/* append the message to the chat box and prepare message preview */
-	append_msg(state, furi_string_get_cstr(state->msg_input));
+    /* append the message to the chat box and prepare message preview */
+    append_msg(state, furi_string_get_cstr(state->msg_input));
 
-	/* encrypt and transmit message */
-	tx_msg_input(state);
+    /* encrypt and transmit message */
+    tx_msg_input(state);
 
-	/* clear message input buffer */
-	furi_string_set_char(state->msg_input, 0, 0);
+    /* clear message input buffer */
+    furi_string_set_char(state->msg_input, 0, 0);
 
-	/* switch to text box view */
-	view_dispatcher_send_custom_event(state->view_dispatcher,
-			ESubGhzChatEvent_MsgEntered);
+    /* switch to text box view */
+    view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_MsgEntered);
 
-	return true;
+    return true;
 }
 
 /* Prepares the message input scene. */
-void scene_on_enter_chat_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_chat_input");
+void scene_on_enter_chat_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_chat_input");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	state->text_input_store[0] = 0;
-	text_input_reset(state->text_input);
-	/* use validator for scene change to get around minimum length
+    state->text_input_store[0] = 0;
+    text_input_reset(state->text_input);
+    /* use validator for scene change to get around minimum length
 	 * requirement */
-	text_input_set_result_callback(
-			state->text_input,
-			NULL,
-			NULL,
-			state->text_input_store,
-			sizeof(state->text_input_store),
-			true);
-	text_input_set_validator(
-			state->text_input,
-			chat_input_validator,
-			state);
-	set_chat_input_header(state);
-
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
+    text_input_set_result_callback(
+        state->text_input,
+        NULL,
+        NULL,
+        state->text_input_store,
+        sizeof(state->text_input_store),
+        true);
+    text_input_set_validator(state->text_input, chat_input_validator, state);
+    set_chat_input_header(state);
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
 }
 
 /* Handles scene manager events for the message input scene. */
-bool scene_on_event_chat_input(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_chat_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to text box scene */
-		case ESubGhzChatEvent_MsgEntered:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_ChatBox);
-			consumed = true;
-			break;
-		}
-		break;
-
-	case SceneManagerEventTypeBack:
-		/* stop the application if the user presses back here */
-		view_dispatcher_stop(state->view_dispatcher);
-		consumed = true;
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_chat_input(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_chat_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to text box scene */
+        case ESubGhzChatEvent_MsgEntered:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_ChatBox);
+            consumed = true;
+            break;
+        }
+        break;
+
+    case SceneManagerEventTypeBack:
+        /* stop the application if the user presses back here */
+        view_dispatcher_stop(state->view_dispatcher);
+        consumed = true;
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the password input scene. */
-void scene_on_exit_chat_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_chat_input");
+void scene_on_exit_chat_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_chat_input");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	text_input_reset(state->text_input);
+    text_input_reset(state->text_input);
 }

+ 85 - 102
esubghz_chat/scenes/esubghz_chat_freq_input.c

@@ -1,128 +1,111 @@
 #include "../esubghz_chat_i.h"
 
 /* Sends FreqEntered event to scene manager and enters the chat. */
-static void freq_input_cb(void *context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static void freq_input_cb(void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	enter_chat(state);
+    enter_chat(state);
 
-	/* starting from here running in background is supported */
-	state->exit_for_real = false;
+    /* starting from here running in background is supported */
+    state->exit_for_real = false;
 
-	view_dispatcher_send_custom_event(state->view_dispatcher,
-			ESubGhzChatEvent_FreqEntered);
+    view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_FreqEntered);
 }
 
 /* Validates the entered frequency. */
-static bool freq_input_validator(const char *text, FuriString *error,
-		void *context)
-{
-	furi_assert(text);
-	furi_assert(error);
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-        int ret = sscanf(text, "%lu", &(state->frequency));
-	if (ret != 1) {
-		furi_string_printf(error, "Please enter\nfrequency\nin Hz!");
-		return false;
-	}
-
-	if (!subghz_devices_is_frequency_valid(state->subghz_device,
-				state->frequency)) {
-		furi_string_printf(error, "Frequency\n%lu\n is invalid!",
-				state->frequency);
-		return false;
-	}
+static bool freq_input_validator(const char* text, FuriString* error, void* context) {
+    furi_assert(text);
+    furi_assert(error);
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    int ret = sscanf(text, "%lu", &(state->frequency));
+    if(ret != 1) {
+        furi_string_printf(error, "Please enter\nfrequency\nin Hz!");
+        return false;
+    }
+
+    if(!subghz_devices_is_frequency_valid(state->subghz_device, state->frequency)) {
+        furi_string_printf(error, "Frequency\n%lu\n is invalid!", state->frequency);
+        return false;
+    }
 
 #ifdef FW_ORIGIN_Official
-	if (!furi_hal_region_is_frequency_allowed(state->frequency)) {
+    if(!furi_hal_region_is_frequency_allowed(state->frequency)) {
 #else /* FW_ORIGIN_Official */
-	if (!furi_hal_subghz_is_tx_allowed(state->frequency)) {
+    if(!furi_hal_subghz_is_tx_allowed(state->frequency)) {
 #endif /* FW_ORIGIN_Official */
-		furi_string_printf(error, "TX forbidden\non frequency\n%lu!",
-				state->frequency);
-		return false;
-	}
+        furi_string_printf(error, "TX forbidden\non frequency\n%lu!", state->frequency);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 /* Prepares the frequency input scene. */
-void scene_on_enter_freq_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_freq_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	snprintf(state->text_input_store, TEXT_INPUT_STORE_SIZE, "%lu",
-			state->frequency);
-	text_input_reset(state->text_input);
-	text_input_set_result_callback(
-			state->text_input,
-			freq_input_cb,
-			state,
-			state->text_input_store,
-			sizeof(state->text_input_store),
-			true);
-	text_input_set_validator(
-			state->text_input,
-			freq_input_validator,
-			state);
-	text_input_set_header_text(
-			state->text_input,
-			"Frequency");
-
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
+void scene_on_enter_freq_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_freq_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    snprintf(state->text_input_store, TEXT_INPUT_STORE_SIZE, "%lu", state->frequency);
+    text_input_reset(state->text_input);
+    text_input_set_result_callback(
+        state->text_input,
+        freq_input_cb,
+        state,
+        state->text_input_store,
+        sizeof(state->text_input_store),
+        true);
+    text_input_set_validator(state->text_input, freq_input_validator, state);
+    text_input_set_header_text(state->text_input, "Frequency");
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
 }
 
 /* Handles scene manager events for the frequency input scene. */
-bool scene_on_event_freq_input(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_freq_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to message input scene */
-		case ESubGhzChatEvent_FreqEntered:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_ChatInput);
-			consumed = true;
-			break;
-		}
-		break;
-
-	case SceneManagerEventTypeBack:
-		/* stop the application if the user presses back here */
-		view_dispatcher_stop(state->view_dispatcher);
-		consumed = true;
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_freq_input(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_freq_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to message input scene */
+        case ESubGhzChatEvent_FreqEntered:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_ChatInput);
+            consumed = true;
+            break;
+        }
+        break;
+
+    case SceneManagerEventTypeBack:
+        /* stop the application if the user presses back here */
+        view_dispatcher_stop(state->view_dispatcher);
+        consumed = true;
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the frequency input scene. */
-void scene_on_exit_freq_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_freq_input");
+void scene_on_exit_freq_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_freq_input");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	text_input_reset(state->text_input);
+    text_input_reset(state->text_input);
 }

+ 59 - 68
esubghz_chat/scenes/esubghz_chat_hex_key_input.c

@@ -2,88 +2,79 @@
 
 /* Sets the entered bytes as the key and sends a HexKeyEntered event to the
  * scene manager. */
-static void hex_key_input_cb(void* context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static void hex_key_input_cb(void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	/* initiate the crypto context */
-	bool ret = crypto_ctx_set_key(state->crypto_ctx,
-			state->hex_key_input_store, state->name_prefix,
-			furi_get_tick());
+    /* initiate the crypto context */
+    bool ret = crypto_ctx_set_key(
+        state->crypto_ctx, state->hex_key_input_store, state->name_prefix, furi_get_tick());
 
-	/* cleanup */
-	crypto_explicit_bzero(state->hex_key_input_store,
-			sizeof(state->hex_key_input_store));
+    /* cleanup */
+    crypto_explicit_bzero(state->hex_key_input_store, sizeof(state->hex_key_input_store));
 
-	if (!ret) {
-		crypto_ctx_clear(state->crypto_ctx);
-		return;
-	}
+    if(!ret) {
+        crypto_ctx_clear(state->crypto_ctx);
+        return;
+    }
 
-	state->encrypted = true;
+    state->encrypted = true;
 
-	view_dispatcher_send_custom_event(state->view_dispatcher,
-			ESubGhzChatEvent_HexKeyEntered);
+    view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_HexKeyEntered);
 }
 
 /* Prepares the hex key input scene. */
-void scene_on_enter_hex_key_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_hex_key_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	byte_input_set_result_callback(state->hex_key_input,
-			hex_key_input_cb,
-			NULL,
-			state,
-			state->hex_key_input_store,
-			sizeof(state->hex_key_input_store));
-
-	view_dispatcher_switch_to_view(state->view_dispatcher,
-			ESubGhzChatView_HexKeyInput);
+void scene_on_enter_hex_key_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_hex_key_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    byte_input_set_result_callback(
+        state->hex_key_input,
+        hex_key_input_cb,
+        NULL,
+        state,
+        state->hex_key_input_store,
+        sizeof(state->hex_key_input_store));
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_HexKeyInput);
 }
 
 /* Handles scene manager events for the hex key input scene. */
-bool scene_on_event_hex_key_input(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_hex_key_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to frequency input scene */
-		case ESubGhzChatEvent_HexKeyEntered:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_FreqInput);
-			consumed = true;
-			break;
-		}
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_hex_key_input(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_hex_key_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to frequency input scene */
+        case ESubGhzChatEvent_HexKeyEntered:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_FreqInput);
+            consumed = true;
+            break;
+        }
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the hex key input scene. */
-void scene_on_exit_hex_key_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_hex_key_input");
+void scene_on_exit_hex_key_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_hex_key_input");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	crypto_explicit_bzero(state->hex_key_input_store,
-			sizeof(state->hex_key_input_store));
+    crypto_explicit_bzero(state->hex_key_input_store, sizeof(state->hex_key_input_store));
 }

+ 133 - 116
esubghz_chat/scenes/esubghz_chat_key_display.c

@@ -1,130 +1,147 @@
 #include "../esubghz_chat_i.h"
 
-void key_display_result_cb(DialogExResult result, void* context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	switch(result) {
-	case DialogExResultLeft:
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyDisplayBack);
-		break;
-
-	case DialogExResultCenter:
-		if (state->encrypted) {
-			view_dispatcher_send_custom_event(state->view_dispatcher,
-					ESubGhzChatEvent_KeyDisplayShare);
-		}
-		break;
-
-	default:
-		break;
-	}
+void key_display_result_cb(DialogExResult result, void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    switch(result) {
+    case DialogExResultLeft:
+        view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_KeyDisplayBack);
+        break;
+
+    case DialogExResultCenter:
+        if(state->encrypted) {
+            view_dispatcher_send_custom_event(
+                state->view_dispatcher, ESubGhzChatEvent_KeyDisplayShare);
+        }
+        break;
+
+    default:
+        break;
+    }
 }
 
 /* Prepares the key display scene. */
-void scene_on_enter_key_display(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_display");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	if (state->encrypted) {
-		uint8_t key[KEY_BITS / 8];
-		crypto_ctx_get_key(state->crypto_ctx, key);
-		snprintf(state->key_hex_str, KEY_HEX_STR_SIZE,
-				"%02hX%02hX%02hX%02hX"
-				"%02hX%02hX%02hX%02hX\n"
-				"%02hX%02hX%02hX%02hX"
-				"%02hX%02hX%02hX%02hX\n"
-				"%02hX%02hX%02hX%02hX"
-				"%02hX%02hX%02hX%02hX\n"
-				"%02hX%02hX%02hX%02hX"
-				"%02hX%02hX%02hX%02hX",
-				key[0], key[1], key[2], key[3],
-				key[4], key[5], key[6], key[7],
-				key[8], key[9], key[10], key[11],
-				key[12], key[13], key[14], key[15],
-				key[16], key[17], key[18], key[19],
-				key[20], key[21], key[22], key[23],
-				key[24], key[25], key[26], key[27],
-				key[28], key[29], key[30], key[31]);
-		crypto_explicit_bzero(key, sizeof(key));
-	} else {
-		strcpy(state->key_hex_str, "No Key");
-	}
-
-	dialog_ex_reset(state->key_display);
-
-	dialog_ex_set_text(state->key_display, state->key_hex_str, 64, 2,
-			AlignCenter, AlignTop);
-
-	dialog_ex_set_icon(state->key_display, 0, 0, NULL);
-
-	dialog_ex_set_left_button_text(state->key_display, "Back");
-
-	if (state->encrypted) {
-		dialog_ex_set_center_button_text(state->key_display, "Share");
-	}
-
-	dialog_ex_set_result_callback(state->key_display,
-			key_display_result_cb);
-	dialog_ex_set_context(state->key_display, state);
-
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_KeyDisplay);
+void scene_on_enter_key_display(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_display");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    if(state->encrypted) {
+        uint8_t key[KEY_BITS / 8];
+        crypto_ctx_get_key(state->crypto_ctx, key);
+        snprintf(
+            state->key_hex_str,
+            KEY_HEX_STR_SIZE,
+            "%02hX%02hX%02hX%02hX"
+            "%02hX%02hX%02hX%02hX\n"
+            "%02hX%02hX%02hX%02hX"
+            "%02hX%02hX%02hX%02hX\n"
+            "%02hX%02hX%02hX%02hX"
+            "%02hX%02hX%02hX%02hX\n"
+            "%02hX%02hX%02hX%02hX"
+            "%02hX%02hX%02hX%02hX",
+            key[0],
+            key[1],
+            key[2],
+            key[3],
+            key[4],
+            key[5],
+            key[6],
+            key[7],
+            key[8],
+            key[9],
+            key[10],
+            key[11],
+            key[12],
+            key[13],
+            key[14],
+            key[15],
+            key[16],
+            key[17],
+            key[18],
+            key[19],
+            key[20],
+            key[21],
+            key[22],
+            key[23],
+            key[24],
+            key[25],
+            key[26],
+            key[27],
+            key[28],
+            key[29],
+            key[30],
+            key[31]);
+        crypto_explicit_bzero(key, sizeof(key));
+    } else {
+        strcpy(state->key_hex_str, "No Key");
+    }
+
+    dialog_ex_reset(state->key_display);
+
+    dialog_ex_set_text(state->key_display, state->key_hex_str, 64, 2, AlignCenter, AlignTop);
+
+    dialog_ex_set_icon(state->key_display, 0, 0, NULL);
+
+    dialog_ex_set_left_button_text(state->key_display, "Back");
+
+    if(state->encrypted) {
+        dialog_ex_set_center_button_text(state->key_display, "Share");
+    }
+
+    dialog_ex_set_result_callback(state->key_display, key_display_result_cb);
+    dialog_ex_set_context(state->key_display, state);
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_KeyDisplay);
 }
 
 /* Handles scene manager events for the key display scene. */
-bool scene_on_event_key_display(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_display");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to message input scene */
-		case ESubGhzChatEvent_KeyDisplayBack:
-			if (!scene_manager_previous_scene(
-						state->scene_manager)) {
-				/* error condition, exit for real */
-				state->exit_for_real = true;
-				view_dispatcher_stop(state->view_dispatcher);
-			}
-			consumed = true;
-			break;
-
-		/* open key sharing popup */
-		case ESubGhzChatEvent_KeyDisplayShare:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_KeySharePopup);
-			consumed = true;
-			break;
-		}
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_key_display(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_display");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to message input scene */
+        case ESubGhzChatEvent_KeyDisplayBack:
+            if(!scene_manager_previous_scene(state->scene_manager)) {
+                /* error condition, exit for real */
+                state->exit_for_real = true;
+                view_dispatcher_stop(state->view_dispatcher);
+            }
+            consumed = true;
+            break;
+
+        /* open key sharing popup */
+        case ESubGhzChatEvent_KeyDisplayShare:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_KeySharePopup);
+            consumed = true;
+            break;
+        }
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the key display scene. */
-void scene_on_exit_key_display(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_display");
+void scene_on_exit_key_display(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_display");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	dialog_ex_reset(state->key_display);
-	crypto_explicit_bzero(state->key_hex_str, sizeof(state->key_hex_str));
+    dialog_ex_reset(state->key_display);
+    crypto_explicit_bzero(state->key_hex_str, sizeof(state->key_hex_str));
 }

+ 140 - 162
esubghz_chat/scenes/esubghz_chat_key_menu.c

@@ -1,196 +1,174 @@
 #include "../esubghz_chat_i.h"
 
 typedef enum {
-	ESubGhzChatKeyMenuItems_NoEncryption,
-	ESubGhzChatKeyMenuItems_Password,
-	ESubGhzChatKeyMenuItems_HexKey,
-	ESubGhzChatKeyMenuItems_GenKey,
-	ESubGhzChatKeyMenuItems_ReadKeyFromNfc,
+    ESubGhzChatKeyMenuItems_NoEncryption,
+    ESubGhzChatKeyMenuItems_Password,
+    ESubGhzChatKeyMenuItems_HexKey,
+    ESubGhzChatKeyMenuItems_GenKey,
+    ESubGhzChatKeyMenuItems_ReadKeyFromNfc,
 } ESubGhzChatKeyMenuItems;
 
-static void key_menu_cb(void* context, uint32_t index)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static void key_menu_cb(void* context, uint32_t index) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	uint8_t key[KEY_BITS / 8];
+    uint8_t key[KEY_BITS / 8];
 
-	switch(index) {
-	case ESubGhzChatKeyMenuItems_NoEncryption:
-		state->encrypted = false;
+    switch(index) {
+    case ESubGhzChatKeyMenuItems_NoEncryption:
+        state->encrypted = false;
 
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyMenuNoEncryption);
-		break;
+        view_dispatcher_send_custom_event(
+            state->view_dispatcher, ESubGhzChatEvent_KeyMenuNoEncryption);
+        break;
 
-	case ESubGhzChatKeyMenuItems_Password:
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyMenuPassword);
-		break;
+    case ESubGhzChatKeyMenuItems_Password:
+        view_dispatcher_send_custom_event(
+            state->view_dispatcher, ESubGhzChatEvent_KeyMenuPassword);
+        break;
 
-	case ESubGhzChatKeyMenuItems_HexKey:
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyMenuHexKey);
-		break;
+    case ESubGhzChatKeyMenuItems_HexKey:
+        view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_KeyMenuHexKey);
+        break;
 
-	case ESubGhzChatKeyMenuItems_GenKey:
-		/* generate a random key */
-		furi_hal_random_fill_buf(key, KEY_BITS / 8);
+    case ESubGhzChatKeyMenuItems_GenKey:
+        /* generate a random key */
+        furi_hal_random_fill_buf(key, KEY_BITS / 8);
 
-		/* initiate the crypto context */
-		bool ret = crypto_ctx_set_key(state->crypto_ctx, key,
-				state->name_prefix, furi_get_tick());
+        /* initiate the crypto context */
+        bool ret = crypto_ctx_set_key(state->crypto_ctx, key, state->name_prefix, furi_get_tick());
 
-		/* cleanup */
-		crypto_explicit_bzero(key, sizeof(key));
+        /* cleanup */
+        crypto_explicit_bzero(key, sizeof(key));
 
-		if (!ret) {
-			crypto_ctx_clear(state->crypto_ctx);
-			return;
-		}
+        if(!ret) {
+            crypto_ctx_clear(state->crypto_ctx);
+            return;
+        }
 
-		/* set encrypted flag and enter the chat */
-		state->encrypted = true;
+        /* set encrypted flag and enter the chat */
+        state->encrypted = true;
 
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyMenuGenKey);
-		break;
+        view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_KeyMenuGenKey);
+        break;
 
-	case ESubGhzChatKeyMenuItems_ReadKeyFromNfc:
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyMenuReadKeyFromNfc);
-		break;
+    case ESubGhzChatKeyMenuItems_ReadKeyFromNfc:
+        view_dispatcher_send_custom_event(
+            state->view_dispatcher, ESubGhzChatEvent_KeyMenuReadKeyFromNfc);
+        break;
 
-	default:
-		break;
-	}
+    default:
+        break;
+    }
 }
 
 /* Prepares the key menu scene. */
-void scene_on_enter_key_menu(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_menu");
+void scene_on_enter_key_menu(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_menu");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	menu_reset(state->menu);
+    menu_reset(state->menu);
 
-	/* clear the crypto CTX in case we got back from password or hex key
+    /* clear the crypto CTX in case we got back from password or hex key
 	 * input */
-	crypto_ctx_clear(state->crypto_ctx);
-
-	menu_add_item(
-		state->menu,
-		"No encryption",
-		&I_chat_14px,
-		ESubGhzChatKeyMenuItems_NoEncryption,
-		key_menu_cb,
-		state
-	);
-	menu_add_item(
-		state->menu,
-		"Password",
-		&I_keyboard_14px,
-		ESubGhzChatKeyMenuItems_Password,
-		key_menu_cb,
-		state
-	);
-	menu_add_item(
-		state->menu,
-		"Hex Key",
-		&I_hex_14px,
-		ESubGhzChatKeyMenuItems_HexKey,
-		key_menu_cb,
-		state
-	);
-	menu_add_item(
-		state->menu,
-		"Generate Key",
-		&I_u2f_14px,
-		ESubGhzChatKeyMenuItems_GenKey,
-		key_menu_cb,
-		state
-	);
-	menu_add_item(
-		state->menu,
-		"Read Key from NFC",
-		&I_Nfc_14px,
-		ESubGhzChatKeyMenuItems_ReadKeyFromNfc,
-		key_menu_cb,
-		state
-	);
-
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Menu);
+    crypto_ctx_clear(state->crypto_ctx);
+
+    menu_add_item(
+        state->menu,
+        "No encryption",
+        &I_chat_14px,
+        ESubGhzChatKeyMenuItems_NoEncryption,
+        key_menu_cb,
+        state);
+    menu_add_item(
+        state->menu,
+        "Password",
+        &I_keyboard_14px,
+        ESubGhzChatKeyMenuItems_Password,
+        key_menu_cb,
+        state);
+    menu_add_item(
+        state->menu, "Hex Key", &I_hex_14px, ESubGhzChatKeyMenuItems_HexKey, key_menu_cb, state);
+    menu_add_item(
+        state->menu,
+        "Generate Key",
+        &I_u2f_14px,
+        ESubGhzChatKeyMenuItems_GenKey,
+        key_menu_cb,
+        state);
+    menu_add_item(
+        state->menu,
+        "Read Key from NFC",
+        &I_Nfc_14px,
+        ESubGhzChatKeyMenuItems_ReadKeyFromNfc,
+        key_menu_cb,
+        state);
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Menu);
 }
 
 /* Handles scene manager events for the key menu scene. */
-bool scene_on_event_key_menu(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_menu");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to frequency input scene */
-		case ESubGhzChatEvent_KeyMenuNoEncryption:
-		case ESubGhzChatEvent_KeyMenuGenKey:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_FreqInput);
-			consumed = true;
-			break;
-
-		/* switch to password input scene */
-		case ESubGhzChatEvent_KeyMenuPassword:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_PassInput);
-			consumed = true;
-			break;
-
-		/* switch to hex key input scene */
-		case ESubGhzChatEvent_KeyMenuHexKey:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_HexKeyInput);
-			consumed = true;
-			break;
-
-		/* switch to hex key read scene */
-		case ESubGhzChatEvent_KeyMenuReadKeyFromNfc:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_KeyReadPopup);
-			consumed = true;
-			break;
-		}
-
-		break;
-
-	case SceneManagerEventTypeBack:
-		/* stop the application if the user presses back here */
-		view_dispatcher_stop(state->view_dispatcher);
-		consumed = true;
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_key_menu(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_menu");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to frequency input scene */
+        case ESubGhzChatEvent_KeyMenuNoEncryption:
+        case ESubGhzChatEvent_KeyMenuGenKey:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_FreqInput);
+            consumed = true;
+            break;
+
+        /* switch to password input scene */
+        case ESubGhzChatEvent_KeyMenuPassword:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_PassInput);
+            consumed = true;
+            break;
+
+        /* switch to hex key input scene */
+        case ESubGhzChatEvent_KeyMenuHexKey:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_HexKeyInput);
+            consumed = true;
+            break;
+
+        /* switch to hex key read scene */
+        case ESubGhzChatEvent_KeyMenuReadKeyFromNfc:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_KeyReadPopup);
+            consumed = true;
+            break;
+        }
+
+        break;
+
+    case SceneManagerEventTypeBack:
+        /* stop the application if the user presses back here */
+        view_dispatcher_stop(state->view_dispatcher);
+        consumed = true;
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the key menu scene. */
-void scene_on_exit_key_menu(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_menu");
+void scene_on_exit_key_menu(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_menu");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	menu_reset(state->menu);
+    menu_reset(state->menu);
 }
-

+ 231 - 261
esubghz_chat/scenes/esubghz_chat_key_read_popup.c

@@ -2,302 +2,272 @@
 #include "../helpers/nfc_helpers.h"
 
 typedef enum {
-	KeyReadPopupState_Idle,
-	KeyReadPopupState_Detecting,
-	KeyReadPopupState_Reading,
-	KeyReadPopupState_Fail,
-	KeyReadPopupState_Success,
+    KeyReadPopupState_Idle,
+    KeyReadPopupState_Detecting,
+    KeyReadPopupState_Reading,
+    KeyReadPopupState_Fail,
+    KeyReadPopupState_Success,
 } KeyReadPopupState;
 
-static bool read_worker_cb(NfcWorkerEvent event, void* context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static bool read_worker_cb(NfcWorkerEvent event, void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	view_dispatcher_send_custom_event(state->view_dispatcher, event);
+    view_dispatcher_send_custom_event(state->view_dispatcher, event);
 
-	return true;
+    return true;
 }
 
-static void key_read_popup_timeout_cb(void* context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	uint32_t cur_state = scene_manager_get_scene_state(
-			state->scene_manager, ESubGhzChatScene_KeyReadPopup);
-
-	/* done displaying our failure */
-	if (cur_state == KeyReadPopupState_Fail) {
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyReadPopupFailed);
-	/* done displaying our success */
-	} else if (cur_state == KeyReadPopupState_Success) {
-		view_dispatcher_send_custom_event(state->view_dispatcher,
-				ESubGhzChatEvent_KeyReadPopupSucceeded);
-	}
+static void key_read_popup_timeout_cb(void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    uint32_t cur_state =
+        scene_manager_get_scene_state(state->scene_manager, ESubGhzChatScene_KeyReadPopup);
+
+    /* done displaying our failure */
+    if(cur_state == KeyReadPopupState_Fail) {
+        view_dispatcher_send_custom_event(
+            state->view_dispatcher, ESubGhzChatEvent_KeyReadPopupFailed);
+        /* done displaying our success */
+    } else if(cur_state == KeyReadPopupState_Success) {
+        view_dispatcher_send_custom_event(
+            state->view_dispatcher, ESubGhzChatEvent_KeyReadPopupSucceeded);
+    }
 }
 
 struct ReplayDictNfcReaderContext {
-	uint8_t *cur;
-	uint8_t *max;
+    uint8_t* cur;
+    uint8_t* max;
 };
 
-static bool replay_dict_nfc_reader(uint64_t *run_id, uint32_t *counter, void
-		*context)
-{
-	struct ReplayDictNfcReaderContext *ctx = (struct
-			ReplayDictNfcReaderContext *) context;
+static bool replay_dict_nfc_reader(uint64_t* run_id, uint32_t* counter, void* context) {
+    struct ReplayDictNfcReaderContext* ctx = (struct ReplayDictNfcReaderContext*)context;
 
-	if (ctx->cur + sizeof(struct ReplayDictNfcEntry) > ctx->max) {
-		return false;
-	}
+    if(ctx->cur + sizeof(struct ReplayDictNfcEntry) > ctx->max) {
+        return false;
+    }
 
-	struct ReplayDictNfcEntry *entry = (struct ReplayDictNfcEntry *)
-		ctx->cur;
-	*run_id = entry->run_id;
-	*counter = __ntohl(entry->counter);
+    struct ReplayDictNfcEntry* entry = (struct ReplayDictNfcEntry*)ctx->cur;
+    *run_id = entry->run_id;
+    *counter = __ntohl(entry->counter);
 
-	ctx->cur += sizeof(struct ReplayDictNfcEntry);
+    ctx->cur += sizeof(struct ReplayDictNfcEntry);
 
-	return true;
+    return true;
 }
 
-static bool key_read_popup_handle_key_read(ESubGhzChatState *state)
-{
-	NfcDeviceData *dev_data = state->nfc_dev_data;
-
-	/* check for config pages */
-	if (dev_data->mf_ul_data.data_read < NFC_CONFIG_PAGES * 4) {
-		return false;
-	}
-
-	size_t data_read = dev_data->mf_ul_data.data_read - (NFC_CONFIG_PAGES *
-			4);
-
-	/* check if key was transmitted */
-	if (data_read < KEY_BITS / 8) {
-		return false;
-	}
-
-	/* initiate the crypto context */
-	bool ret = crypto_ctx_set_key(state->crypto_ctx,
-			dev_data->mf_ul_data.data, state->name_prefix,
-			furi_get_tick());
-
-	/* cleanup */
-	crypto_explicit_bzero(dev_data->mf_ul_data.data, KEY_BITS / 8);
-
-	if (!ret) {
-		crypto_ctx_clear(state->crypto_ctx);
-		return false;
-	}
-
-	/* read the frequency */
-	if (data_read >= (KEY_BITS / 8) + sizeof(struct FreqNfcEntry)) {
-		struct FreqNfcEntry *freq_entry = (struct FreqNfcEntry *)
-			(dev_data->mf_ul_data.data + (KEY_BITS / 8));
-		state->frequency = __ntohl(freq_entry->frequency);
-	}
-
-	/* read the replay dict */
-	struct ReplayDictNfcReaderContext rd_ctx = {
-		.cur = dev_data->mf_ul_data.data + (KEY_BITS / 8) +
-			sizeof(struct FreqNfcEntry),
-		.max = dev_data->mf_ul_data.data + (data_read < NFC_MAX_BYTES ?
-				data_read : NFC_MAX_BYTES)
-	};
-
-	crypto_ctx_read_replay_dict(state->crypto_ctx, replay_dict_nfc_reader,
-			&rd_ctx);
-
-	/* set encrypted flag */
-	state->encrypted = true;
-
-	return true;
+static bool key_read_popup_handle_key_read(ESubGhzChatState* state) {
+    NfcDeviceData* dev_data = state->nfc_dev_data;
+
+    /* check for config pages */
+    if(dev_data->mf_ul_data.data_read < NFC_CONFIG_PAGES * 4) {
+        return false;
+    }
+
+    size_t data_read = dev_data->mf_ul_data.data_read - (NFC_CONFIG_PAGES * 4);
+
+    /* check if key was transmitted */
+    if(data_read < KEY_BITS / 8) {
+        return false;
+    }
+
+    /* initiate the crypto context */
+    bool ret = crypto_ctx_set_key(
+        state->crypto_ctx, dev_data->mf_ul_data.data, state->name_prefix, furi_get_tick());
+
+    /* cleanup */
+    crypto_explicit_bzero(dev_data->mf_ul_data.data, KEY_BITS / 8);
+
+    if(!ret) {
+        crypto_ctx_clear(state->crypto_ctx);
+        return false;
+    }
+
+    /* read the frequency */
+    if(data_read >= (KEY_BITS / 8) + sizeof(struct FreqNfcEntry)) {
+        struct FreqNfcEntry* freq_entry =
+            (struct FreqNfcEntry*)(dev_data->mf_ul_data.data + (KEY_BITS / 8));
+        state->frequency = __ntohl(freq_entry->frequency);
+    }
+
+    /* read the replay dict */
+    struct ReplayDictNfcReaderContext rd_ctx = {
+        .cur = dev_data->mf_ul_data.data + (KEY_BITS / 8) + sizeof(struct FreqNfcEntry),
+        .max =
+            dev_data->mf_ul_data.data + (data_read < NFC_MAX_BYTES ? data_read : NFC_MAX_BYTES)};
+
+    crypto_ctx_read_replay_dict(state->crypto_ctx, replay_dict_nfc_reader, &rd_ctx);
+
+    /* set encrypted flag */
+    state->encrypted = true;
+
+    return true;
 }
 
-static void key_read_popup_set_state(ESubGhzChatState *state, KeyReadPopupState
-		new_state)
-{
-	uint32_t cur_state = scene_manager_get_scene_state(
-			state->scene_manager, ESubGhzChatScene_KeyReadPopup);
-	if (cur_state == new_state) {
-		return;
-	}
-
-	if (new_state == KeyReadPopupState_Detecting) {
-		popup_reset(state->nfc_popup);
-		popup_disable_timeout(state->nfc_popup);
-		popup_set_text(state->nfc_popup, "Tap Flipper\n to sender", 97,
-				24, AlignCenter, AlignTop);
-		popup_set_icon(state->nfc_popup, 0, 8, &I_NFC_manual_60x50);
-		notification_message(state->notification,
-				&sequence_blink_start_cyan);
-	} else if (new_state == KeyReadPopupState_Reading) {
-		popup_reset(state->nfc_popup);
-		popup_disable_timeout(state->nfc_popup);
-		popup_set_header(state->nfc_popup, "Reading key\nDon't "
-				"move...", 85, 24, AlignCenter, AlignTop);
-		popup_set_icon(state->nfc_popup, 12, 23, &I_Loading_24);
-		notification_message(state->notification,
-				&sequence_blink_start_yellow);
-	} else if (new_state == KeyReadPopupState_Fail) {
-		nfc_worker_stop(state->nfc_worker);
-
-		popup_reset(state->nfc_popup);
-		popup_set_header(state->nfc_popup, "Failure!", 64, 2,
-				AlignCenter, AlignTop);
-		popup_set_text(state->nfc_popup, "Failed\nto read\nkey.", 78,
-				16, AlignLeft, AlignTop);
-		popup_set_icon(state->nfc_popup, 21, 13, &I_Cry_dolph_55x52);
-
-		popup_set_timeout(state->nfc_popup, KEY_READ_POPUP_MS);
-		popup_set_context(state->nfc_popup, state);
-		popup_set_callback(state->nfc_popup,
-				key_read_popup_timeout_cb);
-		popup_enable_timeout(state->nfc_popup);
-
-		notification_message(state->notification,
-				&sequence_blink_stop);
-	} else if (new_state == KeyReadPopupState_Success) {
-		nfc_worker_stop(state->nfc_worker);
-
-		popup_reset(state->nfc_popup);
-		popup_set_header(state->nfc_popup, "Key\nread!", 13, 22,
-				AlignLeft, AlignBottom);
-		popup_set_icon(state->nfc_popup, 32, 5, &I_DolphinNice_96x59);
-
-		popup_set_timeout(state->nfc_popup, KEY_READ_POPUP_MS);
-		popup_set_context(state->nfc_popup, state);
-		popup_set_callback(state->nfc_popup,
-				key_read_popup_timeout_cb);
-		popup_enable_timeout(state->nfc_popup);
-
-		notification_message(state->notification, &sequence_success);
-		notification_message(state->notification,
-				&sequence_blink_stop);
-	}
-
-	scene_manager_set_scene_state(state->scene_manager,
-			ESubGhzChatScene_KeyReadPopup, new_state);
-
-	view_dispatcher_switch_to_view(state->view_dispatcher,
-			ESubGhzChatView_NfcPopup);
+static void key_read_popup_set_state(ESubGhzChatState* state, KeyReadPopupState new_state) {
+    uint32_t cur_state =
+        scene_manager_get_scene_state(state->scene_manager, ESubGhzChatScene_KeyReadPopup);
+    if(cur_state == new_state) {
+        return;
+    }
+
+    if(new_state == KeyReadPopupState_Detecting) {
+        popup_reset(state->nfc_popup);
+        popup_disable_timeout(state->nfc_popup);
+        popup_set_text(state->nfc_popup, "Tap Flipper\n to sender", 97, 24, AlignCenter, AlignTop);
+        popup_set_icon(state->nfc_popup, 0, 8, &I_NFC_manual_60x50);
+        notification_message(state->notification, &sequence_blink_start_cyan);
+    } else if(new_state == KeyReadPopupState_Reading) {
+        popup_reset(state->nfc_popup);
+        popup_disable_timeout(state->nfc_popup);
+        popup_set_header(
+            state->nfc_popup,
+            "Reading key\nDon't "
+            "move...",
+            85,
+            24,
+            AlignCenter,
+            AlignTop);
+        popup_set_icon(state->nfc_popup, 12, 23, &I_Loading_24);
+        notification_message(state->notification, &sequence_blink_start_yellow);
+    } else if(new_state == KeyReadPopupState_Fail) {
+        nfc_worker_stop(state->nfc_worker);
+
+        popup_reset(state->nfc_popup);
+        popup_set_header(state->nfc_popup, "Failure!", 64, 2, AlignCenter, AlignTop);
+        popup_set_text(state->nfc_popup, "Failed\nto read\nkey.", 78, 16, AlignLeft, AlignTop);
+        popup_set_icon(state->nfc_popup, 21, 13, &I_Cry_dolph_55x52);
+
+        popup_set_timeout(state->nfc_popup, KEY_READ_POPUP_MS);
+        popup_set_context(state->nfc_popup, state);
+        popup_set_callback(state->nfc_popup, key_read_popup_timeout_cb);
+        popup_enable_timeout(state->nfc_popup);
+
+        notification_message(state->notification, &sequence_blink_stop);
+    } else if(new_state == KeyReadPopupState_Success) {
+        nfc_worker_stop(state->nfc_worker);
+
+        popup_reset(state->nfc_popup);
+        popup_set_header(state->nfc_popup, "Key\nread!", 13, 22, AlignLeft, AlignBottom);
+        popup_set_icon(state->nfc_popup, 32, 5, &I_DolphinNice_96x59);
+
+        popup_set_timeout(state->nfc_popup, KEY_READ_POPUP_MS);
+        popup_set_context(state->nfc_popup, state);
+        popup_set_callback(state->nfc_popup, key_read_popup_timeout_cb);
+        popup_enable_timeout(state->nfc_popup);
+
+        notification_message(state->notification, &sequence_success);
+        notification_message(state->notification, &sequence_blink_stop);
+    }
+
+    scene_manager_set_scene_state(state->scene_manager, ESubGhzChatScene_KeyReadPopup, new_state);
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_NfcPopup);
 }
 
 /* Prepares the key share read scene. */
-void scene_on_enter_key_read_popup(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_read_popup");
+void scene_on_enter_key_read_popup(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_read_popup");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	key_read_popup_set_state(state, KeyReadPopupState_Detecting);
+    key_read_popup_set_state(state, KeyReadPopupState_Detecting);
 
-	state->nfc_dev_data->parsed_data = furi_string_alloc();
-	if (state->nfc_dev_data->parsed_data == NULL) {
-		/* can't do anything here, crash */
-		furi_check(0);
-	}
+    state->nfc_dev_data->parsed_data = furi_string_alloc();
+    if(state->nfc_dev_data->parsed_data == NULL) {
+        /* can't do anything here, crash */
+        furi_check(0);
+    }
 
-	nfc_worker_start(state->nfc_worker, NfcWorkerStateRead,
-			state->nfc_dev_data, read_worker_cb, state);
+    nfc_worker_start(
+        state->nfc_worker, NfcWorkerStateRead, state->nfc_dev_data, read_worker_cb, state);
 }
 
 /* Handles scene manager events for the key read popup scene. */
-bool scene_on_event_key_read_popup(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_read_popup");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* card detected */
-		case NfcWorkerEventCardDetected:
-			key_read_popup_set_state(state,
-					KeyReadPopupState_Reading);
-			consumed = true;
-			break;
-
-		/* no card detected */
-		case NfcWorkerEventNoCardDetected:
-			key_read_popup_set_state(state,
-					KeyReadPopupState_Detecting);
-			consumed = true;
-			break;
-
-		/* key probably read */
-		case NfcWorkerEventReadMfUltralight:
-			if (key_read_popup_handle_key_read(state)) {
-				key_read_popup_set_state(state,
-						KeyReadPopupState_Success);
-			} else {
-				key_read_popup_set_state(state,
-						KeyReadPopupState_Fail);
-			}
-			consumed = true;
-			break;
-
-		/* close the popup and go back */
-		case ESubGhzChatEvent_KeyReadPopupFailed:
-			if (!scene_manager_previous_scene(
-						state->scene_manager)) {
-				view_dispatcher_stop(state->view_dispatcher);
-			}
-			consumed = true;
-			break;
-
-		/* success, go to frequency input */
-		case ESubGhzChatEvent_KeyReadPopupSucceeded:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_FreqInput);
-			consumed = true;
-			break;
-
-		/* something else happend, treat as failure */
-		default:
-			key_read_popup_set_state(state,
-					KeyReadPopupState_Fail);
-			consumed = true;
-			break;
-		}
-
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_key_read_popup(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_read_popup");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* card detected */
+        case NfcWorkerEventCardDetected:
+            key_read_popup_set_state(state, KeyReadPopupState_Reading);
+            consumed = true;
+            break;
+
+        /* no card detected */
+        case NfcWorkerEventNoCardDetected:
+            key_read_popup_set_state(state, KeyReadPopupState_Detecting);
+            consumed = true;
+            break;
+
+        /* key probably read */
+        case NfcWorkerEventReadMfUltralight:
+            if(key_read_popup_handle_key_read(state)) {
+                key_read_popup_set_state(state, KeyReadPopupState_Success);
+            } else {
+                key_read_popup_set_state(state, KeyReadPopupState_Fail);
+            }
+            consumed = true;
+            break;
+
+        /* close the popup and go back */
+        case ESubGhzChatEvent_KeyReadPopupFailed:
+            if(!scene_manager_previous_scene(state->scene_manager)) {
+                view_dispatcher_stop(state->view_dispatcher);
+            }
+            consumed = true;
+            break;
+
+        /* success, go to frequency input */
+        case ESubGhzChatEvent_KeyReadPopupSucceeded:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_FreqInput);
+            consumed = true;
+            break;
+
+        /* something else happend, treat as failure */
+        default:
+            key_read_popup_set_state(state, KeyReadPopupState_Fail);
+            consumed = true;
+            break;
+        }
+
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the key read popup scene. */
-void scene_on_exit_key_read_popup(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_read_popup");
+void scene_on_exit_key_read_popup(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_read_popup");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	popup_reset(state->nfc_popup);
-	scene_manager_set_scene_state(state->scene_manager,
-			ESubGhzChatScene_KeyReadPopup, KeyReadPopupState_Idle);
+    popup_reset(state->nfc_popup);
+    scene_manager_set_scene_state(
+        state->scene_manager, ESubGhzChatScene_KeyReadPopup, KeyReadPopupState_Idle);
 
-	notification_message(state->notification, &sequence_blink_stop);
+    notification_message(state->notification, &sequence_blink_stop);
 
-	nfc_worker_stop(state->nfc_worker);
+    nfc_worker_stop(state->nfc_worker);
 
-	crypto_explicit_bzero(state->nfc_dev_data->mf_ul_data.data, KEY_BITS / 8);
-	if (state->nfc_dev_data->parsed_data != NULL) {
-		furi_string_free(state->nfc_dev_data->parsed_data);
-	}
-	memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
+    crypto_explicit_bzero(state->nfc_dev_data->mf_ul_data.data, KEY_BITS / 8);
+    if(state->nfc_dev_data->parsed_data != NULL) {
+        furi_string_free(state->nfc_dev_data->parsed_data);
+    }
+    memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
 }

+ 87 - 103
esubghz_chat/scenes/esubghz_chat_key_share_popup.c

@@ -2,139 +2,123 @@
 #include "../helpers/nfc_helpers.h"
 
 struct ReplayDictNfcWriterContext {
-	uint8_t *cur;
-	uint8_t *max;
+    uint8_t* cur;
+    uint8_t* max;
 };
 
-static bool replay_dict_nfc_writer(uint64_t run_id, uint32_t counter, void
-		*context)
-{
-	struct ReplayDictNfcWriterContext *ctx = (struct
-			ReplayDictNfcWriterContext *) context;
+static bool replay_dict_nfc_writer(uint64_t run_id, uint32_t counter, void* context) {
+    struct ReplayDictNfcWriterContext* ctx = (struct ReplayDictNfcWriterContext*)context;
 
-	struct ReplayDictNfcEntry entry = {
-		.run_id = run_id,
-		.counter = __htonl(counter),
-		.unused = 0
-	};
+    struct ReplayDictNfcEntry entry = {.run_id = run_id, .counter = __htonl(counter), .unused = 0};
 
-	if (ctx->cur + sizeof(entry) > ctx->max) {
-		return false;
-	}
+    if(ctx->cur + sizeof(entry) > ctx->max) {
+        return false;
+    }
 
-	memcpy(ctx->cur, &entry, sizeof(entry));
-	ctx->cur += sizeof(entry);
+    memcpy(ctx->cur, &entry, sizeof(entry));
+    ctx->cur += sizeof(entry);
 
-	return true;
+    return true;
 }
 
-static void prepare_nfc_dev_data(ESubGhzChatState *state)
-{
-	NfcDeviceData *dev_data = state->nfc_dev_data;
-
-	dev_data->protocol = NfcDeviceProtocolMifareUl;
-	furi_hal_random_fill_buf(dev_data->nfc_data.uid, 7);
-	dev_data->nfc_data.uid_len = 7;
-	dev_data->nfc_data.atqa[0] = 0x44;
-	dev_data->nfc_data.atqa[1] = 0x00;
-	dev_data->nfc_data.sak = 0x00;
-
-	dev_data->mf_ul_data.type = MfUltralightTypeNTAG215;
-	dev_data->mf_ul_data.version.header = 0x00;
-	dev_data->mf_ul_data.version.vendor_id = 0x04;
-	dev_data->mf_ul_data.version.prod_type = 0x04;
-	dev_data->mf_ul_data.version.prod_subtype = 0x02;
-	dev_data->mf_ul_data.version.prod_ver_major = 0x01;
-	dev_data->mf_ul_data.version.prod_ver_minor = 0x00;
-	dev_data->mf_ul_data.version.storage_size = 0x11;
-	dev_data->mf_ul_data.version.protocol_type = 0x03;
-
-	size_t data_written = 0;
-
-	/* write key */
-	crypto_ctx_get_key(state->crypto_ctx, dev_data->mf_ul_data.data);
-	data_written += (KEY_BITS / 8);
-
-	/* write frequency */
-	struct FreqNfcEntry *freq_entry = (struct FreqNfcEntry *)
-		(dev_data->mf_ul_data.data + data_written);
-	freq_entry->frequency = __htonl(state->frequency);
-	freq_entry->unused1 = 0;
-	freq_entry->unused2 = 0;
-	freq_entry->unused3 = 0;
-	data_written += sizeof(struct FreqNfcEntry);
-
-	/* write the replay dict */
-	struct ReplayDictNfcWriterContext wr_ctx = {
-		.cur = dev_data->mf_ul_data.data + data_written,
-		.max = dev_data->mf_ul_data.data + NFC_MAX_BYTES
-	};
-
-	size_t n_entries = crypto_ctx_dump_replay_dict(state->crypto_ctx,
-			replay_dict_nfc_writer, &wr_ctx);
-	data_written += n_entries * sizeof(struct ReplayDictNfcEntry);
-
-	/* calculate size of data, add 16 for config pages */
-	dev_data->mf_ul_data.data_size = data_written + (NFC_CONFIG_PAGES * 4);
+static void prepare_nfc_dev_data(ESubGhzChatState* state) {
+    NfcDeviceData* dev_data = state->nfc_dev_data;
+
+    dev_data->protocol = NfcDeviceProtocolMifareUl;
+    furi_hal_random_fill_buf(dev_data->nfc_data.uid, 7);
+    dev_data->nfc_data.uid_len = 7;
+    dev_data->nfc_data.atqa[0] = 0x44;
+    dev_data->nfc_data.atqa[1] = 0x00;
+    dev_data->nfc_data.sak = 0x00;
+
+    dev_data->mf_ul_data.type = MfUltralightTypeNTAG215;
+    dev_data->mf_ul_data.version.header = 0x00;
+    dev_data->mf_ul_data.version.vendor_id = 0x04;
+    dev_data->mf_ul_data.version.prod_type = 0x04;
+    dev_data->mf_ul_data.version.prod_subtype = 0x02;
+    dev_data->mf_ul_data.version.prod_ver_major = 0x01;
+    dev_data->mf_ul_data.version.prod_ver_minor = 0x00;
+    dev_data->mf_ul_data.version.storage_size = 0x11;
+    dev_data->mf_ul_data.version.protocol_type = 0x03;
+
+    size_t data_written = 0;
+
+    /* write key */
+    crypto_ctx_get_key(state->crypto_ctx, dev_data->mf_ul_data.data);
+    data_written += (KEY_BITS / 8);
+
+    /* write frequency */
+    struct FreqNfcEntry* freq_entry =
+        (struct FreqNfcEntry*)(dev_data->mf_ul_data.data + data_written);
+    freq_entry->frequency = __htonl(state->frequency);
+    freq_entry->unused1 = 0;
+    freq_entry->unused2 = 0;
+    freq_entry->unused3 = 0;
+    data_written += sizeof(struct FreqNfcEntry);
+
+    /* write the replay dict */
+    struct ReplayDictNfcWriterContext wr_ctx = {
+        .cur = dev_data->mf_ul_data.data + data_written,
+        .max = dev_data->mf_ul_data.data + NFC_MAX_BYTES};
+
+    size_t n_entries =
+        crypto_ctx_dump_replay_dict(state->crypto_ctx, replay_dict_nfc_writer, &wr_ctx);
+    data_written += n_entries * sizeof(struct ReplayDictNfcEntry);
+
+    /* calculate size of data, add 16 for config pages */
+    dev_data->mf_ul_data.data_size = data_written + (NFC_CONFIG_PAGES * 4);
 }
 
 /* Prepares the key share popup scene. */
-void scene_on_enter_key_share_popup(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_share_popup");
+void scene_on_enter_key_share_popup(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_key_share_popup");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	popup_reset(state->nfc_popup);
+    popup_reset(state->nfc_popup);
 
-	popup_disable_timeout(state->nfc_popup);
+    popup_disable_timeout(state->nfc_popup);
 
-	popup_set_header(state->nfc_popup, "Sharing...", 67, 13, AlignLeft,
-			AlignTop);
-	popup_set_icon(state->nfc_popup, 0, 3, &I_NFC_dolphin_emulation_47x61);
-	popup_set_text(state->nfc_popup, "Sharing\nKey via\nNFC", 90, 28,
-			AlignCenter, AlignTop);
+    popup_set_header(state->nfc_popup, "Sharing...", 67, 13, AlignLeft, AlignTop);
+    popup_set_icon(state->nfc_popup, 0, 3, &I_NFC_dolphin_emulation_47x61);
+    popup_set_text(state->nfc_popup, "Sharing\nKey via\nNFC", 90, 28, AlignCenter, AlignTop);
 
-	prepare_nfc_dev_data(state);
-	nfc_worker_start(state->nfc_worker, NfcWorkerStateMfUltralightEmulate,
-			state->nfc_dev_data, NULL, NULL);
+    prepare_nfc_dev_data(state);
+    nfc_worker_start(
+        state->nfc_worker, NfcWorkerStateMfUltralightEmulate, state->nfc_dev_data, NULL, NULL);
 
-	notification_message(state->notification,
-			&sequence_blink_start_magenta);
+    notification_message(state->notification, &sequence_blink_start_magenta);
 
-	view_dispatcher_switch_to_view(state->view_dispatcher,
-			ESubGhzChatView_NfcPopup);
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_NfcPopup);
 }
 
 /* Handles scene manager events for the key share popup scene. */
-bool scene_on_event_key_share_popup(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_share_popup");
+bool scene_on_event_key_share_popup(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_key_share_popup");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	UNUSED(state);
-	UNUSED(event);
+    UNUSED(state);
+    UNUSED(event);
 
-	return false;
+    return false;
 }
 
 /* Cleans up the key share popup scene. */
-void scene_on_exit_key_share_popup(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_share_popup");
+void scene_on_exit_key_share_popup(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_key_share_popup");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	popup_reset(state->nfc_popup);
+    popup_reset(state->nfc_popup);
 
-	notification_message(state->notification, &sequence_blink_stop);
+    notification_message(state->notification, &sequence_blink_stop);
 
-	nfc_worker_stop(state->nfc_worker);
+    nfc_worker_stop(state->nfc_worker);
 
-	crypto_explicit_bzero(state->nfc_dev_data->mf_ul_data.data, KEY_BITS / 8);
-	memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
+    crypto_explicit_bzero(state->nfc_dev_data->mf_ul_data.data, KEY_BITS / 8);
+    memset(state->nfc_dev_data, 0, sizeof(NfcDeviceData));
 }

+ 78 - 94
esubghz_chat/scenes/esubghz_chat_pass_input.c

@@ -1,125 +1,109 @@
 #include "../esubghz_chat_i.h"
 
 /* Sends PassEntered event to scene manager. */
-static void pass_input_cb(void *context)
-{
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+static void pass_input_cb(void* context) {
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	crypto_explicit_bzero(state->text_input_store,
-			sizeof(state->text_input_store));
+    crypto_explicit_bzero(state->text_input_store, sizeof(state->text_input_store));
 
-	view_dispatcher_send_custom_event(state->view_dispatcher,
-			ESubGhzChatEvent_PassEntered);
+    view_dispatcher_send_custom_event(state->view_dispatcher, ESubGhzChatEvent_PassEntered);
 }
 
 /* If a password was entered this derives a key from the password using a
  * single pass of SHA256 and initiates the AES-GCM context for encryption. If
  * the initiation fails, the password is rejected. */
-static bool pass_input_validator(const char *text, FuriString *error,
-		void *context)
-{
-	furi_assert(text);
-	furi_assert(error);
+static bool pass_input_validator(const char* text, FuriString* error, void* context) {
+    furi_assert(text);
+    furi_assert(error);
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	if (strlen(text) == 0) {
-		furi_string_printf(error, "Enter a\npassword!");
-		return false;
-	}
+    if(strlen(text) == 0) {
+        furi_string_printf(error, "Enter a\npassword!");
+        return false;
+    }
 
-	unsigned char key[KEY_BITS / 8];
+    unsigned char key[KEY_BITS / 8];
 
-	/* derive a key from the password */
-	sha256((unsigned char *) text, strlen(text), key);
+    /* derive a key from the password */
+    sha256((unsigned char*)text, strlen(text), key);
 
-	/* initiate the crypto context */
-	bool ret = crypto_ctx_set_key(state->crypto_ctx, key,
-			state->name_prefix, furi_get_tick());
+    /* initiate the crypto context */
+    bool ret = crypto_ctx_set_key(state->crypto_ctx, key, state->name_prefix, furi_get_tick());
 
-	/* cleanup */
-	crypto_explicit_bzero(key, sizeof(key));
+    /* cleanup */
+    crypto_explicit_bzero(key, sizeof(key));
 
-	if (!ret) {
-		crypto_ctx_clear(state->crypto_ctx);
-		furi_string_printf(error, "Failed to\nset key!");
-		return false;
-	}
+    if(!ret) {
+        crypto_ctx_clear(state->crypto_ctx);
+        furi_string_printf(error, "Failed to\nset key!");
+        return false;
+    }
 
-	state->encrypted = true;
+    state->encrypted = true;
 
-	return true;
+    return true;
 }
 
 /* Prepares the password input scene. */
-void scene_on_enter_pass_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_pass_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	state->text_input_store[0] = 0;
-	text_input_reset(state->text_input);
-	text_input_set_result_callback(
-			state->text_input,
-			pass_input_cb,
-			state,
-			state->text_input_store,
-			sizeof(state->text_input_store),
-			true);
-	text_input_set_validator(
-			state->text_input,
-			pass_input_validator,
-			state);
-	text_input_set_header_text(
-			state->text_input,
-			"Password");
-
-	view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
+void scene_on_enter_pass_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_enter_pass_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    state->text_input_store[0] = 0;
+    text_input_reset(state->text_input);
+    text_input_set_result_callback(
+        state->text_input,
+        pass_input_cb,
+        state,
+        state->text_input_store,
+        sizeof(state->text_input_store),
+        true);
+    text_input_set_validator(state->text_input, pass_input_validator, state);
+    text_input_set_header_text(state->text_input, "Password");
+
+    view_dispatcher_switch_to_view(state->view_dispatcher, ESubGhzChatView_Input);
 }
 
 /* Handles scene manager events for the password input scene. */
-bool scene_on_event_pass_input(void* context, SceneManagerEvent event)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_event_pass_input");
-
-	furi_assert(context);
-	ESubGhzChatState* state = context;
-
-	bool consumed = false;
-
-	switch(event.type) {
-	case SceneManagerEventTypeCustom:
-		switch(event.event) {
-		/* switch to frequency input scene */
-		case ESubGhzChatEvent_PassEntered:
-			scene_manager_next_scene(state->scene_manager,
-					ESubGhzChatScene_FreqInput);
-			consumed = true;
-			break;
-		}
-		break;
-
-	default:
-		consumed = false;
-		break;
-	}
-
-	return consumed;
+bool scene_on_event_pass_input(void* context, SceneManagerEvent event) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_event_pass_input");
+
+    furi_assert(context);
+    ESubGhzChatState* state = context;
+
+    bool consumed = false;
+
+    switch(event.type) {
+    case SceneManagerEventTypeCustom:
+        switch(event.event) {
+        /* switch to frequency input scene */
+        case ESubGhzChatEvent_PassEntered:
+            scene_manager_next_scene(state->scene_manager, ESubGhzChatScene_FreqInput);
+            consumed = true;
+            break;
+        }
+        break;
+
+    default:
+        consumed = false;
+        break;
+    }
+
+    return consumed;
 }
 
 /* Cleans up the password input scene. */
-void scene_on_exit_pass_input(void* context)
-{
-	FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_pass_input");
+void scene_on_exit_pass_input(void* context) {
+    FURI_LOG_T(APPLICATION_NAME, "scene_on_exit_pass_input");
 
-	furi_assert(context);
-	ESubGhzChatState* state = context;
+    furi_assert(context);
+    ESubGhzChatState* state = context;
 
-	text_input_reset(state->text_input);
-	crypto_explicit_bzero(state->text_input_store,
-			sizeof(state->text_input_store));
+    text_input_reset(state->text_input);
+    crypto_explicit_bzero(state->text_input_store, sizeof(state->text_input_store));
 }

+ 2 - 2
esubghz_chat/scenes/esubghz_chat_scene.h

@@ -6,7 +6,7 @@
 #define ADD_SCENE(prefix, name, id) ESubGhzChatScene_##id,
 typedef enum {
 #include "esubghz_chat_scene_config.h"
-	ESubGhzChatScene_MAX
+    ESubGhzChatScene_MAX
 } ESubGhzChatScene;
 #undef ADD_SCENE
 
@@ -19,7 +19,7 @@ extern const SceneManagerHandlers esubghz_chat_scene_event_handlers;
 
 // Generate scene on_event handlers declaration
 #define ADD_SCENE(prefix, name, id) \
-	bool scene_on_event_##name(void* context, SceneManagerEvent event);
+    bool scene_on_event_##name(void* context, SceneManagerEvent event);
 #include "esubghz_chat_scene_config.h"
 #undef ADD_SCENE
 

+ 116 - 120
evil_portal/evil_portal_app.c

@@ -4,150 +4,146 @@
 #include <furi.h>
 #include <furi_hal.h>
 
-static bool evil_portal_app_custom_event_callback(void *context,
-                                                  uint32_t event) {
-  furi_assert(context);
-  Evil_PortalApp *app = context;
-  return scene_manager_handle_custom_event(app->scene_manager, event);
+static bool evil_portal_app_custom_event_callback(void* context, uint32_t event) {
+    furi_assert(context);
+    Evil_PortalApp* app = context;
+    return scene_manager_handle_custom_event(app->scene_manager, event);
 }
 
-static bool evil_portal_app_back_event_callback(void *context) {
-  furi_assert(context);
-  Evil_PortalApp *app = context;
-  return scene_manager_handle_back_event(app->scene_manager);
+static bool evil_portal_app_back_event_callback(void* context) {
+    furi_assert(context);
+    Evil_PortalApp* app = context;
+    return scene_manager_handle_back_event(app->scene_manager);
 }
 
-static void evil_portal_app_tick_event_callback(void *context) {
-  furi_assert(context);
-  Evil_PortalApp *app = context;
-  scene_manager_handle_tick_event(app->scene_manager);
+static void evil_portal_app_tick_event_callback(void* context) {
+    furi_assert(context);
+    Evil_PortalApp* app = context;
+    scene_manager_handle_tick_event(app->scene_manager);
 }
 
-Evil_PortalApp *evil_portal_app_alloc() {
-  Evil_PortalApp *app = malloc(sizeof(Evil_PortalApp));
-
-  app->sent_html = false;
-  app->sent_ap = false;
-  app->sent_reset = false;
-  app->has_command_queue = false;  
-  app->command_index = 0;
-  app->portal_logs = furi_string_alloc();
-  
-  app->dialogs = furi_record_open(RECORD_DIALOGS);
-  app->file_path = furi_string_alloc();
-  
-  app->gui = furi_record_open(RECORD_GUI);
-
-  app->view_dispatcher = view_dispatcher_alloc();
-
-  app->loading = loading_alloc();
-  
-  app->scene_manager = scene_manager_alloc(&evil_portal_scene_handlers, app);
-  view_dispatcher_enable_queue(app->view_dispatcher);
-  view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
-
-  view_dispatcher_set_custom_event_callback(
-      app->view_dispatcher, evil_portal_app_custom_event_callback);
-  view_dispatcher_set_navigation_event_callback(
-      app->view_dispatcher, evil_portal_app_back_event_callback);
-  view_dispatcher_set_tick_event_callback(
-      app->view_dispatcher, evil_portal_app_tick_event_callback, 100);
-
-  view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui,
-                                ViewDispatcherTypeFullscreen);
-
-  app->view_stack = view_stack_alloc();
-
-  app->var_item_list = variable_item_list_alloc();
-  view_dispatcher_add_view(app->view_dispatcher, Evil_PortalAppViewVarItemList,
-                           variable_item_list_get_view(app->var_item_list));
-
-  app->text_input = text_input_alloc();
-  view_dispatcher_add_view(app->view_dispatcher, Evil_PortalAppViewTextInput, text_input_get_view(app->text_input));
-                    
-
-  for (int i = 0; i < NUM_MENU_ITEMS; ++i) {
-    app->selected_option_index[i] = 0;
-  }
-
-  app->text_box = text_box_alloc();
-  view_dispatcher_add_view(app->view_dispatcher,
-                           Evil_PortalAppViewConsoleOutput,
-                           text_box_get_view(app->text_box));
-  app->text_box_store = furi_string_alloc();
-  furi_string_reserve(app->text_box_store, EVIL_PORTAL_TEXT_BOX_STORE_SIZE);
-
-  scene_manager_next_scene(app->scene_manager, Evil_PortalSceneStart);
-
-  return app;
+Evil_PortalApp* evil_portal_app_alloc() {
+    Evil_PortalApp* app = malloc(sizeof(Evil_PortalApp));
+
+    app->sent_html = false;
+    app->sent_ap = false;
+    app->sent_reset = false;
+    app->has_command_queue = false;
+    app->command_index = 0;
+    app->portal_logs = furi_string_alloc();
+
+    app->dialogs = furi_record_open(RECORD_DIALOGS);
+    app->file_path = furi_string_alloc();
+
+    app->gui = furi_record_open(RECORD_GUI);
+
+    app->view_dispatcher = view_dispatcher_alloc();
+
+    app->loading = loading_alloc();
+
+    app->scene_manager = scene_manager_alloc(&evil_portal_scene_handlers, app);
+    view_dispatcher_enable_queue(app->view_dispatcher);
+    view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
+
+    view_dispatcher_set_custom_event_callback(
+        app->view_dispatcher, evil_portal_app_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        app->view_dispatcher, evil_portal_app_back_event_callback);
+    view_dispatcher_set_tick_event_callback(
+        app->view_dispatcher, evil_portal_app_tick_event_callback, 100);
+
+    view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
+
+    app->view_stack = view_stack_alloc();
+
+    app->var_item_list = variable_item_list_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        Evil_PortalAppViewVarItemList,
+        variable_item_list_get_view(app->var_item_list));
+
+    app->text_input = text_input_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher, Evil_PortalAppViewTextInput, text_input_get_view(app->text_input));
+
+    for(int i = 0; i < NUM_MENU_ITEMS; ++i) {
+        app->selected_option_index[i] = 0;
+    }
+
+    app->text_box = text_box_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher, Evil_PortalAppViewConsoleOutput, text_box_get_view(app->text_box));
+    app->text_box_store = furi_string_alloc();
+    furi_string_reserve(app->text_box_store, EVIL_PORTAL_TEXT_BOX_STORE_SIZE);
+
+    scene_manager_next_scene(app->scene_manager, Evil_PortalSceneStart);
+
+    return app;
 }
 
-void evil_portal_app_free(Evil_PortalApp *app) {  
+void evil_portal_app_free(Evil_PortalApp* app) {
+    // save latest logs
+    if(furi_string_utf8_length(app->portal_logs) > 0) {
+        write_logs(app->portal_logs);
+        furi_string_free(app->portal_logs);
+    }
 
-  // save latest logs
-  if (furi_string_utf8_length(app->portal_logs) > 0) {
-    write_logs(app->portal_logs);
-    furi_string_free(app->portal_logs);
-  }
+    // Send reset event to dev board
+    evil_portal_uart_tx((uint8_t*)(RESET_CMD), strlen(RESET_CMD));
+    evil_portal_uart_tx((uint8_t*)("\n"), 1);
 
-  // Send reset event to dev board
-  evil_portal_uart_tx((uint8_t *)(RESET_CMD), strlen(RESET_CMD));
-  evil_portal_uart_tx((uint8_t *)("\n"), 1);
+    furi_assert(app);
 
-  furi_assert(app);
+    // Views
+    view_dispatcher_remove_view(app->view_dispatcher, Evil_PortalAppViewVarItemList);
+    view_dispatcher_remove_view(app->view_dispatcher, Evil_PortalAppViewConsoleOutput);
 
-  // Views
-  view_dispatcher_remove_view(app->view_dispatcher,
-                              Evil_PortalAppViewVarItemList);
-  view_dispatcher_remove_view(app->view_dispatcher,
-                              Evil_PortalAppViewConsoleOutput);
+    text_box_free(app->text_box);
+    furi_string_free(app->text_box_store);
+    text_input_free(app->text_input);
 
-  text_box_free(app->text_box);
-  furi_string_free(app->text_box_store);
-  text_input_free(app->text_input);
-  
-  view_stack_free(app->view_stack);
-  loading_free(app->loading);
+    view_stack_free(app->view_stack);
+    loading_free(app->loading);
 
-  // View dispatcher
-  view_dispatcher_free(app->view_dispatcher);
-  scene_manager_free(app->scene_manager);
+    // View dispatcher
+    view_dispatcher_free(app->view_dispatcher);
+    scene_manager_free(app->scene_manager);
 
-  evil_portal_uart_free(app->uart);
+    evil_portal_uart_free(app->uart);
 
-  // Close records
-  furi_record_close(RECORD_GUI);
+    // Close records
+    furi_record_close(RECORD_GUI);
 
-  furi_record_close(RECORD_DIALOGS);
-  furi_string_free(app->file_path);
+    furi_record_close(RECORD_DIALOGS);
+    furi_string_free(app->file_path);
 
-  free(app);
+    free(app);
 }
 
-int32_t evil_portal_app(void *p) {  
-  UNUSED(p);
-  Evil_PortalApp *evil_portal_app = evil_portal_app_alloc();
+int32_t evil_portal_app(void* p) {
+    UNUSED(p);
+    Evil_PortalApp* evil_portal_app = evil_portal_app_alloc();
 
-  bool otg_was_enabled = furi_hal_power_is_otg_enabled();
-  // turn off 5v, so it gets reset on startup
-  if(otg_was_enabled) {
-    furi_hal_power_disable_otg();
-  }
-  uint8_t attempts = 0;
-  while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
-    furi_hal_power_enable_otg();
-    furi_delay_ms(10);
-  }
+    bool otg_was_enabled = furi_hal_power_is_otg_enabled();
+    // turn off 5v, so it gets reset on startup
+    if(otg_was_enabled) {
+        furi_hal_power_disable_otg();
+    }
+    uint8_t attempts = 0;
+    while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
+        furi_hal_power_enable_otg();
+        furi_delay_ms(10);
+    }
 
-  evil_portal_app->uart = evil_portal_uart_init(evil_portal_app);
+    evil_portal_app->uart = evil_portal_uart_init(evil_portal_app);
 
-  view_dispatcher_run(evil_portal_app->view_dispatcher);  
+    view_dispatcher_run(evil_portal_app->view_dispatcher);
 
-  evil_portal_app_free(evil_portal_app);
+    evil_portal_app_free(evil_portal_app);
 
-  if(furi_hal_power_is_otg_enabled() && !otg_was_enabled) {
-    furi_hal_power_disable_otg();
-  }
+    if(furi_hal_power_is_otg_enabled() && !otg_was_enabled) {
+        furi_hal_power_disable_otg();
+    }
 
-  return 0;
+    return 0;
 }

+ 37 - 38
evil_portal/evil_portal_app_i.h

@@ -21,56 +21,55 @@
 #define NUM_MENU_ITEMS (6)
 
 #define EVIL_PORTAL_TEXT_BOX_STORE_SIZE (4096)
-#define UART_CH                                                              \
-    (xtreme_settings.uart_esp_channel == UARTDefault ? FuriHalUartIdUSART1 : \
-                                                       FuriHalUartIdLPUART1)
+#define UART_CH \
+    (xtreme_settings.uart_esp_channel == UARTDefault ? FuriHalUartIdUSART1 : FuriHalUartIdLPUART1)
 
 #define SET_HTML_CMD "sethtml"
 #define SET_AP_CMD "setap"
 #define RESET_CMD "reset"
 
 struct Evil_PortalApp {
-  Gui *gui;
-  ViewDispatcher *view_dispatcher;
-  SceneManager *scene_manager;
+    Gui* gui;
+    ViewDispatcher* view_dispatcher;
+    SceneManager* scene_manager;
 
-  FuriString* portal_logs;
-  const char *command_queue[1];
-  int command_index;
-  bool has_command_queue;
+    FuriString* portal_logs;
+    const char* command_queue[1];
+    int command_index;
+    bool has_command_queue;
 
-  FuriString *text_box_store;
-  size_t text_box_store_strlen;
-  TextBox *text_box;
+    FuriString* text_box_store;
+    size_t text_box_store_strlen;
+    TextBox* text_box;
 
-  VariableItemList *var_item_list;
-  Evil_PortalUart *uart;
-  TextInput* text_input;
-  DialogsApp* dialogs;
-  FuriString* file_path;
-  Loading* loading;
-  ViewStack* view_stack;
+    VariableItemList* var_item_list;
+    Evil_PortalUart* uart;
+    TextInput* text_input;
+    DialogsApp* dialogs;
+    FuriString* file_path;
+    Loading* loading;
+    ViewStack* view_stack;
 
-  int selected_menu_index;
-  int selected_option_index[NUM_MENU_ITEMS];
-  const char *selected_tx_string;
-  bool is_command;
-  bool is_custom_tx_string;
-  bool focus_console_start;
-  bool show_stopscan_tip;
-  bool sent_ap;
-  bool sent_html;
-  bool sent_reset;
-  int BAUDRATE;
-  char text_store[2][128 + 1];
+    int selected_menu_index;
+    int selected_option_index[NUM_MENU_ITEMS];
+    const char* selected_tx_string;
+    bool is_command;
+    bool is_custom_tx_string;
+    bool focus_console_start;
+    bool show_stopscan_tip;
+    bool sent_ap;
+    bool sent_html;
+    bool sent_reset;
+    int BAUDRATE;
+    char text_store[2][128 + 1];
 
-  uint8_t *index_html;
-  uint8_t *ap_name;
+    uint8_t* index_html;
+    uint8_t* ap_name;
 };
 
 typedef enum {
-  Evil_PortalAppViewVarItemList,
-  Evil_PortalAppViewConsoleOutput,
-  Evil_PortalAppViewStartPortal,
-  Evil_PortalAppViewTextInput,
+    Evil_PortalAppViewVarItemList,
+    Evil_PortalAppViewConsoleOutput,
+    Evil_PortalAppViewStartPortal,
+    Evil_PortalAppViewTextInput,
 } Evil_PortalAppView;

+ 5 - 5
evil_portal/evil_portal_custom_event.h

@@ -1,9 +1,9 @@
 #pragma once
 
 typedef enum {
-  Evil_PortalEventRefreshConsoleOutput = 0,
-  Evil_PortalEventStartConsole,
-  Evil_PortalEventStartKeyboard,
-  Evil_PortalEventStartPortal,
-  Evil_PortalEventTextInput,
+    Evil_PortalEventRefreshConsoleOutput = 0,
+    Evil_PortalEventStartConsole,
+    Evil_PortalEventStartKeyboard,
+    Evil_PortalEventStartPortal,
+    Evil_PortalEventTextInput,
 } Evil_PortalCustomEvent;

+ 119 - 121
evil_portal/evil_portal_uart.c

@@ -3,157 +3,155 @@
 #include "helpers/evil_portal_storage.h"
 
 struct Evil_PortalUart {
-  Evil_PortalApp *app;
-  FuriThread *rx_thread;
-  FuriStreamBuffer *rx_stream;
-  uint8_t rx_buf[RX_BUF_SIZE + 1];
-  void (*handle_rx_data_cb)(uint8_t *buf, size_t len, void *context);
+    Evil_PortalApp* app;
+    FuriThread* rx_thread;
+    FuriStreamBuffer* rx_stream;
+    uint8_t rx_buf[RX_BUF_SIZE + 1];
+    void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
 };
 
 typedef enum {
-  WorkerEvtStop = (1 << 0),
-  WorkerEvtRxDone = (1 << 1),
+    WorkerEvtStop = (1 << 0),
+    WorkerEvtRxDone = (1 << 1),
 } WorkerEvtFlags;
 
 void evil_portal_uart_set_handle_rx_data_cb(
-    Evil_PortalUart *uart,
-    void (*handle_rx_data_cb)(uint8_t *buf, size_t len, void *context)) {
-  furi_assert(uart);
-  uart->handle_rx_data_cb = handle_rx_data_cb;
+    Evil_PortalUart* uart,
+    void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)) {
+    furi_assert(uart);
+    uart->handle_rx_data_cb = handle_rx_data_cb;
 }
 
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
 
-void evil_portal_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void *context) {
-  Evil_PortalUart *uart = (Evil_PortalUart *)context;
+void evil_portal_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+    Evil_PortalUart* uart = (Evil_PortalUart*)context;
 
-  if (ev == UartIrqEventRXNE) {
-    furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
-    furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
-  }
+    if(ev == UartIrqEventRXNE) {
+        furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
+        furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+    }
 }
 
-static int32_t uart_worker(void *context) {
-  Evil_PortalUart *uart = (void *)context;
-
-  while (1) {
-
-    uint32_t events = furi_thread_flags_wait(WORKER_ALL_RX_EVENTS,
-                                             FuriFlagWaitAny, FuriWaitForever);
-    furi_check((events & FuriFlagError) == 0);
-    if (events & WorkerEvtStop)
-      break;
-    if (events & WorkerEvtRxDone) {
-      size_t len = furi_stream_buffer_receive(uart->rx_stream, uart->rx_buf,
-                                              RX_BUF_SIZE, 0);
-
-      if (len > 0) {
-        if (uart->handle_rx_data_cb) {
-          uart->handle_rx_data_cb(uart->rx_buf, len, uart->app);
-
-          if (uart->app->has_command_queue) {
-            if (uart->app->command_index < 1) {
-              if (0 ==
-                  strncmp(SET_AP_CMD,
-                          uart->app->command_queue[uart->app->command_index],
-                          strlen(SET_AP_CMD))) {
-                FuriString *out_data = furi_string_alloc();
-
-                furi_string_cat(out_data, "setap=");
-                furi_string_cat(out_data, (char *)uart->app->ap_name);
-
-                evil_portal_uart_tx((uint8_t *)(furi_string_get_cstr(out_data)),
+static int32_t uart_worker(void* context) {
+    Evil_PortalUart* uart = (void*)context;
+
+    while(1) {
+        uint32_t events =
+            furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever);
+        furi_check((events & FuriFlagError) == 0);
+        if(events & WorkerEvtStop) break;
+        if(events & WorkerEvtRxDone) {
+            size_t len = furi_stream_buffer_receive(uart->rx_stream, uart->rx_buf, RX_BUF_SIZE, 0);
+
+            if(len > 0) {
+                if(uart->handle_rx_data_cb) {
+                    uart->handle_rx_data_cb(uart->rx_buf, len, uart->app);
+
+                    if(uart->app->has_command_queue) {
+                        if(uart->app->command_index < 1) {
+                            if(0 == strncmp(
+                                        SET_AP_CMD,
+                                        uart->app->command_queue[uart->app->command_index],
+                                        strlen(SET_AP_CMD))) {
+                                FuriString* out_data = furi_string_alloc();
+
+                                furi_string_cat(out_data, "setap=");
+                                furi_string_cat(out_data, (char*)uart->app->ap_name);
+
+                                evil_portal_uart_tx(
+                                    (uint8_t*)(furi_string_get_cstr(out_data)),
                                     strlen(furi_string_get_cstr(out_data)));
-                evil_portal_uart_tx((uint8_t *)("\n"), 1);
-
-                uart->app->sent_ap = true;
-
-                free(out_data);
-                free(uart->app->ap_name);
-              }
-
-              uart->app->command_index = 0;
-              uart->app->has_command_queue = false;
-              uart->app->command_queue[0] = "";
+                                evil_portal_uart_tx((uint8_t*)("\n"), 1);
+
+                                uart->app->sent_ap = true;
+
+                                free(out_data);
+                                free(uart->app->ap_name);
+                            }
+
+                            uart->app->command_index = 0;
+                            uart->app->has_command_queue = false;
+                            uart->app->command_queue[0] = "";
+                        }
+                    }
+
+                    if(uart->app->sent_reset == false) {
+                        furi_string_cat(uart->app->portal_logs, (char*)uart->rx_buf);
+                    }
+
+                    if(furi_string_utf8_length(uart->app->portal_logs) > 4000) {
+                        write_logs(uart->app->portal_logs);
+                        furi_string_reset(uart->app->portal_logs);
+                    }
+                } else {
+                    uart->rx_buf[len] = '\0';
+                    if(uart->app->sent_reset == false) {
+                        furi_string_cat(uart->app->portal_logs, (char*)uart->rx_buf);
+                    }
+
+                    if(furi_string_utf8_length(uart->app->portal_logs) > 4000) {
+                        write_logs(uart->app->portal_logs);
+                        furi_string_reset(uart->app->portal_logs);
+                    }
+                }
             }
-          }
-
-          if (uart->app->sent_reset == false) {
-            furi_string_cat(uart->app->portal_logs, (char *)uart->rx_buf);
-          }
-
-          if (furi_string_utf8_length(uart->app->portal_logs) > 4000) {
-            write_logs(uart->app->portal_logs);
-            furi_string_reset(uart->app->portal_logs);
-          }
-        } else {          
-          uart->rx_buf[len] = '\0';
-          if (uart->app->sent_reset == false) {
-            furi_string_cat(uart->app->portal_logs, (char *)uart->rx_buf);
-          }
-
-          if (furi_string_utf8_length(uart->app->portal_logs) > 4000) {
-            write_logs(uart->app->portal_logs);
-            furi_string_reset(uart->app->portal_logs);
-          }
         }
-      } 
     }
-  }
 
-  furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL);
-  furi_stream_buffer_free(uart->rx_stream);
+    furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL);
+    furi_stream_buffer_free(uart->rx_stream);
 
-  return 0;
+    return 0;
 }
 
-void evil_portal_uart_tx(uint8_t *data, size_t len) {
-  furi_hal_uart_tx(UART_CH, data, len);
+void evil_portal_uart_tx(uint8_t* data, size_t len) {
+    furi_hal_uart_tx(UART_CH, data, len);
 }
 
-Evil_PortalUart *evil_portal_uart_init(Evil_PortalApp *app) {
-  Evil_PortalUart *uart = malloc(sizeof(Evil_PortalUart));
-  uart->app = app;
-  // Init all rx stream and thread early to avoid crashes
-  uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
-  uart->rx_thread = furi_thread_alloc();
-  furi_thread_set_name(uart->rx_thread, "Evil_PortalUartRxThread");
-  furi_thread_set_stack_size(uart->rx_thread, 1024);
-  furi_thread_set_context(uart->rx_thread, uart);
-  furi_thread_set_callback(uart->rx_thread, uart_worker);
-
-  furi_thread_start(uart->rx_thread);
+Evil_PortalUart* evil_portal_uart_init(Evil_PortalApp* app) {
+    Evil_PortalUart* uart = malloc(sizeof(Evil_PortalUart));
+    uart->app = app;
+    // Init all rx stream and thread early to avoid crashes
+    uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
+    uart->rx_thread = furi_thread_alloc();
+    furi_thread_set_name(uart->rx_thread, "Evil_PortalUartRxThread");
+    furi_thread_set_stack_size(uart->rx_thread, 1024);
+    furi_thread_set_context(uart->rx_thread, uart);
+    furi_thread_set_callback(uart->rx_thread, uart_worker);
+
+    furi_thread_start(uart->rx_thread);
+
+    if(UART_CH == FuriHalUartIdUSART1) {
+        furi_hal_console_disable();
+    } else if(UART_CH == FuriHalUartIdLPUART1) {
+        furi_hal_uart_init(UART_CH, app->BAUDRATE);
+    }
 
-  if(UART_CH == FuriHalUartIdUSART1) {
     furi_hal_console_disable();
-  } else if(UART_CH == FuriHalUartIdLPUART1) {
-    furi_hal_uart_init(UART_CH, app->BAUDRATE);
-  }
-
-  furi_hal_console_disable();
-  if (app->BAUDRATE == 0) {
-    app->BAUDRATE = 115200;
-  }
-  furi_hal_uart_set_br(UART_CH, app->BAUDRATE);
-  furi_hal_uart_set_irq_cb(UART_CH, evil_portal_uart_on_irq_cb, uart);
+    if(app->BAUDRATE == 0) {
+        app->BAUDRATE = 115200;
+    }
+    furi_hal_uart_set_br(UART_CH, app->BAUDRATE);
+    furi_hal_uart_set_irq_cb(UART_CH, evil_portal_uart_on_irq_cb, uart);
 
-  evil_portal_uart_tx((uint8_t*)("XFW#EVILPORTAL=1\n"), strlen("XFW#EVILPORTAL=1\n"));
+    evil_portal_uart_tx((uint8_t*)("XFW#EVILPORTAL=1\n"), strlen("XFW#EVILPORTAL=1\n"));
 
-  return uart;
+    return uart;
 }
 
-void evil_portal_uart_free(Evil_PortalUart *uart) {
-  furi_assert(uart);
+void evil_portal_uart_free(Evil_PortalUart* uart) {
+    furi_assert(uart);
 
-  furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtStop);
-  furi_thread_join(uart->rx_thread);
-  furi_thread_free(uart->rx_thread);
+    furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtStop);
+    furi_thread_join(uart->rx_thread);
+    furi_thread_free(uart->rx_thread);
 
-  if(UART_CH == FuriHalUartIdLPUART1) {
-    furi_hal_uart_deinit(UART_CH);
-  } else {
-    furi_hal_console_enable();
-  }
+    if(UART_CH == FuriHalUartIdLPUART1) {
+        furi_hal_uart_deinit(UART_CH);
+    } else {
+        furi_hal_console_enable();
+    }
 
-  free(uart);
+    free(uart);
 }

+ 5 - 5
evil_portal/evil_portal_uart.h

@@ -7,8 +7,8 @@
 typedef struct Evil_PortalUart Evil_PortalUart;
 
 void evil_portal_uart_set_handle_rx_data_cb(
-    Evil_PortalUart *uart,
-    void (*handle_rx_data_cb)(uint8_t *buf, size_t len, void *context));
-void evil_portal_uart_tx(uint8_t *data, size_t len);
-Evil_PortalUart *evil_portal_uart_init(Evil_PortalApp *app);
-void evil_portal_uart_free(Evil_PortalUart *uart);
+    Evil_PortalUart* uart,
+    void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context));
+void evil_portal_uart_tx(uint8_t* data, size_t len);
+Evil_PortalUart* evil_portal_uart_init(Evil_PortalApp* app);
+void evil_portal_uart_free(Evil_PortalUart* uart);

+ 134 - 136
evil_portal/helpers/evil_portal_storage.c

@@ -1,165 +1,163 @@
 #include "evil_portal_storage.h"
 
-static Storage *evil_portal_open_storage() {
-  return furi_record_open(RECORD_STORAGE);
+static Storage* evil_portal_open_storage() {
+    return furi_record_open(RECORD_STORAGE);
 }
 
-static void evil_portal_close_storage() { furi_record_close(RECORD_STORAGE); }
-
-void evil_portal_read_index_html(void *context) {
-
-  Evil_PortalApp *app = context;
-  Storage *storage = evil_portal_open_storage();
-  FileInfo fi;
-
-  if(!storage_common_exists(storage, EVIL_PORTAL_INDEX_SAVE_PATH)) {
-    FuriString* tmp = furi_string_alloc_set(EVIL_PORTAL_INDEX_DEFAULT_PATH);
-    evil_portal_replace_index_html(tmp);
-    furi_string_free(tmp);
-  }
-
-  if (storage_common_stat(storage, EVIL_PORTAL_INDEX_SAVE_PATH, &fi) ==
-      FSE_OK) {
-    File *index_html = storage_file_alloc(storage);
-    if (storage_file_open(index_html, EVIL_PORTAL_INDEX_SAVE_PATH, FSAM_READ,
-                          FSOM_OPEN_EXISTING)) {
-      app->index_html = malloc((size_t)fi.size);
-      uint8_t *buf_ptr = app->index_html;
-      size_t read = 0;
-      while (read < fi.size) {
-        size_t to_read = fi.size - read;
-        if (to_read > UINT16_MAX)
-          to_read = UINT16_MAX;
-        uint16_t now_read =
-            storage_file_read(index_html, buf_ptr, (uint16_t)to_read);
-        read += now_read;
-        buf_ptr += now_read;
-      }
-      free(buf_ptr);
+static void evil_portal_close_storage() {
+    furi_record_close(RECORD_STORAGE);
+}
+
+void evil_portal_read_index_html(void* context) {
+    Evil_PortalApp* app = context;
+    Storage* storage = evil_portal_open_storage();
+    FileInfo fi;
+
+    if(!storage_common_exists(storage, EVIL_PORTAL_INDEX_SAVE_PATH)) {
+        FuriString* tmp = furi_string_alloc_set(EVIL_PORTAL_INDEX_DEFAULT_PATH);
+        evil_portal_replace_index_html(tmp);
+        furi_string_free(tmp);
+    }
+
+    if(storage_common_stat(storage, EVIL_PORTAL_INDEX_SAVE_PATH, &fi) == FSE_OK) {
+        File* index_html = storage_file_alloc(storage);
+        if(storage_file_open(
+               index_html, EVIL_PORTAL_INDEX_SAVE_PATH, FSAM_READ, FSOM_OPEN_EXISTING)) {
+            app->index_html = malloc((size_t)fi.size);
+            uint8_t* buf_ptr = app->index_html;
+            size_t read = 0;
+            while(read < fi.size) {
+                size_t to_read = fi.size - read;
+                if(to_read > UINT16_MAX) to_read = UINT16_MAX;
+                uint16_t now_read = storage_file_read(index_html, buf_ptr, (uint16_t)to_read);
+                read += now_read;
+                buf_ptr += now_read;
+            }
+            free(buf_ptr);
+        }
+        storage_file_close(index_html);
+        storage_file_free(index_html);
+    } else {
+        char* html_error = "<b>Evil portal</b><br>Unable to read the html file.<br>"
+                           "Is the SD Card set up correctly? <br>See instructions @ "
+                           "github.com/bigbrodude6119/flipper-zero-evil-portal<br>"
+                           "Under the 'Install pre-built app on the flipper' section.";
+        app->index_html = (uint8_t*)html_error;
     }
-    storage_file_close(index_html);
-    storage_file_free(index_html);
-  } else {
-    char *html_error =
-        "<b>Evil portal</b><br>Unable to read the html file.<br>"
-        "Is the SD Card set up correctly? <br>See instructions @ "
-        "github.com/bigbrodude6119/flipper-zero-evil-portal<br>"
-        "Under the 'Install pre-built app on the flipper' section.";
-    app->index_html = (uint8_t *)html_error;
-  }
-
-  evil_portal_close_storage();
+
+    evil_portal_close_storage();
 }
 
 void evil_portal_replace_index_html(FuriString* path) {
-  Storage *storage = evil_portal_open_storage();
-  FS_Error error;
-  error = storage_common_remove(storage, EVIL_PORTAL_INDEX_SAVE_PATH);
-  if(error != FSE_OK) {
-    FURI_LOG_D("EVIL PORTAL", "Error removing file");
-  } else {
-    FURI_LOG_D("EVIL PORTAL", "Error removed file");
-  }
-  error = storage_common_copy(storage, furi_string_get_cstr(path), EVIL_PORTAL_INDEX_SAVE_PATH);
-  if(error != FSE_OK) {
-      FURI_LOG_D("EVIL PORTAL", "Error copying file");
-  }
-  evil_portal_close_storage();
+    Storage* storage = evil_portal_open_storage();
+    FS_Error error;
+    error = storage_common_remove(storage, EVIL_PORTAL_INDEX_SAVE_PATH);
+    if(error != FSE_OK) {
+        FURI_LOG_D("EVIL PORTAL", "Error removing file");
+    } else {
+        FURI_LOG_D("EVIL PORTAL", "Error removed file");
+    }
+    error = storage_common_copy(storage, furi_string_get_cstr(path), EVIL_PORTAL_INDEX_SAVE_PATH);
+    if(error != FSE_OK) {
+        FURI_LOG_D("EVIL PORTAL", "Error copying file");
+    }
+    evil_portal_close_storage();
 }
 
 void evil_portal_create_html_folder_if_not_exists() {
-  Storage *storage = evil_portal_open_storage();
-  if(storage_common_stat(storage, HTML_FOLDER, NULL) == FSE_NOT_EXIST) {
-    FURI_LOG_D("Evil Portal", "Directory %s doesn't exist. Will create new.", HTML_FOLDER);
-    if(!storage_simply_mkdir(storage, HTML_FOLDER)) {
-      FURI_LOG_E("Evil Portal", "Error creating directory %s", HTML_FOLDER);
+    Storage* storage = evil_portal_open_storage();
+    if(storage_common_stat(storage, HTML_FOLDER, NULL) == FSE_NOT_EXIST) {
+        FURI_LOG_D("Evil Portal", "Directory %s doesn't exist. Will create new.", HTML_FOLDER);
+        if(!storage_simply_mkdir(storage, HTML_FOLDER)) {
+            FURI_LOG_E("Evil Portal", "Error creating directory %s", HTML_FOLDER);
+        }
     }
-  }
-  evil_portal_close_storage();
+    evil_portal_close_storage();
 }
 
-void evil_portal_read_ap_name(void *context) {
-  Evil_PortalApp *app = context;
-  Storage *storage = evil_portal_open_storage();
-  FileInfo fi;
-
-  if (storage_common_stat(storage, EVIL_PORTAL_AP_SAVE_PATH, &fi) == FSE_OK) {
-    File *ap_name = storage_file_alloc(storage);
-    if (storage_file_open(ap_name, EVIL_PORTAL_AP_SAVE_PATH, FSAM_READ,
-                          FSOM_OPEN_EXISTING)) {
-      app->ap_name = malloc((size_t)fi.size);
-      uint8_t *buf_ptr = app->ap_name;
-      size_t read = 0;
-      while (read < fi.size) {
-        size_t to_read = fi.size - read;
-        if (to_read > UINT16_MAX)
-          to_read = UINT16_MAX;
-        uint16_t now_read =
-            storage_file_read(ap_name, buf_ptr, (uint16_t)to_read);
-        read += now_read;
-        buf_ptr += now_read;
-      }
-      free(buf_ptr);
+void evil_portal_read_ap_name(void* context) {
+    Evil_PortalApp* app = context;
+    Storage* storage = evil_portal_open_storage();
+    FileInfo fi;
+
+    if(storage_common_stat(storage, EVIL_PORTAL_AP_SAVE_PATH, &fi) == FSE_OK) {
+        File* ap_name = storage_file_alloc(storage);
+        if(storage_file_open(ap_name, EVIL_PORTAL_AP_SAVE_PATH, FSAM_READ, FSOM_OPEN_EXISTING)) {
+            app->ap_name = malloc((size_t)fi.size);
+            uint8_t* buf_ptr = app->ap_name;
+            size_t read = 0;
+            while(read < fi.size) {
+                size_t to_read = fi.size - read;
+                if(to_read > UINT16_MAX) to_read = UINT16_MAX;
+                uint16_t now_read = storage_file_read(ap_name, buf_ptr, (uint16_t)to_read);
+                read += now_read;
+                buf_ptr += now_read;
+            }
+            free(buf_ptr);
+        }
+        storage_file_close(ap_name);
+        storage_file_free(ap_name);
+    } else {
+        char* app_default = "Evil Portal";
+        app->ap_name = (uint8_t*)app_default;
     }
-    storage_file_close(ap_name);
-    storage_file_free(ap_name);
-  } else {
-    char *app_default = "Evil Portal";
-    app->ap_name = (uint8_t *)app_default;
-  }
-  evil_portal_close_storage();
+    evil_portal_close_storage();
 }
 
-void evil_portal_write_ap_name(void *context) {
-  Evil_PortalApp *app = context;
-  Storage *storage = evil_portal_open_storage();
-
-  File *ap_name = storage_file_alloc(storage);
-  if (storage_file_open(ap_name, EVIL_PORTAL_AP_SAVE_PATH, FSAM_WRITE,
-                          FSOM_CREATE_ALWAYS)) {
-      storage_file_write(ap_name, app->text_store[0], strlen(app->text_store[0]));
-  }
-  storage_file_close(ap_name);
-  storage_file_free(ap_name);
-  evil_portal_close_storage();
+void evil_portal_write_ap_name(void* context) {
+    Evil_PortalApp* app = context;
+    Storage* storage = evil_portal_open_storage();
+
+    File* ap_name = storage_file_alloc(storage);
+    if(storage_file_open(ap_name, EVIL_PORTAL_AP_SAVE_PATH, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
+        storage_file_write(ap_name, app->text_store[0], strlen(app->text_store[0]));
+    }
+    storage_file_close(ap_name);
+    storage_file_free(ap_name);
+    evil_portal_close_storage();
 }
 
-char *sequential_file_resolve_path(Storage *storage, const char *dir,
-                                   const char *prefix, const char *extension) {
-  if (storage == NULL || dir == NULL || prefix == NULL || extension == NULL) {
-    return NULL;
-  }
+char* sequential_file_resolve_path(
+    Storage* storage,
+    const char* dir,
+    const char* prefix,
+    const char* extension) {
+    if(storage == NULL || dir == NULL || prefix == NULL || extension == NULL) {
+        return NULL;
+    }
 
-  char file_path[256];
-  int file_index = 0;
+    char file_path[256];
+    int file_index = 0;
 
-  do {
-    if (snprintf(file_path, sizeof(file_path), "%s/%s_%d.%s", dir, prefix,
-                 file_index, extension) < 0) {
-      return NULL;
-    }
-    file_index++;
-  } while (storage_file_exists(storage, file_path));
+    do {
+        if(snprintf(
+               file_path, sizeof(file_path), "%s/%s_%d.%s", dir, prefix, file_index, extension) <
+           0) {
+            return NULL;
+        }
+        file_index++;
+    } while(storage_file_exists(storage, file_path));
 
-  return strdup(file_path);
+    return strdup(file_path);
 }
 
-void write_logs(FuriString *portal_logs) {
-  Storage *storage = evil_portal_open_storage();
+void write_logs(FuriString* portal_logs) {
+    Storage* storage = evil_portal_open_storage();
 
-  if (!storage_file_exists(storage, EVIL_PORTAL_LOG_SAVE_PATH)) {
-    storage_simply_mkdir(storage, EVIL_PORTAL_LOG_SAVE_PATH);
-  }
+    if(!storage_file_exists(storage, EVIL_PORTAL_LOG_SAVE_PATH)) {
+        storage_simply_mkdir(storage, EVIL_PORTAL_LOG_SAVE_PATH);
+    }
 
-  char *seq_file_path = sequential_file_resolve_path(
-      storage, EVIL_PORTAL_LOG_SAVE_PATH, "log", "txt");
+    char* seq_file_path =
+        sequential_file_resolve_path(storage, EVIL_PORTAL_LOG_SAVE_PATH, "log", "txt");
 
-  File *file = storage_file_alloc(storage);
+    File* file = storage_file_alloc(storage);
 
-  if (storage_file_open(file, seq_file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
-    storage_file_write(file, furi_string_get_cstr(portal_logs), furi_string_utf8_length(portal_logs));
-  }
-  storage_file_close(file);
-  storage_file_free(file);
-  evil_portal_close_storage();
+    if(storage_file_open(file, seq_file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
+        storage_file_write(
+            file, furi_string_get_cstr(portal_logs), furi_string_utf8_length(portal_logs));
+    }
+    storage_file_close(file);
+    storage_file_free(file);
+    evil_portal_close_storage();
 }

+ 8 - 5
evil_portal/helpers/evil_portal_storage.h

@@ -13,11 +13,14 @@
 #define EVIL_PORTAL_AP_SAVE_PATH PORTAL_FILE_DIRECTORY_PATH "/ap.config.txt"
 #define EVIL_PORTAL_LOG_SAVE_PATH PORTAL_FILE_DIRECTORY_PATH "/logs"
 
-void evil_portal_read_index_html(void *context);
-void evil_portal_read_ap_name(void *context);
-void evil_portal_write_ap_name(void *context);
+void evil_portal_read_index_html(void* context);
+void evil_portal_read_ap_name(void* context);
+void evil_portal_write_ap_name(void* context);
 void evil_portal_replace_index_html(FuriString* path);
 void evil_portal_create_html_folder_if_not_exists();
 void write_logs(FuriString* portal_logs);
-char *sequential_file_resolve_path(Storage *storage, const char *dir,
-                                   const char *prefix, const char *extension);
+char* sequential_file_resolve_path(
+    Storage* storage,
+    const char* dir,
+    const char* prefix,
+    const char* extension);

+ 3 - 4
evil_portal/scenes/evil_portal_scene.c

@@ -2,22 +2,21 @@
 
 // Generate scene on_enter handlers array
 #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
-void (*const evil_portal_scene_on_enter_handlers[])(void *) = {
+void (*const evil_portal_scene_on_enter_handlers[])(void*) = {
 #include "evil_portal_scene_config.h"
 };
 #undef ADD_SCENE
 
 // Generate scene on_event handlers array
 #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
-bool (*const evil_portal_scene_on_event_handlers[])(void *context,
-                                                    SceneManagerEvent event) = {
+bool (*const evil_portal_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = {
 #include "evil_portal_scene_config.h"
 };
 #undef ADD_SCENE
 
 // Generate scene on_exit handlers array
 #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
-void (*const evil_portal_scene_on_exit_handlers[])(void *context) = {
+void (*const evil_portal_scene_on_exit_handlers[])(void* context) = {
 #include "evil_portal_scene_config.h"
 };
 #undef ADD_SCENE

+ 5 - 7
evil_portal/scenes/evil_portal_scene.h

@@ -6,26 +6,24 @@
 #define ADD_SCENE(prefix, name, id) Evil_PortalScene##id,
 typedef enum {
 #include "evil_portal_scene_config.h"
-  Evil_PortalSceneNum,
+    Evil_PortalSceneNum,
 } Evil_PortalScene;
 #undef ADD_SCENE
 
 extern const SceneManagerHandlers evil_portal_scene_handlers;
 
 // Generate scene on_enter handlers declaration
-#define ADD_SCENE(prefix, name, id)                                            \
-  void prefix##_scene_##name##_on_enter(void *);
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
 #include "evil_portal_scene_config.h"
 #undef ADD_SCENE
 
 // Generate scene on_event handlers declaration
-#define ADD_SCENE(prefix, name, id)                                            \
-  bool prefix##_scene_##name##_on_event(void *context, SceneManagerEvent event);
+#define ADD_SCENE(prefix, name, id) \
+    bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
 #include "evil_portal_scene_config.h"
 #undef ADD_SCENE
 
 // Generate scene on_exit handlers declaration
-#define ADD_SCENE(prefix, name, id)                                            \
-  void prefix##_scene_##name##_on_exit(void *context);
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
 #include "evil_portal_scene_config.h"
 #undef ADD_SCENE

+ 136 - 148
evil_portal/scenes/evil_portal_scene_console_output.c

@@ -1,169 +1,157 @@
 #include "../evil_portal_app_i.h"
 #include "../helpers/evil_portal_storage.h"
 
-void evil_portal_console_output_handle_rx_data_cb(uint8_t *buf, size_t len,
-                                                  void *context) {
-  furi_assert(context);
-  Evil_PortalApp *app = context;
-
-  // If text box store gets too big, then truncate it
-  app->text_box_store_strlen += len;
-  if (app->text_box_store_strlen >= EVIL_PORTAL_TEXT_BOX_STORE_SIZE - 1) {
-    furi_string_right(app->text_box_store, app->text_box_store_strlen / 2);
-    app->text_box_store_strlen = furi_string_size(app->text_box_store) + len;
-  }
-
-  // Null-terminate buf and append to text box store
-  buf[len] = '\0';
-  furi_string_cat_printf(app->text_box_store, "%s", buf);
-
-  view_dispatcher_send_custom_event(app->view_dispatcher,
-                                    Evil_PortalEventRefreshConsoleOutput);
-}
-
-void evil_portal_scene_console_output_on_enter(void *context) {
-  Evil_PortalApp *app = context;
-
-  TextBox *text_box = app->text_box;
-  text_box_reset(app->text_box);
-  text_box_set_font(text_box, TextBoxFontText);
-  if (app->focus_console_start) {
-    text_box_set_focus(text_box, TextBoxFocusStart);
-  } else {
-    text_box_set_focus(text_box, TextBoxFocusEnd);
-  }
-
-  if (app->is_command) {
-    furi_string_reset(app->text_box_store);
-    app->text_box_store_strlen = 0;
-    app->sent_reset = false;
-
-    if (0 == strncmp("help", app->selected_tx_string, strlen("help"))) {
-      const char *help_msg =
-          "BLUE = Waiting\nGREEN = Good\nRED = Bad\n\nThis project is a "
-          "WIP.\ngithub.com/bigbrodude6119/flipper-zero-evil-portal\n\n"
-          "Version 0.0.2\n\n";
-      furi_string_cat_str(app->text_box_store, help_msg);
-      app->text_box_store_strlen += strlen(help_msg);
-      if (app->show_stopscan_tip) {
-        const char *msg = "Press BACK to return\n";
-        furi_string_cat_str(app->text_box_store, msg);
-        app->text_box_store_strlen += strlen(msg);
-      }
+void evil_portal_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) {
+    furi_assert(context);
+    Evil_PortalApp* app = context;
+
+    // If text box store gets too big, then truncate it
+    app->text_box_store_strlen += len;
+    if(app->text_box_store_strlen >= EVIL_PORTAL_TEXT_BOX_STORE_SIZE - 1) {
+        furi_string_right(app->text_box_store, app->text_box_store_strlen / 2);
+        app->text_box_store_strlen = furi_string_size(app->text_box_store) + len;
     }
 
-    if (0 == strncmp("savelogs", app->selected_tx_string, strlen("savelogs"))) {
-      const char *help_msg = "Logs saved.\n\n";
-      furi_string_cat_str(app->text_box_store, help_msg);
-      app->text_box_store_strlen += strlen(help_msg);
-      write_logs(app->portal_logs);
-      furi_string_reset(app->portal_logs);
-      if (app->show_stopscan_tip) {
-        const char *msg = "Press BACK to return\n";
-        furi_string_cat_str(app->text_box_store, msg);
-        app->text_box_store_strlen += strlen(msg);
-      }
-    }
+    // Null-terminate buf and append to text box store
+    buf[len] = '\0';
+    furi_string_cat_printf(app->text_box_store, "%s", buf);
 
-    if (0 == strncmp("setapname", app->selected_tx_string, strlen("setapname"))) {
-      scene_manager_next_scene(app->scene_manager,
-                               Evil_PortalSceneRename);
-      return;
-    }
+    view_dispatcher_send_custom_event(app->view_dispatcher, Evil_PortalEventRefreshConsoleOutput);
+}
 
-    if (0 == strncmp("selecthtml", app->selected_tx_string, strlen("selecthtml"))) {
-      scene_manager_next_scene(app->scene_manager,
-                               Evil_PortalSceneSelectHtml);
-      return;
-    }
+void evil_portal_scene_console_output_on_enter(void* context) {
+    Evil_PortalApp* app = context;
 
-    if (0 ==
-        strncmp(SET_HTML_CMD, app->selected_tx_string, strlen(SET_HTML_CMD))) {
-      app->command_queue[0] = SET_AP_CMD;
-      app->has_command_queue = true;
-      app->command_index = 0;
-      if (app->show_stopscan_tip) {
-        const char *msg =
-            "Starting portal\nIf no response press\nBACK to return\n";
-        furi_string_cat_str(app->text_box_store, msg);
-        app->text_box_store_strlen += strlen(msg);
-      }
+    TextBox* text_box = app->text_box;
+    text_box_reset(app->text_box);
+    text_box_set_font(text_box, TextBoxFontText);
+    if(app->focus_console_start) {
+        text_box_set_focus(text_box, TextBoxFocusStart);
+    } else {
+        text_box_set_focus(text_box, TextBoxFocusEnd);
     }
 
-    if (0 == strncmp(RESET_CMD, app->selected_tx_string, strlen(RESET_CMD))) {
-      app->sent_reset = true;
-      if (app->show_stopscan_tip) {
-        const char *msg = "Reseting portal\nPress BACK to return\n\n\n\n";
-        furi_string_cat_str(app->text_box_store, msg);
-        app->text_box_store_strlen += strlen(msg);
-      }
+    if(app->is_command) {
+        furi_string_reset(app->text_box_store);
+        app->text_box_store_strlen = 0;
+        app->sent_reset = false;
+
+        if(0 == strncmp("help", app->selected_tx_string, strlen("help"))) {
+            const char* help_msg = "BLUE = Waiting\nGREEN = Good\nRED = Bad\n\nThis project is a "
+                                   "WIP.\ngithub.com/bigbrodude6119/flipper-zero-evil-portal\n\n"
+                                   "Version 0.0.2\n\n";
+            furi_string_cat_str(app->text_box_store, help_msg);
+            app->text_box_store_strlen += strlen(help_msg);
+            if(app->show_stopscan_tip) {
+                const char* msg = "Press BACK to return\n";
+                furi_string_cat_str(app->text_box_store, msg);
+                app->text_box_store_strlen += strlen(msg);
+            }
+        }
+
+        if(0 == strncmp("savelogs", app->selected_tx_string, strlen("savelogs"))) {
+            const char* help_msg = "Logs saved.\n\n";
+            furi_string_cat_str(app->text_box_store, help_msg);
+            app->text_box_store_strlen += strlen(help_msg);
+            write_logs(app->portal_logs);
+            furi_string_reset(app->portal_logs);
+            if(app->show_stopscan_tip) {
+                const char* msg = "Press BACK to return\n";
+                furi_string_cat_str(app->text_box_store, msg);
+                app->text_box_store_strlen += strlen(msg);
+            }
+        }
+
+        if(0 == strncmp("setapname", app->selected_tx_string, strlen("setapname"))) {
+            scene_manager_next_scene(app->scene_manager, Evil_PortalSceneRename);
+            return;
+        }
+
+        if(0 == strncmp("selecthtml", app->selected_tx_string, strlen("selecthtml"))) {
+            scene_manager_next_scene(app->scene_manager, Evil_PortalSceneSelectHtml);
+            return;
+        }
+
+        if(0 == strncmp(SET_HTML_CMD, app->selected_tx_string, strlen(SET_HTML_CMD))) {
+            app->command_queue[0] = SET_AP_CMD;
+            app->has_command_queue = true;
+            app->command_index = 0;
+            if(app->show_stopscan_tip) {
+                const char* msg = "Starting portal\nIf no response press\nBACK to return\n";
+                furi_string_cat_str(app->text_box_store, msg);
+                app->text_box_store_strlen += strlen(msg);
+            }
+        }
+
+        if(0 == strncmp(RESET_CMD, app->selected_tx_string, strlen(RESET_CMD))) {
+            app->sent_reset = true;
+            if(app->show_stopscan_tip) {
+                const char* msg = "Reseting portal\nPress BACK to return\n\n\n\n";
+                furi_string_cat_str(app->text_box_store, msg);
+                app->text_box_store_strlen += strlen(msg);
+            }
+        }
     }
-  }
-
-  text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store));
-
-  scene_manager_set_scene_state(app->scene_manager,
-                                Evil_PortalSceneConsoleOutput, 0);
-  view_dispatcher_switch_to_view(app->view_dispatcher,
-                                 Evil_PortalAppViewConsoleOutput);
-
-  // Register callback to receive data
-  evil_portal_uart_set_handle_rx_data_cb(
-      app->uart, evil_portal_console_output_handle_rx_data_cb);
-
-  if (app->is_command && app->selected_tx_string) {
-    if (0 ==
-        strncmp(SET_HTML_CMD, app->selected_tx_string, strlen(SET_HTML_CMD))) {
-      evil_portal_read_index_html(context);
-
-      FuriString *data = furi_string_alloc();
-      furi_string_cat(data, "sethtml=");
-      furi_string_cat(data, (char *)app->index_html);
-
-      evil_portal_uart_tx((uint8_t *)(furi_string_get_cstr(data)),
-                          strlen(furi_string_get_cstr(data)));
-      evil_portal_uart_tx((uint8_t *)("\n"), 1);
-
-      app->sent_html = true;
-
-      free(data);
-      free(app->index_html);
-
-      evil_portal_read_ap_name(context);
-    } else if (0 ==
-               strncmp(RESET_CMD, app->selected_tx_string, strlen(RESET_CMD))) {
-      app->sent_html = false;
-      app->sent_ap = false;
-      evil_portal_uart_tx((uint8_t *)(app->selected_tx_string),
-                          strlen(app->selected_tx_string));
-      evil_portal_uart_tx((uint8_t *)("\n"), 1);
-    } else if (1 == strncmp("help", app->selected_tx_string, strlen("help"))) {
-      evil_portal_uart_tx((uint8_t *)(app->selected_tx_string),
-                          strlen(app->selected_tx_string));
-      evil_portal_uart_tx((uint8_t *)("\n"), 1);
+
+    text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store));
+
+    scene_manager_set_scene_state(app->scene_manager, Evil_PortalSceneConsoleOutput, 0);
+    view_dispatcher_switch_to_view(app->view_dispatcher, Evil_PortalAppViewConsoleOutput);
+
+    // Register callback to receive data
+    evil_portal_uart_set_handle_rx_data_cb(
+        app->uart, evil_portal_console_output_handle_rx_data_cb);
+
+    if(app->is_command && app->selected_tx_string) {
+        if(0 == strncmp(SET_HTML_CMD, app->selected_tx_string, strlen(SET_HTML_CMD))) {
+            evil_portal_read_index_html(context);
+
+            FuriString* data = furi_string_alloc();
+            furi_string_cat(data, "sethtml=");
+            furi_string_cat(data, (char*)app->index_html);
+
+            evil_portal_uart_tx(
+                (uint8_t*)(furi_string_get_cstr(data)), strlen(furi_string_get_cstr(data)));
+            evil_portal_uart_tx((uint8_t*)("\n"), 1);
+
+            app->sent_html = true;
+
+            free(data);
+            free(app->index_html);
+
+            evil_portal_read_ap_name(context);
+        } else if(0 == strncmp(RESET_CMD, app->selected_tx_string, strlen(RESET_CMD))) {
+            app->sent_html = false;
+            app->sent_ap = false;
+            evil_portal_uart_tx(
+                (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
+            evil_portal_uart_tx((uint8_t*)("\n"), 1);
+        } else if(1 == strncmp("help", app->selected_tx_string, strlen("help"))) {
+            evil_portal_uart_tx(
+                (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
+            evil_portal_uart_tx((uint8_t*)("\n"), 1);
+        }
     }
-  }
 }
 
-bool evil_portal_scene_console_output_on_event(void *context,
-                                               SceneManagerEvent event) {
-  Evil_PortalApp *app = context;
+bool evil_portal_scene_console_output_on_event(void* context, SceneManagerEvent event) {
+    Evil_PortalApp* app = context;
 
-  bool consumed = false;
+    bool consumed = false;
 
-  if (event.type == SceneManagerEventTypeCustom) {
-    text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store));
-    consumed = true;
-  } else if (event.type == SceneManagerEventTypeTick) {
-    consumed = true;
-  }
+    if(event.type == SceneManagerEventTypeCustom) {
+        text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store));
+        consumed = true;
+    } else if(event.type == SceneManagerEventTypeTick) {
+        consumed = true;
+    }
 
-  return consumed;
+    return consumed;
 }
 
-void evil_portal_scene_console_output_on_exit(void *context) {
-  Evil_PortalApp *app = context;
+void evil_portal_scene_console_output_on_exit(void* context) {
+    Evil_PortalApp* app = context;
 
-  // Unregister rx callback
-  evil_portal_uart_set_handle_rx_data_cb(app->uart, NULL);
+    // Unregister rx callback
+    evil_portal_uart_set_handle_rx_data_cb(app->uart, NULL);
 }

+ 27 - 28
evil_portal/scenes/evil_portal_scene_rename.c

@@ -7,37 +7,36 @@ void evil_portal_text_input_callback(void* context) {
     view_dispatcher_send_custom_event(app->view_dispatcher, Evil_PortalEventTextInput);
 }
 
-void evil_portal_scene_rename_on_enter(void *context) {
-  Evil_PortalApp *app = context;
-  TextInput* text_input = app->text_input;
-  size_t enter_name_length = 25;
-  evil_portal_read_ap_name(app);
-  text_input_set_header_text(text_input, "AP Name/SSID");
-  strncpy(app->text_store[0], (char *)app->ap_name, enter_name_length);
-  text_input_set_result_callback(
-    text_input,
-    evil_portal_text_input_callback,
-    context,
-    app->text_store[0],
-    enter_name_length,
-    false);
+void evil_portal_scene_rename_on_enter(void* context) {
+    Evil_PortalApp* app = context;
+    TextInput* text_input = app->text_input;
+    size_t enter_name_length = 25;
+    evil_portal_read_ap_name(app);
+    text_input_set_header_text(text_input, "AP Name/SSID");
+    strncpy(app->text_store[0], (char*)app->ap_name, enter_name_length);
+    text_input_set_result_callback(
+        text_input,
+        evil_portal_text_input_callback,
+        context,
+        app->text_store[0],
+        enter_name_length,
+        false);
     view_dispatcher_switch_to_view(app->view_dispatcher, Evil_PortalAppViewTextInput);
 }
 
-bool evil_portal_scene_rename_on_event(void *context, SceneManagerEvent event) {
-  Evil_PortalApp *app = context;
-  SceneManager* scene_manager = app->scene_manager;
-  bool consumed = false;
-  if(event.type == SceneManagerEventTypeCustom) {
-    evil_portal_write_ap_name(app);
-    scene_manager_search_and_switch_to_previous_scene(
-                    scene_manager, Evil_PortalSceneStart);
-    consumed = true;
-  }
-  return consumed;
+bool evil_portal_scene_rename_on_event(void* context, SceneManagerEvent event) {
+    Evil_PortalApp* app = context;
+    SceneManager* scene_manager = app->scene_manager;
+    bool consumed = false;
+    if(event.type == SceneManagerEventTypeCustom) {
+        evil_portal_write_ap_name(app);
+        scene_manager_search_and_switch_to_previous_scene(scene_manager, Evil_PortalSceneStart);
+        consumed = true;
+    }
+    return consumed;
 }
 
-void evil_portal_scene_rename_on_exit(void *context) {
-  Evil_PortalApp *app = context;
-  variable_item_list_reset(app->var_item_list);
+void evil_portal_scene_rename_on_exit(void* context) {
+    Evil_PortalApp* app = context;
+    variable_item_list_reset(app->var_item_list);
 }

+ 36 - 39
evil_portal/scenes/evil_portal_scene_select_html.c

@@ -16,47 +16,44 @@ void evil_portal_show_loading_popup(Evil_PortalApp* app, bool show) {
     }
 }
 
-void evil_portal_scene_select_html_on_enter(void *context) {
-  Evil_PortalApp *app = context;
-  DialogsFileBrowserOptions browser_options;
-  evil_portal_create_html_folder_if_not_exists();
-
-  dialog_file_browser_set_basic_options(&browser_options, HTML_EXTENSION, &I_evil_portal_10px);
-  browser_options.base_path = HTML_FOLDER;
-
-  FuriString* path;
-  path = furi_string_alloc();
-
-  furi_string_set(path, HTML_FOLDER);
-
-
-
-  bool success = dialog_file_browser_show(
-    app->dialogs, app->file_path, path, &browser_options);
-  furi_string_free(path);
-
-  if(success) {
-    //Replace HTML File
-    evil_portal_show_loading_popup(app, true);
-    evil_portal_replace_index_html(app->file_path);
-    evil_portal_show_loading_popup(app, false);
-  }
-  
-  if(success) {
-    scene_manager_search_and_switch_to_previous_scene(
-                    app->scene_manager, Evil_PortalSceneStart);
-  } else {
-    scene_manager_previous_scene(app->scene_manager);
-  }
+void evil_portal_scene_select_html_on_enter(void* context) {
+    Evil_PortalApp* app = context;
+    DialogsFileBrowserOptions browser_options;
+    evil_portal_create_html_folder_if_not_exists();
+
+    dialog_file_browser_set_basic_options(&browser_options, HTML_EXTENSION, &I_evil_portal_10px);
+    browser_options.base_path = HTML_FOLDER;
+
+    FuriString* path;
+    path = furi_string_alloc();
+
+    furi_string_set(path, HTML_FOLDER);
+
+    bool success = dialog_file_browser_show(app->dialogs, app->file_path, path, &browser_options);
+    furi_string_free(path);
+
+    if(success) {
+        //Replace HTML File
+        evil_portal_show_loading_popup(app, true);
+        evil_portal_replace_index_html(app->file_path);
+        evil_portal_show_loading_popup(app, false);
+    }
+
+    if(success) {
+        scene_manager_search_and_switch_to_previous_scene(
+            app->scene_manager, Evil_PortalSceneStart);
+    } else {
+        scene_manager_previous_scene(app->scene_manager);
+    }
 }
 
-bool evil_portal_scene_select_html_on_event(void *context, SceneManagerEvent event) {
-  UNUSED(context);
-  UNUSED(event);
-  bool consumed = true;
-  return consumed;
+bool evil_portal_scene_select_html_on_event(void* context, SceneManagerEvent event) {
+    UNUSED(context);
+    UNUSED(event);
+    bool consumed = true;
+    return consumed;
 }
 
-void evil_portal_scene_select_html_on_exit(void *context) {
-  UNUSED(context);
+void evil_portal_scene_select_html_on_exit(void* context) {
+    UNUSED(context);
 }

+ 92 - 132
evil_portal/scenes/evil_portal_scene_start.c

@@ -5,172 +5,132 @@
 // text box should focus at the start of the output or the end
 typedef enum { NO_ARGS = 0, INPUT_ARGS, TOGGLE_ARGS } InputArgs;
 
-typedef enum {
-  FOCUS_CONSOLE_END = 0,
-  FOCUS_CONSOLE_START,
-  FOCUS_CONSOLE_TOGGLE
-} FocusConsole;
+typedef enum { FOCUS_CONSOLE_END = 0, FOCUS_CONSOLE_START, FOCUS_CONSOLE_TOGGLE } FocusConsole;
 
 #define SHOW_STOPSCAN_TIP (true)
 #define NO_TIP (false)
 
 #define MAX_OPTIONS (9)
 typedef struct {
-  const char *item_string;
-  const char *options_menu[MAX_OPTIONS];
-  int num_options_menu;
-  const char *actual_commands[MAX_OPTIONS];
-  InputArgs needs_keyboard;
-  FocusConsole focus_console;
-  bool show_stopscan_tip;
+    const char* item_string;
+    const char* options_menu[MAX_OPTIONS];
+    int num_options_menu;
+    const char* actual_commands[MAX_OPTIONS];
+    InputArgs needs_keyboard;
+    FocusConsole focus_console;
+    bool show_stopscan_tip;
 } Evil_PortalItem;
 
 // NUM_MENU_ITEMS defined in evil_portal_app_i.h - if you add an entry here,
 // increment it!
 const Evil_PortalItem items[NUM_MENU_ITEMS] = {
     // send command
-    {"Start portal",
-     {""},
-     1,
-     {SET_HTML_CMD},
-     NO_ARGS,
-     FOCUS_CONSOLE_END,
-     SHOW_STOPSCAN_TIP},
+    {"Start portal", {""}, 1, {SET_HTML_CMD}, NO_ARGS, FOCUS_CONSOLE_END, SHOW_STOPSCAN_TIP},
 
     // stop portal
     {"Stop portal", {""}, 1, {RESET_CMD}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
 
     // console
-    {"Save logs",
-     {""},
-     1,
-     {"savelogs"},
-     NO_ARGS,
-     FOCUS_CONSOLE_START,
-     SHOW_STOPSCAN_TIP},
+    {"Save logs", {""}, 1, {"savelogs"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
 
     // set AP name
-    {"Set AP name",
-     {""},
-     1,
-     {"setapname"},
-     NO_ARGS,
-     FOCUS_CONSOLE_START,
-     SHOW_STOPSCAN_TIP},
+    {"Set AP name", {""}, 1, {"setapname"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
 
     // select HTML Portal File
-    {"Select HTML",
-     {""},
-     1,
-     {"selecthtml"},
-     NO_ARGS,
-     FOCUS_CONSOLE_START,
-     SHOW_STOPSCAN_TIP},
+    {"Select HTML", {""}, 1, {"selecthtml"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
 
     // help
-    {"Help",
-     {""},
-     1,
-     {"help"},
-     NO_ARGS,
-     FOCUS_CONSOLE_START,
-     SHOW_STOPSCAN_TIP},
+    {"Help", {""}, 1, {"help"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
 };
 
-static void evil_portal_scene_start_var_list_enter_callback(void *context,
-                                                            uint32_t index) {
-  furi_assert(context);
-  Evil_PortalApp *app = context;
-
-  furi_assert(index < NUM_MENU_ITEMS);
-  const Evil_PortalItem *item = &items[index];
-
-  const int selected_option_index = app->selected_option_index[index];
-  furi_assert(selected_option_index < item->num_options_menu);
-  app->selected_tx_string = item->actual_commands[selected_option_index];
-  app->is_command = true;
-  app->is_custom_tx_string = false;
-  app->selected_menu_index = index;
-  app->focus_console_start = (item->focus_console == FOCUS_CONSOLE_TOGGLE)
-                                 ? (selected_option_index == 0)
-                                 : item->focus_console;
-  app->show_stopscan_tip = item->show_stopscan_tip;
-
-  view_dispatcher_send_custom_event(app->view_dispatcher,
-                                    Evil_PortalEventStartConsole);
+static void evil_portal_scene_start_var_list_enter_callback(void* context, uint32_t index) {
+    furi_assert(context);
+    Evil_PortalApp* app = context;
+
+    furi_assert(index < NUM_MENU_ITEMS);
+    const Evil_PortalItem* item = &items[index];
+
+    const int selected_option_index = app->selected_option_index[index];
+    furi_assert(selected_option_index < item->num_options_menu);
+    app->selected_tx_string = item->actual_commands[selected_option_index];
+    app->is_command = true;
+    app->is_custom_tx_string = false;
+    app->selected_menu_index = index;
+    app->focus_console_start = (item->focus_console == FOCUS_CONSOLE_TOGGLE) ?
+                                   (selected_option_index == 0) :
+                                   item->focus_console;
+    app->show_stopscan_tip = item->show_stopscan_tip;
+
+    view_dispatcher_send_custom_event(app->view_dispatcher, Evil_PortalEventStartConsole);
 }
 
-static void
-evil_portal_scene_start_var_list_change_callback(VariableItem *item) {
-  furi_assert(item);
+static void evil_portal_scene_start_var_list_change_callback(VariableItem* item) {
+    furi_assert(item);
 
-  Evil_PortalApp *app = variable_item_get_context(item);
-  furi_assert(app);
+    Evil_PortalApp* app = variable_item_get_context(item);
+    furi_assert(app);
 
-  const Evil_PortalItem *menu_item = &items[app->selected_menu_index];
-  uint8_t item_index = variable_item_get_current_value_index(item);
-  furi_assert(item_index < menu_item->num_options_menu);
-  variable_item_set_current_value_text(item,
-                                       menu_item->options_menu[item_index]);
-  app->selected_option_index[app->selected_menu_index] = item_index;
+    const Evil_PortalItem* menu_item = &items[app->selected_menu_index];
+    uint8_t item_index = variable_item_get_current_value_index(item);
+    furi_assert(item_index < menu_item->num_options_menu);
+    variable_item_set_current_value_text(item, menu_item->options_menu[item_index]);
+    app->selected_option_index[app->selected_menu_index] = item_index;
 }
 
-void evil_portal_scene_start_on_enter(void *context) {
-  Evil_PortalApp *app = context;
-  VariableItemList *var_item_list = app->var_item_list;
-
-  variable_item_list_set_enter_callback(
-      var_item_list, evil_portal_scene_start_var_list_enter_callback, app);
-
-  VariableItem *item;
-  for (int i = 0; i < NUM_MENU_ITEMS; ++i) {
-    item = variable_item_list_add(
-        var_item_list, items[i].item_string, items[i].num_options_menu,
-        evil_portal_scene_start_var_list_change_callback, app);
-    variable_item_set_current_value_index(item, app->selected_option_index[i]);
-    variable_item_set_current_value_text(
-        item, items[i].options_menu[app->selected_option_index[i]]);
-  }
-
-  variable_item_list_set_selected_item(
-      var_item_list,
-      scene_manager_get_scene_state(app->scene_manager, Evil_PortalSceneStart));
-
-  view_dispatcher_switch_to_view(app->view_dispatcher,
-                                 Evil_PortalAppViewVarItemList);
+void evil_portal_scene_start_on_enter(void* context) {
+    Evil_PortalApp* app = context;
+    VariableItemList* var_item_list = app->var_item_list;
+
+    variable_item_list_set_enter_callback(
+        var_item_list, evil_portal_scene_start_var_list_enter_callback, app);
+
+    VariableItem* item;
+    for(int i = 0; i < NUM_MENU_ITEMS; ++i) {
+        item = variable_item_list_add(
+            var_item_list,
+            items[i].item_string,
+            items[i].num_options_menu,
+            evil_portal_scene_start_var_list_change_callback,
+            app);
+        variable_item_set_current_value_index(item, app->selected_option_index[i]);
+        variable_item_set_current_value_text(
+            item, items[i].options_menu[app->selected_option_index[i]]);
+    }
+
+    variable_item_list_set_selected_item(
+        var_item_list, scene_manager_get_scene_state(app->scene_manager, Evil_PortalSceneStart));
+
+    view_dispatcher_switch_to_view(app->view_dispatcher, Evil_PortalAppViewVarItemList);
 }
 
-bool evil_portal_scene_start_on_event(void *context, SceneManagerEvent event) {
-  UNUSED(context);
-  Evil_PortalApp *app = context;
-  bool consumed = false;
-
-  if (event.type == SceneManagerEventTypeCustom) {
-    if (event.event == Evil_PortalEventStartPortal) {
-      scene_manager_set_scene_state(app->scene_manager, Evil_PortalSceneStart,
-                                    app->selected_menu_index);
-      scene_manager_next_scene(app->scene_manager,
-                               Evil_PortalAppViewStartPortal);
-    } else if (event.event == Evil_PortalEventStartKeyboard) {
-      scene_manager_set_scene_state(app->scene_manager, Evil_PortalSceneStart,
-                                    app->selected_menu_index);
-    } else if (event.event == Evil_PortalEventStartConsole) {
-      scene_manager_set_scene_state(app->scene_manager, Evil_PortalSceneStart,
-                                    app->selected_menu_index);
-      scene_manager_next_scene(app->scene_manager,
-                               Evil_PortalAppViewConsoleOutput);
+bool evil_portal_scene_start_on_event(void* context, SceneManagerEvent event) {
+    UNUSED(context);
+    Evil_PortalApp* app = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == Evil_PortalEventStartPortal) {
+            scene_manager_set_scene_state(
+                app->scene_manager, Evil_PortalSceneStart, app->selected_menu_index);
+            scene_manager_next_scene(app->scene_manager, Evil_PortalAppViewStartPortal);
+        } else if(event.event == Evil_PortalEventStartKeyboard) {
+            scene_manager_set_scene_state(
+                app->scene_manager, Evil_PortalSceneStart, app->selected_menu_index);
+        } else if(event.event == Evil_PortalEventStartConsole) {
+            scene_manager_set_scene_state(
+                app->scene_manager, Evil_PortalSceneStart, app->selected_menu_index);
+            scene_manager_next_scene(app->scene_manager, Evil_PortalAppViewConsoleOutput);
+        }
+        consumed = true;
+    } else if(event.type == SceneManagerEventTypeTick) {
+        app->selected_menu_index = variable_item_list_get_selected_item_index(app->var_item_list);
+        consumed = true;
     }
-    consumed = true;
-  } else if (event.type == SceneManagerEventTypeTick) {
-    app->selected_menu_index =
-        variable_item_list_get_selected_item_index(app->var_item_list);
-    consumed = true;
-  }
-
-  return consumed;
+
+    return consumed;
 }
 
-void evil_portal_scene_start_on_exit(void *context) {
-  Evil_PortalApp *app = context;
-  variable_item_list_reset(app->var_item_list);
+void evil_portal_scene_start_on_exit(void* context) {
+    Evil_PortalApp* app = context;
+    variable_item_list_reset(app->var_item_list);
 }

+ 3 - 3
flipbip/flipbip.c

@@ -102,8 +102,7 @@ static void flipbip_scene_renew_dialog_callback(DialogExResult result, void* con
 static void flipbip_wallet_create(void* context) {
     FlipBip* app = context;
     furi_assert(app);
-    scene_manager_set_scene_state(
-        app->scene_manager, FlipBipSceneMenu, SubmenuIndexScene1New);
+    scene_manager_set_scene_state(app->scene_manager, FlipBipSceneMenu, SubmenuIndexScene1New);
     scene_manager_next_scene(app->scene_manager, FlipBipSceneScene_1);
 }
 
@@ -171,7 +170,8 @@ FlipBip* flipbip_app_alloc() {
     dialog_ex_set_context(app->renew_dialog, app);
     dialog_ex_set_left_button_text(app->renew_dialog, "No");
     dialog_ex_set_right_button_text(app->renew_dialog, "Yes");
-    dialog_ex_set_header(app->renew_dialog, "Current wallet\nWill be lost.\nProceed?", 16, 12, AlignLeft, AlignTop);
+    dialog_ex_set_header(
+        app->renew_dialog, "Current wallet\nWill be lost.\nProceed?", 16, 12, AlignLeft, AlignTop);
     view_dispatcher_add_view(
         app->view_dispatcher, FlipBipViewRenewConfirm, dialog_ex_get_view(app->renew_dialog));
 

+ 1 - 3
flipbip/flipbip.h

@@ -24,8 +24,6 @@
 
 #define TEXT_BUFFER_SIZE 256
 
-
-
 typedef struct {
     Gui* gui;
     // NotificationApp* notification;
@@ -50,7 +48,7 @@ typedef struct {
     char import_mnemonic_text[TEXT_BUFFER_SIZE];
     char input_text[TEXT_BUFFER_SIZE];
 
-    void (* wallet_create)(void* context);
+    void (*wallet_create)(void* context);
 } FlipBip;
 
 typedef enum {

+ 48 - 56
game15/game15.c

@@ -46,10 +46,7 @@ static moving_cell_t moving_cell;
 static uint8_t loaded_saving_ticks;
 static uint8_t popup_menu_selected_item;
 
-static const char* popup_menu_strings[] = {
-    "Continue",
-    "Reset"
-};
+static const char* popup_menu_strings[] = {"Continue", "Reset"};
 
 static uint8_t keys[KEY_STACK_SIZE];
 static uint8_t key_stack_head = 0;
@@ -222,10 +219,8 @@ static bool is_board_solved() {
 static void game_tick() {
     switch(game_state.scene) {
     case ScenePlay:
-        if (game_state.move_count >= 1)
-            game_state.tick_count++;
-        if (loaded_saving_ticks)
-            loaded_saving_ticks--;
+        if(game_state.move_count >= 1) game_state.tick_count++;
+        if(loaded_saving_ticks) loaded_saving_ticks--;
         if(moving_cell.move_direction == DirectionNone && !key_stack_is_empty()) {
             set_moving_cell_by_direction(key_stack_pop());
             if(moving_cell.move_direction == DirectionNone) {
@@ -259,27 +254,25 @@ static void game_tick() {
         break;
 
     case ScenePopup:
-        if (!key_stack_is_empty()) {
-            switch(key_stack_pop())
-            {
-                case DirectionDown:
-                    popup_menu_selected_item++;
-                    popup_menu_selected_item = popup_menu_selected_item % POPUP_MENU_ITEMS;
-                    break;
-                case DirectionUp:
-                    popup_menu_selected_item--;
-                    popup_menu_selected_item = popup_menu_selected_item % POPUP_MENU_ITEMS;
-                    break;
-                case DirectionNone:
-                    if (popup_menu_selected_item == 0) {
-                        game_state.scene = ScenePlay;
-                        notification_message(notification, &sequence_single_vibro);
-                    }
-                    else if (popup_menu_selected_item == 1) {
-                        notification_message(notification, &sequence_single_vibro);
-                        game_init();
-                    }
-                    break;
+        if(!key_stack_is_empty()) {
+            switch(key_stack_pop()) {
+            case DirectionDown:
+                popup_menu_selected_item++;
+                popup_menu_selected_item = popup_menu_selected_item % POPUP_MENU_ITEMS;
+                break;
+            case DirectionUp:
+                popup_menu_selected_item--;
+                popup_menu_selected_item = popup_menu_selected_item % POPUP_MENU_ITEMS;
+                break;
+            case DirectionNone:
+                if(popup_menu_selected_item == 0) {
+                    game_state.scene = ScenePlay;
+                    notification_message(notification, &sequence_single_vibro);
+                } else if(popup_menu_selected_item == 1) {
+                    notification_message(notification, &sequence_single_vibro);
+                    game_init();
+                }
+                break;
             }
         }
         break;
@@ -354,17 +347,19 @@ static void render_callback(Canvas* const canvas) {
     canvas_set_color(canvas, ColorWhite);
     canvas_draw_box(canvas, 0, 0, 128, 64);
 
-    if(game_state.scene == ScenePlay || game_state.scene == SceneWin || game_state.scene == ScenePopup) {
+    if(game_state.scene == ScenePlay || game_state.scene == SceneWin ||
+       game_state.scene == ScenePopup) {
         canvas_set_color(canvas, ColorBlack);
         board_draw(canvas);
         info_draw(canvas);
 
-        if (loaded_saving_ticks && game_state.scene != ScenePopup) {
+        if(loaded_saving_ticks && game_state.scene != ScenePopup) {
             canvas_set_color(canvas, ColorWhite);
             canvas_draw_rbox(canvas, 20, 24, 88, 16, 4);
             canvas_set_color(canvas, ColorBlack);
             canvas_draw_rframe(canvas, 20, 24, 88, 16, 4);
-            canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignCenter, "Restoring game ...");
+            canvas_draw_str_aligned(
+                canvas, 64, 32, AlignCenter, AlignCenter, "Restoring game ...");
         }
     }
 
@@ -377,23 +372,23 @@ static void render_callback(Canvas* const canvas) {
         canvas_draw_box(canvas, 10, 23, 108, 18);
         canvas_set_color(canvas, ColorBlack);
         canvas_draw_xbm(canvas, 14, 27, 100, 10, pic_puzzled);
-    }
-    else if (game_state.scene == ScenePopup) {
-            gray_screen(canvas);
-            canvas_set_color(canvas, ColorWhite);
-            canvas_draw_rbox(canvas, 28, 16, 72, 32, 4);
-            canvas_set_color(canvas, ColorBlack);
-            canvas_draw_rframe(canvas, 28, 16, 72, 32, 4);
+    } else if(game_state.scene == ScenePopup) {
+        gray_screen(canvas);
+        canvas_set_color(canvas, ColorWhite);
+        canvas_draw_rbox(canvas, 28, 16, 72, 32, 4);
+        canvas_set_color(canvas, ColorBlack);
+        canvas_draw_rframe(canvas, 28, 16, 72, 32, 4);
 
-            for(int i=0; i < POPUP_MENU_ITEMS; i++) {
-                if ( i ==  popup_menu_selected_item) {
-                    canvas_set_color(canvas, ColorBlack);
-                    canvas_draw_box(canvas, 34, 20 + 12 * i, 60, 12);
-                }
-                
-                canvas_set_color(canvas, i == popup_menu_selected_item ? ColorWhite : ColorBlack);
-                canvas_draw_str_aligned(canvas, 64, 26 + 12 * i, AlignCenter, AlignCenter, popup_menu_strings[i]);
+        for(int i = 0; i < POPUP_MENU_ITEMS; i++) {
+            if(i == popup_menu_selected_item) {
+                canvas_set_color(canvas, ColorBlack);
+                canvas_draw_box(canvas, 34, 20 + 12 * i, 60, 12);
             }
+
+            canvas_set_color(canvas, i == popup_menu_selected_item ? ColorWhite : ColorBlack);
+            canvas_draw_str_aligned(
+                canvas, 64, 26 + 12 * i, AlignCenter, AlignCenter, popup_menu_strings[i]);
+        }
     }
 }
 
@@ -414,18 +409,16 @@ static void game_event_handler(GameEvent const event) {
                 key_stack_push(DirectionLeft);
                 break;
             case InputKeyOk:
-                if (game_state.scene == ScenePlay) {
+                if(game_state.scene == ScenePlay) {
                     game_state.scene = ScenePopup;
                     key_stack_init();
-                } 
-                else
+                } else
                     key_stack_push(DirectionNone);
                 break;
             case InputKeyBack:
-                if (game_state.scene == ScenePopup) {
+                if(game_state.scene == ScenePopup) {
                     game_state.scene = ScenePlay;
-                }
-                else {
+                } else {
                     storage_game_state_save();
                     sandbox_loop_exit();
                 }
@@ -455,12 +448,11 @@ int32_t game15_app() {
 
     loaded_saving_ticks = 0;
     if(storage_game_state_load()) {
-        if (game_state.scene != ScenePlay) 
+        if(game_state.scene != ScenePlay)
             game_init();
         else
             loaded_saving_ticks = FPS;
-    }
-    else 
+    } else
         game_init();
 
     sandbox_init(

+ 13 - 16
game15/sandbox.c

@@ -13,11 +13,9 @@ SandboxEventHandler sandbox_user_event_handler;
 
 static void sandbox_render_callback(Canvas* const canvas, void* context) {
     UNUSED(context);
-    if (furi_mutex_acquire(sandbox_mutex, 25) != FuriStatusOk)
-        return;
+    if(furi_mutex_acquire(sandbox_mutex, 25) != FuriStatusOk) return;
 
-    if (sandbox_user_render_callback)
-        sandbox_user_render_callback(canvas);
+    if(sandbox_user_render_callback) sandbox_user_render_callback(canvas);
 
     furi_mutex_release(sandbox_mutex);
 }
@@ -28,7 +26,7 @@ static void sandbox_input_callback(InputEvent* input_event, void* context) {
     furi_message_queue_put(sandbox_event_queue, &event, FuriWaitForever);
 }
 
-static void sandbox_timer_callback(void* context ) {
+static void sandbox_timer_callback(void* context) {
     UNUSED(context);
     GameEvent event = {.type = EventTypeTick};
     furi_message_queue_put(sandbox_event_queue, &event, 0);
@@ -36,18 +34,17 @@ static void sandbox_timer_callback(void* context ) {
 
 void sandbox_loop() {
     sandbox_loop_processing = true;
-    while( sandbox_loop_processing ) {
+    while(sandbox_loop_processing) {
         GameEvent event;
         FuriStatus event_status = furi_message_queue_get(sandbox_event_queue, &event, 100);
-        if (event_status != FuriStatusOk) {
+        if(event_status != FuriStatusOk) {
             // timeout
             continue;
         }
 
         furi_mutex_acquire(sandbox_mutex, FuriWaitForever);
 
-        if (sandbox_user_event_handler)
-            sandbox_user_event_handler(event);
+        if(sandbox_user_event_handler) sandbox_user_event_handler(event);
 
         view_port_update(sandbox_view_port);
         furi_mutex_release(sandbox_mutex);
@@ -58,8 +55,10 @@ void sandbox_loop_exit() {
     sandbox_loop_processing = false;
 }
 
-void sandbox_init(uint8_t fps, SandboxRenderCallback u_render_callback, SandboxEventHandler u_event_handler)
-{
+void sandbox_init(
+    uint8_t fps,
+    SandboxRenderCallback u_render_callback,
+    SandboxEventHandler u_event_handler) {
     sandbox_user_render_callback = u_render_callback;
     sandbox_user_event_handler = u_event_handler;
 
@@ -73,17 +72,15 @@ void sandbox_init(uint8_t fps, SandboxRenderCallback u_render_callback, SandboxE
     sandbox_gui = furi_record_open(RECORD_GUI);
     gui_add_view_port(sandbox_gui, sandbox_view_port, GuiLayerFullscreen);
 
-    if (fps > 0) {
+    if(fps > 0) {
         sandbox_timer = furi_timer_alloc(sandbox_timer_callback, FuriTimerTypePeriodic, NULL);
         furi_timer_start(sandbox_timer, furi_kernel_get_tick_frequency() / fps);
     } else
         sandbox_timer = NULL;
 }
 
-void sandbox_free()
-{
-    if (sandbox_timer)    
-        furi_timer_free(sandbox_timer);
+void sandbox_free() {
+    if(sandbox_timer) furi_timer_free(sandbox_timer);
 
     gui_remove_view_port(sandbox_gui, sandbox_view_port);
     view_port_enabled_set(sandbox_view_port, false);

+ 148 - 125
geiger/flipper_geiger.c

@@ -44,8 +44,7 @@ typedef struct {
     uint8_t version;
 } mutexStruct;
 
-static void draw_callback(Canvas* canvas, void* ctx) 
-{
+static void draw_callback(Canvas* canvas, void* ctx) {
     furi_assert(ctx);
 
     mutexStruct* mutexVal = ctx;
@@ -54,68 +53,96 @@ static void draw_callback(Canvas* canvas, void* ctx)
     memcpy(&mutexDraw, mutexVal, sizeof(mutexStruct));
     furi_mutex_release(mutexVal->mutex);
 
-    if (mutexDraw.version == 0)
-    {
+    if(mutexDraw.version == 0) {
         char buffer[32];
-        if (mutexDraw.data == 0) snprintf(buffer, sizeof(buffer), "%ld cps - %ld cpm", mutexDraw.cps, mutexDraw.cpm);
-        else if (mutexDraw.data == 1) snprintf(buffer, sizeof(buffer), "%ld cps - %.2f uSv/h", mutexDraw.cps, ((double)mutexDraw.cpm*(double)CONVERSION_FACTOR));
-        else if (mutexDraw.data == 2) snprintf(buffer, sizeof(buffer), "%ld cps - %.2f mSv/y", mutexDraw.cps, (((double)mutexDraw.cpm*(double)CONVERSION_FACTOR))*(double)8.76);
-        else if (mutexDraw.data == 3) snprintf(buffer, sizeof(buffer), "%ld cps - %.4f Rad/h", mutexDraw.cps, ((double)mutexDraw.cpm*(double)CONVERSION_FACTOR)/(double)10000);
-        else if (mutexDraw.data == 4) snprintf(buffer, sizeof(buffer), "%ld cps - %.2f mR/h", mutexDraw.cps, ((double)mutexDraw.cpm*(double)CONVERSION_FACTOR)/(double)10);
-        else snprintf(buffer, sizeof(buffer), "%ld cps - %.2f uR/h", mutexDraw.cps, ((double)mutexDraw.cpm*(double)CONVERSION_FACTOR)*(double)100);
+        if(mutexDraw.data == 0)
+            snprintf(buffer, sizeof(buffer), "%ld cps - %ld cpm", mutexDraw.cps, mutexDraw.cpm);
+        else if(mutexDraw.data == 1)
+            snprintf(
+                buffer,
+                sizeof(buffer),
+                "%ld cps - %.2f uSv/h",
+                mutexDraw.cps,
+                ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR));
+        else if(mutexDraw.data == 2)
+            snprintf(
+                buffer,
+                sizeof(buffer),
+                "%ld cps - %.2f mSv/y",
+                mutexDraw.cps,
+                (((double)mutexDraw.cpm * (double)CONVERSION_FACTOR)) * (double)8.76);
+        else if(mutexDraw.data == 3)
+            snprintf(
+                buffer,
+                sizeof(buffer),
+                "%ld cps - %.4f Rad/h",
+                mutexDraw.cps,
+                ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) / (double)10000);
+        else if(mutexDraw.data == 4)
+            snprintf(
+                buffer,
+                sizeof(buffer),
+                "%ld cps - %.2f mR/h",
+                mutexDraw.cps,
+                ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) / (double)10);
+        else
+            snprintf(
+                buffer,
+                sizeof(buffer),
+                "%ld cps - %.2f uR/h",
+                mutexDraw.cps,
+                ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) * (double)100);
 
         canvas_set_font(canvas, FontPrimary);
         canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignBottom, buffer);
 
         uint8_t linePosition = mutexDraw.newLinePosition;
 
-        if (mutexDraw.zoom == 0)
-        {
-            for (int i=0;i<SCREEN_SIZE_X;i+=8)
-            {
-                if (linePosition != 0) linePosition--;
-                else linePosition = SCREEN_SIZE_X - 1;
+        if(mutexDraw.zoom == 0) {
+            for(int i = 0; i < SCREEN_SIZE_X; i += 8) {
+                if(linePosition != 0)
+                    linePosition--;
+                else
+                    linePosition = SCREEN_SIZE_X - 1;
 
-                float Y = SCREEN_SIZE_Y-(mutexDraw.line[linePosition]*mutexDraw.coef);
-                for (int j=0;j<8;j++)canvas_draw_line(canvas, i+j, Y, i+j, SCREEN_SIZE_Y);
+                float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef);
+                for(int j = 0; j < 8; j++)
+                    canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y);
             }
-        }
-        else if (mutexDraw.zoom == 1)
-        {
-            for (int i=0;i<SCREEN_SIZE_X;i+=4)
-            {
-                if (linePosition != 0) linePosition--;
-                else linePosition = SCREEN_SIZE_X - 1;
-
-                float Y = SCREEN_SIZE_Y-(mutexDraw.line[linePosition]*mutexDraw.coef);
-                for (int j=0;j<4;j++)canvas_draw_line(canvas, i+j, Y, i+j, SCREEN_SIZE_Y);
+        } else if(mutexDraw.zoom == 1) {
+            for(int i = 0; i < SCREEN_SIZE_X; i += 4) {
+                if(linePosition != 0)
+                    linePosition--;
+                else
+                    linePosition = SCREEN_SIZE_X - 1;
+
+                float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef);
+                for(int j = 0; j < 4; j++)
+                    canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y);
             }
-        }
-        else if (mutexDraw.zoom == 2)
-        {
-            for (int i=0;i<SCREEN_SIZE_X;i+=2)
-            {
-                if (linePosition != 0) linePosition--;
-                else linePosition = SCREEN_SIZE_X - 1;
-
-                float Y = SCREEN_SIZE_Y-(mutexDraw.line[linePosition]*mutexDraw.coef);
-                for (int j=0;j<2;j++)canvas_draw_line(canvas, i+j, Y, i+j, SCREEN_SIZE_Y);
+        } else if(mutexDraw.zoom == 2) {
+            for(int i = 0; i < SCREEN_SIZE_X; i += 2) {
+                if(linePosition != 0)
+                    linePosition--;
+                else
+                    linePosition = SCREEN_SIZE_X - 1;
+
+                float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef);
+                for(int j = 0; j < 2; j++)
+                    canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y);
             }
-        }
-        else if (mutexDraw.zoom == 3)
-        {
-            for (int i=0;i<SCREEN_SIZE_X;i++)
-            {
-                if (linePosition != 0) linePosition--;
-                else linePosition = SCREEN_SIZE_X - 1;
-
-                float Y = SCREEN_SIZE_Y-(mutexDraw.line[linePosition]*mutexDraw.coef);
+        } else if(mutexDraw.zoom == 3) {
+            for(int i = 0; i < SCREEN_SIZE_X; i++) {
+                if(linePosition != 0)
+                    linePosition--;
+                else
+                    linePosition = SCREEN_SIZE_X - 1;
+
+                float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef);
                 canvas_draw_line(canvas, i, Y, i, SCREEN_SIZE_Y);
             }
         }
-    }
-    else
-    {
+    } else {
         canvas_set_font(canvas, FontPrimary);
         canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignBottom, "Geiger Counter");
         canvas_draw_str_aligned(canvas, 64, 20, AlignCenter, AlignBottom, "Version 20230806");
@@ -123,8 +150,7 @@ static void draw_callback(Canvas* canvas, void* ctx)
     }
 }
 
-static void input_callback(InputEvent* input_event, void* ctx) 
-{
+static void input_callback(InputEvent* input_event, void* ctx) {
     furi_assert(ctx);
     FuriMessageQueue* event_queue = ctx;
     EventApp event = {.type = EventTypeInput, .input = *input_event};
@@ -136,7 +162,7 @@ static void clock_tick(void* ctx) {
 
     uint32_t randomNumber = furi_hal_random_get();
     randomNumber &= 0xFFF;
-    if (randomNumber == 0) randomNumber = 1;
+    if(randomNumber == 0) randomNumber = 1;
 
     furi_hal_pwm_set_params(FuriHalPwmOutputIdLptim2PA4, randomNumber, 50);
 
@@ -152,8 +178,7 @@ static void gpiocallback(void* ctx) {
     furi_message_queue_put(queue, &event, 0);
 }
 
-int32_t flipper_geiger_app() 
-{
+int32_t flipper_geiger_app() {
     EventApp event;
     FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(EventApp));
 
@@ -163,7 +188,7 @@ int32_t flipper_geiger_app()
     mutexStruct mutexVal;
     mutexVal.cps = 0;
     mutexVal.cpm = 0;
-    for (int i=0;i<SCREEN_SIZE_X;i++) mutexVal.line[i] = 0;
+    for(int i = 0; i < SCREEN_SIZE_X; i++) mutexVal.line[i] = 0;
     mutexVal.coef = 1;
     mutexVal.data = 0;
     mutexVal.zoom = 2;
@@ -172,7 +197,7 @@ int32_t flipper_geiger_app()
 
     uint32_t counter = 0;
 
-    mutexVal.mutex= furi_mutex_alloc(FuriMutexTypeNormal);
+    mutexVal.mutex = furi_mutex_alloc(FuriMutexTypeNormal);
     if(!mutexVal.mutex) {
         furi_message_queue_free(event_queue);
         return 255;
@@ -207,109 +232,105 @@ int32_t flipper_geiger_app()
 
     NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
 
-    while(1) 
-    {
+    while(1) {
         FuriStatus event_status = furi_message_queue_get(event_queue, &event, FuriWaitForever);
-        
+
         uint8_t screenRefresh = 0;
 
-        if (event_status == FuriStatusOk)
-        {   
-            if(event.type == EventTypeInput) 
-            {
-                if(event.input.key == InputKeyBack && (event.input.type == InputTypeShort || event.input.type == InputTypeLong)) 
-                {
+        if(event_status == FuriStatusOk) {
+            if(event.type == EventTypeInput) {
+                if(event.input.key == InputKeyBack &&
+                   (event.input.type == InputTypeShort || event.input.type == InputTypeLong)) {
                     break;
-                }
-                else if(event.input.key == InputKeyOk && event.input.type == InputTypeLong)
-                {
+                } else if(event.input.key == InputKeyOk && event.input.type == InputTypeLong) {
                     counter = 0;
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
 
                     mutexVal.cps = 0;
                     mutexVal.cpm = 0;
-                    for (uint8_t i=0;i<SCREEN_SIZE_X;i++) mutexVal.line[i] = 0;
+                    for(uint8_t i = 0; i < SCREEN_SIZE_X; i++) mutexVal.line[i] = 0;
                     mutexVal.newLinePosition = 0;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
-                }
-                else if(event.input.key == InputKeyUp && event.input.type == InputTypeLong)
-                {
-                    if (recordData == 0) 
-                    {
+                } else if(event.input.key == InputKeyUp && event.input.type == InputTypeLong) {
+                    if(recordData == 0) {
                         notification_message(notification, &sequence_set_only_red_255);
 
                         FuriHalRtcDateTime datetime;
                         furi_hal_rtc_get_datetime(&datetime);
 
                         char path[64];
-                        snprintf(path, sizeof(path), EXT_PATH("/geiger-%.4d-%.2d-%.2d--%.2d-%.2d-%.2d.csv"), datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second);
-
-                        buffered_file_stream_open(file_stream, path, FSAM_WRITE, FSOM_CREATE_ALWAYS);
+                        snprintf(
+                            path,
+                            sizeof(path),
+                            EXT_PATH("/geiger-%.4d-%.2d-%.2d--%.2d-%.2d-%.2d.csv"),
+                            datetime.year,
+                            datetime.month,
+                            datetime.day,
+                            datetime.hour,
+                            datetime.minute,
+                            datetime.second);
+
+                        buffered_file_stream_open(
+                            file_stream, path, FSAM_WRITE, FSOM_CREATE_ALWAYS);
                         furi_string_printf(dataString, "epoch,cps\n");
                         stream_write_string(file_stream, dataString);
                         epoch = 0;
                         recordData = 1;
-                    }
-                    else
-                    {
+                    } else {
                         buffered_file_stream_close(file_stream);
                         notification_message(notification, &sequence_reset_red);
                         recordData = 0;
                     }
-                }
-                else if((event.input.key == InputKeyLeft && event.input.type == InputTypeShort))
-                {
+                } else if((event.input.key == InputKeyLeft &&
+                           event.input.type == InputTypeShort)) {
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
 
-                    if (mutexVal.data != 0) mutexVal.data--;
-                    else mutexVal.data = 5;
+                    if(mutexVal.data != 0)
+                        mutexVal.data--;
+                    else
+                        mutexVal.data = 5;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
-                }
-                else if((event.input.key == InputKeyRight && event.input.type == InputTypeShort))
-                {
+                } else if((event.input.key == InputKeyRight &&
+                           event.input.type == InputTypeShort)) {
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
 
-                    if (mutexVal.data != 5) mutexVal.data++;
-                    else mutexVal.data = 0;
+                    if(mutexVal.data != 5)
+                        mutexVal.data++;
+                    else
+                        mutexVal.data = 0;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
-                }
-                else if((event.input.key == InputKeyUp && event.input.type == InputTypeShort))
-                {
+                } else if((event.input.key == InputKeyUp && event.input.type == InputTypeShort)) {
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
-                    if (mutexVal.zoom != 0) mutexVal.zoom--;
+                    if(mutexVal.zoom != 0) mutexVal.zoom--;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
 
-                }
-                else if((event.input.key == InputKeyDown && event.input.type == InputTypeShort))
-                {
+                } else if((event.input.key == InputKeyDown &&
+                           event.input.type == InputTypeShort)) {
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
-                    if (mutexVal.zoom != 3) mutexVal.zoom++;
+                    if(mutexVal.zoom != 3) mutexVal.zoom++;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
-                }
-                else if((event.input.key == InputKeyDown && event.input.type == InputTypeLong))
-                {
+                } else if((event.input.key == InputKeyDown && event.input.type == InputTypeLong)) {
                     furi_mutex_acquire(mutexVal.mutex, FuriWaitForever);
-                    if (mutexVal.version == 0) mutexVal.version = 1;
-                    else mutexVal.version = 0;
+                    if(mutexVal.version == 0)
+                        mutexVal.version = 1;
+                    else
+                        mutexVal.version = 0;
 
                     screenRefresh = 1;
                     furi_mutex_release(mutexVal.mutex);
                 }
-            }
-            else if (event.type == ClockEventTypeTick)
-            {
-                if (recordData == 1)
-                {
+            } else if(event.type == ClockEventTypeTick) {
+                if(recordData == 1) {
                     furi_string_printf(dataString, "%lu,%lu\n", epoch++, counter);
                     stream_write_string(file_stream, dataString);
                 }
@@ -324,35 +345,37 @@ int32_t flipper_geiger_app()
                 uint32_t max = mutexVal.line[mutexVal.newLinePosition];
                 uint8_t linePosition = mutexVal.newLinePosition;
 
-                for (int i=1;i<SCREEN_SIZE_X;i++)
-                {
-                    if (linePosition != 0) linePosition--;
-                    else linePosition = SCREEN_SIZE_X - 1;
+                for(int i = 1; i < SCREEN_SIZE_X; i++) {
+                    if(linePosition != 0)
+                        linePosition--;
+                    else
+                        linePosition = SCREEN_SIZE_X - 1;
 
-                    if (i < 60) mutexVal.cpm += mutexVal.line[linePosition];
-                    if (mutexVal.line[linePosition] > max) max = mutexVal.line[linePosition];
+                    if(i < 60) mutexVal.cpm += mutexVal.line[linePosition];
+                    if(mutexVal.line[linePosition] > max) max = mutexVal.line[linePosition];
                 }
 
-                if (max > 0) mutexVal.coef = ((float)(SCREEN_SIZE_Y-15))/((float)max);
-                else mutexVal.coef = 1;
+                if(max > 0)
+                    mutexVal.coef = ((float)(SCREEN_SIZE_Y - 15)) / ((float)max);
+                else
+                    mutexVal.coef = 1;
 
-                if (mutexVal.newLinePosition != SCREEN_SIZE_X - 1) mutexVal.newLinePosition++;
-                else mutexVal.newLinePosition = 0;
+                if(mutexVal.newLinePosition != SCREEN_SIZE_X - 1)
+                    mutexVal.newLinePosition++;
+                else
+                    mutexVal.newLinePosition = 0;
 
                 screenRefresh = 1;
                 furi_mutex_release(mutexVal.mutex);
-            }
-            else if (event.type == EventGPIO)
-            {
+            } else if(event.type == EventGPIO) {
                 counter++;
             }
         }
 
-        if (screenRefresh == 1) view_port_update(view_port);
+        if(screenRefresh == 1) view_port_update(view_port);
     }
 
-    if (recordData == 1) 
-    {
+    if(recordData == 1) {
         buffered_file_stream_close(file_stream);
         notification_message(notification, &sequence_reset_red);
     }

+ 56 - 35
gpio_reader_a/GPIO_reader.c

@@ -20,30 +20,50 @@ typedef struct {
     FuriMutex* mutex;
 } PluginState;
 
-
 static void render_callback(Canvas* const canvas, void* ctx) {
     const PluginState* plugin_state = ctx;
     furi_mutex_acquire(plugin_state->mutex, FuriWaitForever);
-    
+
     canvas_set_font(canvas, FontPrimary);
-    canvas_draw_str_aligned(canvas, canvas_width(canvas) / 2, canvas_height(canvas) / 10, AlignCenter, AlignCenter, "GPIO reader");
+    canvas_draw_str_aligned(
+        canvas,
+        canvas_width(canvas) / 2,
+        canvas_height(canvas) / 10,
+        AlignCenter,
+        AlignCenter,
+        "GPIO reader");
 
     canvas_set_font(canvas, FontSecondary);
-    canvas_draw_str_aligned(canvas, canvas_width(canvas) / 2, canvas_height(canvas) / 10 * 3, AlignCenter, AlignCenter,
-                                gpio_item_get_pin_name(plugin_state->pin));
-
-    canvas_draw_str_aligned(canvas, canvas_width(canvas) / 2, canvas_height(canvas) / 10 * 5, AlignCenter, AlignCenter,
-                                gpio_item_get_pull_mode(plugin_state->pullMode));
+    canvas_draw_str_aligned(
+        canvas,
+        canvas_width(canvas) / 2,
+        canvas_height(canvas) / 10 * 3,
+        AlignCenter,
+        AlignCenter,
+        gpio_item_get_pin_name(plugin_state->pin));
+
+    canvas_draw_str_aligned(
+        canvas,
+        canvas_width(canvas) / 2,
+        canvas_height(canvas) / 10 * 5,
+        AlignCenter,
+        AlignCenter,
+        gpio_item_get_pull_mode(plugin_state->pullMode));
 
     canvas_set_font(canvas, FontPrimary);
-    canvas_draw_str_aligned(canvas, canvas_width(canvas) / 2, canvas_height(canvas) / 10 * 8, AlignCenter, AlignCenter,
-                                gpio_item_get_pin_level(plugin_state->pin));
+    canvas_draw_str_aligned(
+        canvas,
+        canvas_width(canvas) / 2,
+        canvas_height(canvas) / 10 * 8,
+        AlignCenter,
+        AlignCenter,
+        gpio_item_get_pin_level(plugin_state->pin));
 
     furi_mutex_release(plugin_state->mutex);
 }
 
 static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
-    furi_assert(event_queue); 
+    furi_assert(event_queue);
 
     PluginEvent event = {.type = EventTypeKey, .input = *input_event};
     furi_message_queue_put(event_queue, &event, FuriWaitForever);
@@ -53,33 +73,32 @@ static void GPIO_reader_state_init(PluginState* const plugin_state) {
     plugin_state->pin = 0;
     plugin_state->pullMode = 0;
     gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
-} 
+}
 
 int32_t GPIO_reader_app(void* p) {
     UNUSED(p);
     FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
-    
+
     PluginState* plugin_state = malloc(sizeof(PluginState));
     GPIO_reader_state_init(plugin_state);
     plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
     if(!plugin_state->mutex) {
         FURI_LOG_E("GPIO_reader", "cannot create mutex\r\n");
-        free(plugin_state); 
+        free(plugin_state);
         return 255;
     }
 
     // Set system callbacks
-    ViewPort* view_port = view_port_alloc(); 
+    ViewPort* view_port = view_port_alloc();
     view_port_draw_callback_set(view_port, render_callback, plugin_state);
     view_port_input_callback_set(view_port, input_callback, event_queue);
- 
+
     // Open GUI and register view_port
-    Gui* gui = furi_record_open("gui"); 
-    gui_add_view_port(gui, view_port, GuiLayerFullscreen); 
+    Gui* gui = furi_record_open("gui");
+    gui_add_view_port(gui, view_port, GuiLayerFullscreen);
 
-   
-    PluginEvent event; 
-    for(bool processing = true; processing;) { 
+    PluginEvent event;
+    for(bool processing = true; processing;) {
         FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
         furi_mutex_acquire(plugin_state->mutex, FuriWaitForever);
 
@@ -88,30 +107,32 @@ int32_t GPIO_reader_app(void* p) {
             if(event.type == EventTypeKey) {
                 if(event.input.type == InputTypePress || event.input.type == InputTypeRepeat) {
                     switch(event.input.key) {
-                    case InputKeyRight: 
-                            plugin_state->pin = (plugin_state->pin + 1) % GPIO_ITEM_COUNT;
-                            gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
-                        break; 
-                    case InputKeyLeft:  
-                            plugin_state->pin = (plugin_state->pin - 1 + GPIO_ITEM_COUNT) % GPIO_ITEM_COUNT;
-                            gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
-                        break; 
+                    case InputKeyRight:
+                        plugin_state->pin = (plugin_state->pin + 1) % GPIO_ITEM_COUNT;
+                        gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
+                        break;
+                    case InputKeyLeft:
+                        plugin_state->pin =
+                            (plugin_state->pin - 1 + GPIO_ITEM_COUNT) % GPIO_ITEM_COUNT;
+                        gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
+                        break;
                     case InputKeyUp:
-                            plugin_state->pullMode = (plugin_state->pullMode + 1) % GPIO_PULL_COUNT;
-                            gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
+                        plugin_state->pullMode = (plugin_state->pullMode + 1) % GPIO_PULL_COUNT;
+                        gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
                         break;
                     case InputKeyDown:
-                            plugin_state->pullMode = (plugin_state->pullMode - 1 + GPIO_PULL_COUNT) % GPIO_PULL_COUNT;
-                            gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
+                        plugin_state->pullMode =
+                            (plugin_state->pullMode - 1 + GPIO_PULL_COUNT) % GPIO_PULL_COUNT;
+                        gpio_item_configure_pin(plugin_state->pin, plugin_state->pullMode);
                         break;
-                    case InputKeyBack: 
+                    case InputKeyBack:
                         processing = false;
                         break;
                     default:
                         break;
                     }
                 }
-            } 
+            }
             // } else {
             //     FURI_LOG_D("GPIO_reader", "FuriMessageQueue: event timeout");
             // event timeout

+ 4 - 3
gpio_reader_a/GPIO_reader_item.c

@@ -13,14 +13,15 @@ const char* gpio_item_get_pull_mode(uint8_t pull_mode) {
 const char* gpio_item_get_pin_level(uint8_t index) {
     furi_assert(index < GPIO_ITEM_COUNT);
     //furi_hal_gpio_write(gpio_item[index].pin, level);
-    if (furi_hal_gpio_read(gpio_item[index].pin)){
+    if(furi_hal_gpio_read(gpio_item[index].pin)) {
         return "High";
-    }else{
+    } else {
         return "Low";
     }
 }
 
 void gpio_item_configure_pin(uint8_t index, uint8_t pull_mode) {
     furi_assert(index < GPIO_ITEM_COUNT);
-    furi_hal_gpio_init(gpio_item[index].pin, GpioModeInput, gpio_pull_mode[pull_mode].pull, GpioSpeedVeryHigh);
+    furi_hal_gpio_init(
+        gpio_item[index].pin, GpioModeInput, gpio_pull_mode[pull_mode].pull, GpioSpeedVeryHigh);
 }

+ 1 - 1
gpio_reader_a/application.fam

@@ -8,4 +8,4 @@ App(
     fap_category="GPIO",
     fap_icon="icon.png",
     order=1,
-)
+)

+ 1 - 1
gpio_reader_b/gpio_item.c

@@ -26,7 +26,7 @@ void gpio_item_configure_pin(uint8_t index, GpioMode mode, GpioPull pull) {
 
 void gpio_item_configure_all_pins(GpioMode mode) {
     GpioPull pull = GpioPullNo;
-    if(mode == GpioModeInput){
+    if(mode == GpioModeInput) {
         pull = GpioPullDown;
     }
     for(uint8_t i = 0; i < GPIO_ITEM_COUNT; i++) {

+ 1 - 1
gpio_reader_b/scenes/gpio_scene_start.c

@@ -56,7 +56,7 @@ void gpio_scene_start_on_enter(void* context) {
     variable_item_list_add(var_item_list, "USB-UART Bridge", 0, NULL, NULL);
 
     variable_item_list_add(var_item_list, "GPIO Manual Control", 0, NULL, NULL);
-    
+
     variable_item_list_add(var_item_list, "GPIO Manual Read", 0, NULL, NULL);
 
     item = variable_item_list_add(

+ 14 - 18
gpio_reader_b/views/gpio_reader.c

@@ -26,32 +26,25 @@ static void gpio_reader_draw_callback(Canvas* canvas, void* _model) {
     canvas_set_font(canvas, FontSecondary);
     elements_multiline_text_aligned(
         canvas, 64, 16, AlignCenter, AlignTop, "A7  A6  A4  B3  B2  C3  C1  C0");
-    elements_multiline_text_aligned(
-        canvas, 64, 40, AlignCenter, AlignTop, "Pull Up");
+    elements_multiline_text_aligned(canvas, 64, 40, AlignCenter, AlignTop, "Pull Up");
     int charOffset = 10;
     for(uint8_t i = 0; i < GPIO_ITEM_COUNT; i++) {
         bool high = gpio_item_get_pin(i);
         if(high) {
-            elements_multiline_text_aligned(
-                canvas, charOffset, 25, AlignCenter, AlignTop, "1");
+            elements_multiline_text_aligned(canvas, charOffset, 25, AlignCenter, AlignTop, "1");
         } else {
-            elements_multiline_text_aligned(
-                canvas, charOffset, 25, AlignCenter, AlignTop, "0");
+            elements_multiline_text_aligned(canvas, charOffset, 25, AlignCenter, AlignTop, "0");
         }
-        
+
         if(model->pullUp[i]) {
-            elements_multiline_text_aligned(
-                canvas, charOffset, 50, AlignCenter, AlignTop, "1");
+            elements_multiline_text_aligned(canvas, charOffset, 50, AlignCenter, AlignTop, "1");
         } else {
-            elements_multiline_text_aligned(
-                canvas, charOffset, 50, AlignCenter, AlignTop, "0");
+            elements_multiline_text_aligned(canvas, charOffset, 50, AlignCenter, AlignTop, "0");
         }
         if(i == model->pin_idx) {
-            elements_multiline_text_aligned(
-                canvas, charOffset, 53, AlignCenter, AlignTop, "_");
+            elements_multiline_text_aligned(canvas, charOffset, 53, AlignCenter, AlignTop, "_");
         }
 
-        
         charOffset += 16;
     }
     //~ free(charOffset);
@@ -93,7 +86,7 @@ static bool gpio_reader_process_right(GpioReader* gpio_reader) {
         gpio_reader->view,
         GpioReaderModel * model,
         {
-            if(model->pin_idx < GPIO_ITEM_COUNT-1) {
+            if(model->pin_idx < GPIO_ITEM_COUNT - 1) {
                 model->pin_idx++;
             }
         },
@@ -109,11 +102,11 @@ static bool gpio_reader_process_ok(GpioReader* gpio_reader, InputEvent* event) {
         GpioReaderModel * model,
         {
             if(event->type == InputTypePress) {
-                if(model->pullUp[model->pin_idx]){
+                if(model->pullUp[model->pin_idx]) {
                     gpio_item_configure_pin(model->pin_idx, GpioModeInput, GpioPullDown);
                     model->pullUp[model->pin_idx] = 0;
                     consumed = true;
-                }else{
+                } else {
                     gpio_item_configure_pin(model->pin_idx, GpioModeInput, GpioPullUp);
                     model->pullUp[model->pin_idx] = 1;
                     consumed = true;
@@ -149,7 +142,10 @@ View* gpio_reader_get_view(GpioReader* gpio_reader) {
     return gpio_reader->view;
 }
 
-void gpio_reader_set_ok_callback(GpioReader* gpio_reader, GpioReaderOkCallback callback, void* context) {
+void gpio_reader_set_ok_callback(
+    GpioReader* gpio_reader,
+    GpioReaderOkCallback callback,
+    void* context) {
     furi_assert(gpio_reader);
     furi_assert(callback);
     with_view_model(

+ 4 - 1
gpio_reader_b/views/gpio_reader.h

@@ -11,4 +11,7 @@ void gpio_reader_free(GpioReader* gpio_reader);
 
 View* gpio_reader_get_view(GpioReader* gpio_reader);
 
-void gpio_reader_set_ok_callback(GpioReader* gpio_reader, GpioReaderOkCallback callback, void* context);
+void gpio_reader_set_ok_callback(
+    GpioReader* gpio_reader,
+    GpioReaderOkCallback callback,
+    void* context);

+ 0 - 3
hex_editor/hex_editor.c

@@ -46,7 +46,6 @@ static void draw_callback(Canvas* canvas, void* ctx) {
     canvas_set_font(canvas, FontPrimary);
     canvas_draw_str(canvas, 0, 10, "Line and mode:");
 
-
     canvas_set_font(canvas, FontSecondary);
 
     canvas_draw_str_aligned(
@@ -57,7 +56,6 @@ static void draw_callback(Canvas* canvas, void* ctx) {
         AlignBottom,
         furi_string_get_cstr(hex_editor->buffer) + hex_editor->model->string_offset);
 
-
     canvas_draw_icon(canvas, 0, 20, &I_Pin_arrow_up_7x9);
 
     if(hex_editor->model->mode) {
@@ -234,7 +232,6 @@ int32_t hex_editor_app(void* p) {
                         stream_seek_to_char(
                             hex_editor->model->stream, '\n', StreamDirectionBackward);
 
-
                         if(!stream_seek_to_char(
                                hex_editor->model->stream, '\n', StreamDirectionBackward)) {
                             stream_rewind(hex_editor->model->stream);

+ 0 - 1
magspoof/helpers/mag_types.h

@@ -36,7 +36,6 @@ typedef enum {
     MagTxCC1101_868,
 } MagTxState;
 
-
 typedef enum {
     UART_TerminalEventRefreshConsoleOutput = 0,
     UART_TerminalEventStartConsole,

+ 4 - 5
magspoof/mag_device.c

@@ -251,7 +251,7 @@ bool mag_device_parse_card_string(MagDevice* mag_dev, FuriString* f_card_str) {
         return false;
     }
     size_t track1_len = track1_end - track1_start;
-    
+
     FURI_LOG_D(TAG, "Track 1: %.*s", track1_len, track1_start);
 
     mag_dev->dev_data.track[0].len = track1_len;
@@ -259,7 +259,7 @@ bool mag_device_parse_card_string(MagDevice* mag_dev, FuriString* f_card_str) {
 
     // Track 2
     const char* track2_start = strchr(track1_end, ';');
-    if (!track2_start) {
+    if(!track2_start) {
         FURI_LOG_D(TAG, "Could not find track 2 start");
         return true;
     }
@@ -279,7 +279,7 @@ bool mag_device_parse_card_string(MagDevice* mag_dev, FuriString* f_card_str) {
 
     // Track 3
     const char* track3_start = strchr(track2_end, ';');
-    if (!track3_start) {
+    if(!track3_start) {
         FURI_LOG_D(TAG, "Could not find track 3 start");
         return true;
     }
@@ -296,11 +296,10 @@ bool mag_device_parse_card_string(MagDevice* mag_dev, FuriString* f_card_str) {
 
     mag_dev->dev_data.track[2].len = track3_len;
     furi_string_printf(mag_dev->dev_data.track[2].str, "%%%.*s?", track3_len, track3_start);
-    
+
     return true;
 }
 
-
 void mag_device_set_loading_callback(
     MagDevice* mag_dev,
     MagLoadingCallback callback,

+ 1 - 2
magspoof/mag_i.h

@@ -50,7 +50,6 @@ typedef struct {
     uint32_t us_interpacket;
 } MagSetting;
 
-
 typedef struct {
     ViewDispatcher* view_dispatcher;
     Gui* gui;
@@ -80,7 +79,7 @@ typedef struct {
     FuriStreamBuffer* uart_rx_stream;
     uint8_t uart_rx_buf[UART_RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
-    
+
     char uart_text_input_store[UART_TERMINAL_TEXT_INPUT_STORE_SIZE + 1];
     FuriString* uart_text_box_store;
     size_t uart_text_box_store_strlen;

+ 0 - 1
magspoof/scenes/mag_scene_read.h

@@ -17,5 +17,4 @@ typedef enum {
     UARTEventRxData = 100,
 } UARTEvents;
 
-
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)

+ 3 - 3
mass_storage/scenes/mass_storage_scene_start.c

@@ -25,7 +25,8 @@ void mass_storage_scene_start_on_enter(void* context) {
     variable_item_list_set_header(variable_item_list, "USB Mass Storage");
 
     variable_item_list_set_selected_item(
-        variable_item_list, scene_manager_get_scene_state(app->scene_manager, MassStorageSceneStart));
+        variable_item_list,
+        scene_manager_get_scene_state(app->scene_manager, MassStorageSceneStart));
 
     view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewStart);
 }
@@ -38,8 +39,7 @@ bool mass_storage_scene_start_on_event(void* context, SceneManagerEvent event) {
     bool consumed = false;
 
     if(event.type == SceneManagerEventTypeCustom) {
-        scene_manager_set_scene_state(
-            app->scene_manager, MassStorageSceneStart, event.event);
+        scene_manager_set_scene_state(app->scene_manager, MassStorageSceneStart, event.event);
         consumed = true;
         switch(event.event) {
         case VarItemListIndexSelectDiskImage:

+ 45 - 43
mayhem_camera/camera.c

@@ -1,6 +1,5 @@
 #include "camera.h"
 
-
 static void camera_view_draw_callback(Canvas* canvas, void* _model) {
     UartDumpModel* model = _model;
 
@@ -20,15 +19,14 @@ static void camera_view_draw_callback(Canvas* canvas, void* _model) {
         }
     }
 
-    if (!model->initialized){
-    
+    if(!model->initialized) {
         /*if(!model->marauderInitialized)
         {
           // Init marauder into stream mode
           uint8_t data[] = "\nstream\n";
           furi_hal_uart_tx(FuriHalUartIdUSART1, data, sizeof(data));
         }*/
-    
+
         canvas_draw_icon(canvas, 74, 16, &I_DolphinCommon_56x48);
         canvas_set_font(canvas, FontSecondary);
         canvas_draw_str(canvas, 8, 12, "Waiting ESP32-CAM...");
@@ -74,22 +72,26 @@ static void save_image(void* context) {
     get_timefilename(file_name);
 
     // this functions open a file, using write access and creates new file if not exist.
-    bool result = storage_file_open(file, furi_string_get_cstr(file_name), FSAM_WRITE, FSOM_OPEN_ALWAYS);
+    bool result =
+        storage_file_open(file, furi_string_get_cstr(file_name), FSAM_WRITE, FSOM_OPEN_ALWAYS);
     //bool result = storage_file_open(file, EXT_PATH("DCIM/test.bmp"), FSAM_WRITE, FSOM_OPEN_ALWAYS);
     furi_string_free(file_name);
 
-    if (result){
+    if(result) {
         storage_file_write(file, bitmap_header, BITMAP_HEADER_LENGTH);
-        with_view_model(app->view, UartDumpModel * model, {
-            int8_t row_buffer[ROW_BUFFER_LENGTH];
-            for (size_t i = 64; i > 0; --i) {
-                for (size_t j = 0; j < ROW_BUFFER_LENGTH; ++j){
-                    row_buffer[j] = model->pixels[((i-1)*ROW_BUFFER_LENGTH) + j];
+        with_view_model(
+            app->view,
+            UartDumpModel * model,
+            {
+                int8_t row_buffer[ROW_BUFFER_LENGTH];
+                for(size_t i = 64; i > 0; --i) {
+                    for(size_t j = 0; j < ROW_BUFFER_LENGTH; ++j) {
+                        row_buffer[j] = model->pixels[((i - 1) * ROW_BUFFER_LENGTH) + j];
+                    }
+                    storage_file_write(file, row_buffer, ROW_BUFFER_LENGTH);
                 }
-                storage_file_write(file, row_buffer, ROW_BUFFER_LENGTH);
-            }
-            
-        }, false);
+            },
+            false);
     }
 
     // Closing the "file descriptor"
@@ -102,26 +104,22 @@ static void save_image(void* context) {
 }
 
 static bool camera_view_input_callback(InputEvent* event, void* context) {
-    if (event->type == InputTypePress){
+    if(event->type == InputTypePress) {
         uint8_t data[1];
-        if (event->key == InputKeyUp){
+        if(event->key == InputKeyUp) {
             data[0] = 'C';
-        }
-        else if (event->key == InputKeyDown){
+        } else if(event->key == InputKeyDown) {
             data[0] = 'c';
-        }
-        else if (event->key == InputKeyRight){
+        } else if(event->key == InputKeyRight) {
             data[0] = '>';
-        }
-        else if (event->key == InputKeyLeft){
+        } else if(event->key == InputKeyLeft) {
             data[0] = '<';
-        }
-        else if (event->key == InputKeyOk){
+        } else if(event->key == InputKeyOk) {
             save_image(context);
         }
         furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1);
     }
-    
+
     return false;
 }
 
@@ -141,36 +139,39 @@ static void camera_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
 }
 
 static void process_ringbuffer(UartDumpModel* model, uint8_t byte) {
-
     //// 1. Phase: filling the ringbuffer
-    if (model->ringbuffer_index == 0 && byte != 'Y'){ // First char has to be 'Y' in the buffer.
+    if(model->ringbuffer_index == 0 && byte != 'Y') { // First char has to be 'Y' in the buffer.
         return;
     }
-    
-    if (model->ringbuffer_index == 1 && byte != ':'){ // Second char has to be ':' in the buffer or reset.
+
+    if(model->ringbuffer_index == 1 &&
+       byte != ':') { // Second char has to be ':' in the buffer or reset.
         model->ringbuffer_index = 0;
         process_ringbuffer(model, byte);
         return;
     }
 
-    model->row_ringbuffer[model->ringbuffer_index] = byte; // Assign current byte to the ringbuffer;
+    model->row_ringbuffer[model->ringbuffer_index] =
+        byte; // Assign current byte to the ringbuffer;
     ++model->ringbuffer_index; // Increment the ringbuffer index
 
-    if (model->ringbuffer_index < RING_BUFFER_LENGTH){ // Let's wait 'till the buffer fills.
+    if(model->ringbuffer_index < RING_BUFFER_LENGTH) { // Let's wait 'till the buffer fills.
         return;
     }
 
     //// 2. Phase: flushing the ringbuffer to the framebuffer
     model->ringbuffer_index = 0; // Let's reset the ringbuffer
     model->initialized = true; // We've successfully established the connection
-    size_t row_start_index = model->row_ringbuffer[2] * ROW_BUFFER_LENGTH; // Third char will determine the row number
+    size_t row_start_index =
+        model->row_ringbuffer[2] * ROW_BUFFER_LENGTH; // Third char will determine the row number
 
-    if (row_start_index > LAST_ROW_INDEX){ // Failsafe
+    if(row_start_index > LAST_ROW_INDEX) { // Failsafe
         row_start_index = 0;
     }
 
-    for (size_t i = 0; i < ROW_BUFFER_LENGTH; ++i) {
-        model->pixels[row_start_index + i] = model->row_ringbuffer[i+3]; // Writing the remaining 16 bytes into the frame buffer
+    for(size_t i = 0; i < ROW_BUFFER_LENGTH; ++i) {
+        model->pixels[row_start_index + i] =
+            model->row_ringbuffer[i + 3]; // Writing the remaining 16 bytes into the frame buffer
     }
 }
 
@@ -195,7 +196,8 @@ static int32_t camera_worker(void* context) {
                     //furi_hal_uart_tx(FuriHalUartIdUSART1, data, length);
                     with_view_model(
                         app->view,
-                        UartDumpModel * model, {
+                        UartDumpModel * model,
+                        {
                             for(size_t i = 0; i < length; i++) {
                                 process_ringbuffer(model, data[i]);
                             }
@@ -205,7 +207,8 @@ static int32_t camera_worker(void* context) {
             } while(length > 0);
 
             notification_message(app->notification, &sequence_notification);
-            with_view_model(app->view, UartDumpModel * model, { UNUSED(model); }, true);
+            with_view_model(
+                app->view, UartDumpModel * model, { UNUSED(model); }, true);
         }
     }
 
@@ -260,10 +263,9 @@ static UartEchoApp* camera_app_alloc() {
     furi_delay_ms(200);
     furi_hal_power_enable_external_3_3v();
     furi_hal_power_enable_otg();
-    for(int i=0;i<2;i++)
-    {
-        furi_delay_ms(500); 
-        furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'c'}, 1); 
+    for(int i = 0; i < 2; i++) {
+        furi_delay_ms(500);
+        furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'c'}, 1);
     }
     furi_delay_ms(1);
     return app;
@@ -301,7 +303,7 @@ int32_t camera_app(void* p) {
     UartEchoApp* app = camera_app_alloc();
     view_dispatcher_run(app->view_dispatcher);
     camera_app_free(app);
-    
+
     furi_hal_power_disable_otg();
 
     return 0;

+ 29 - 10
mayhem_camera/camera.h

@@ -26,7 +26,8 @@
 #define FRAME_WIDTH 128
 #define FRAME_HEIGTH 64
 #define FRAME_BIT_DEPTH 1
-#define FRAME_BUFFER_LENGTH (FRAME_WIDTH * FRAME_HEIGTH * FRAME_BIT_DEPTH / 8) // 128*64*1 / 8 = 1024
+#define FRAME_BUFFER_LENGTH \
+    (FRAME_WIDTH * FRAME_HEIGTH * FRAME_BIT_DEPTH / 8) // 128*64*1 / 8 = 1024
 #define ROW_BUFFER_LENGTH (FRAME_WIDTH / 8) // 128/8 = 16
 #define LAST_ROW_INDEX (FRAME_BUFFER_LENGTH - ROW_BUFFER_LENGTH) // 1024 - 16 = 1008
 #define RING_BUFFER_LENGTH (ROW_BUFFER_LENGTH + 3) // ROW_BUFFER_LENGTH + Header => 16 + 3 = 19
@@ -34,17 +35,35 @@
 #define IMAGE_FILE_DIRECTORY_PATH EXT_PATH("DCIM")
 
 static const unsigned char bitmap_header[BITMAP_HEADER_LENGTH] = {
-	0x42, 0x4D, 0x3E, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00,
-	0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00,
-	0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
-	0xFF, 0x00
-};
+    0x42, 0x4D, 0x3E, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x28, 0x00,
+    0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00};
 
-const uint8_t _I_DolphinCommon_56x48_0[] = {0x01,0x00,0xdf,0x00,0x00,0x1f,0xfe,0x0e,0x05,0x3f,0x04,0x06,0x78,0x06,0x30,0x20,0xf8,0x00,0xc6,0x12,0x1c,0x04,0x0c,0x0a,0x38,0x08,0x08,0x0c,0x60,0xc0,0x21,0xe0,0x04,0x0a,0x18,0x02,0x1b,0x00,0x18,0xa3,0x00,0x21,0x90,0x01,0x8a,0x20,0x02,0x19,0x80,0x18,0x80,0x64,0x09,0x20,0x89,0x81,0x8c,0x3e,0x41,0xe2,0x80,0x50,0x00,0x43,0x08,0x01,0x0c,0xfc,0x68,0x40,0x61,0xc0,0x50,0x30,0x00,0x63,0xa0,0x7f,0x80,0xc4,0x41,0x19,0x07,0xff,0x02,0x06,0x18,0x24,0x03,0x41,0xf3,0x2b,0x10,0x19,0x38,0x10,0x30,0x31,0x7f,0xe0,0x34,0x08,0x30,0x19,0x60,0x80,0x65,0x86,0x0a,0x4c,0x0c,0x30,0x81,0xb9,0x41,0xa0,0x54,0x08,0xc7,0xe2,0x06,0x8a,0x18,0x25,0x02,0x21,0x0f,0x19,0x88,0xd8,0x6e,0x1b,0x01,0xd1,0x1b,0x86,0x39,0x66,0x3a,0xa4,0x1a,0x50,0x06,0x48,0x18,0x18,0xd0,0x03,0x01,0x41,0x98,0xcc,0x60,0x39,0x01,0x49,0x2d,0x06,0x03,0x50,0xf8,0x40,0x3e,0x02,0xc1,0x82,0x86,0xc7,0xfe,0x0f,0x28,0x2c,0x91,0xd2,0x90,0x9a,0x18,0x19,0x3e,0x6d,0x73,0x12,0x16,0x00,0x32,0x49,0x72,0xc0,0x7e,0x5d,0x44,0xba,0x2c,0x08,0xa4,0xc8,0x82,0x06,0x17,0xe0,0x81,0x90,0x2a,0x40,0x61,0xe1,0xa2,0x44,0x0c,0x76,0x2b,0xe8,0x89,0x26,0x43,0x83,0x31,0x8c,0x78,0x0c,0xb0,0x48,0x10,0x1a,0xe0,0x00,0x63,};
+const uint8_t _I_DolphinCommon_56x48_0[] = {
+    0x01, 0x00, 0xdf, 0x00, 0x00, 0x1f, 0xfe, 0x0e, 0x05, 0x3f, 0x04, 0x06, 0x78, 0x06, 0x30, 0x20,
+    0xf8, 0x00, 0xc6, 0x12, 0x1c, 0x04, 0x0c, 0x0a, 0x38, 0x08, 0x08, 0x0c, 0x60, 0xc0, 0x21, 0xe0,
+    0x04, 0x0a, 0x18, 0x02, 0x1b, 0x00, 0x18, 0xa3, 0x00, 0x21, 0x90, 0x01, 0x8a, 0x20, 0x02, 0x19,
+    0x80, 0x18, 0x80, 0x64, 0x09, 0x20, 0x89, 0x81, 0x8c, 0x3e, 0x41, 0xe2, 0x80, 0x50, 0x00, 0x43,
+    0x08, 0x01, 0x0c, 0xfc, 0x68, 0x40, 0x61, 0xc0, 0x50, 0x30, 0x00, 0x63, 0xa0, 0x7f, 0x80, 0xc4,
+    0x41, 0x19, 0x07, 0xff, 0x02, 0x06, 0x18, 0x24, 0x03, 0x41, 0xf3, 0x2b, 0x10, 0x19, 0x38, 0x10,
+    0x30, 0x31, 0x7f, 0xe0, 0x34, 0x08, 0x30, 0x19, 0x60, 0x80, 0x65, 0x86, 0x0a, 0x4c, 0x0c, 0x30,
+    0x81, 0xb9, 0x41, 0xa0, 0x54, 0x08, 0xc7, 0xe2, 0x06, 0x8a, 0x18, 0x25, 0x02, 0x21, 0x0f, 0x19,
+    0x88, 0xd8, 0x6e, 0x1b, 0x01, 0xd1, 0x1b, 0x86, 0x39, 0x66, 0x3a, 0xa4, 0x1a, 0x50, 0x06, 0x48,
+    0x18, 0x18, 0xd0, 0x03, 0x01, 0x41, 0x98, 0xcc, 0x60, 0x39, 0x01, 0x49, 0x2d, 0x06, 0x03, 0x50,
+    0xf8, 0x40, 0x3e, 0x02, 0xc1, 0x82, 0x86, 0xc7, 0xfe, 0x0f, 0x28, 0x2c, 0x91, 0xd2, 0x90, 0x9a,
+    0x18, 0x19, 0x3e, 0x6d, 0x73, 0x12, 0x16, 0x00, 0x32, 0x49, 0x72, 0xc0, 0x7e, 0x5d, 0x44, 0xba,
+    0x2c, 0x08, 0xa4, 0xc8, 0x82, 0x06, 0x17, 0xe0, 0x81, 0x90, 0x2a, 0x40, 0x61, 0xe1, 0xa2, 0x44,
+    0x0c, 0x76, 0x2b, 0xe8, 0x89, 0x26, 0x43, 0x83, 0x31, 0x8c, 0x78, 0x0c, 0xb0, 0x48, 0x10, 0x1a,
+    0xe0, 0x00, 0x63,
+};
 const uint8_t* const _I_DolphinCommon_56x48[] = {_I_DolphinCommon_56x48_0};
-const Icon I_DolphinCommon_56x48 = {.width=56,.height=48,.frame_count=1,.frame_rate=0,.frames=_I_DolphinCommon_56x48};
+const Icon I_DolphinCommon_56x48 = {
+    .width = 56,
+    .height = 48,
+    .frame_count = 1,
+    .frame_rate = 0,
+    .frames = _I_DolphinCommon_56x48};
 
 typedef struct UartDumpModel UartDumpModel;
 

+ 2 - 2
mayhem_marauder/scenes/wifi_marauder_scene_user_input.c

@@ -132,7 +132,7 @@ void wifi_marauder_scene_user_input_on_enter(void* context) {
         return;
     }
 
-    text_input_set_result_callback(
+    text_input_set_result_callback(
         app->text_input,
         wifi_marauder_scene_user_input_ok_callback,
         app,
@@ -152,5 +152,5 @@ bool wifi_marauder_scene_user_input_on_event(void* context, SceneManagerEvent ev
 void wifi_marauder_scene_user_input_on_exit(void* context) {
     WifiMarauderApp* app = context;
     memset(app->text_input_store, 0, sizeof(app->text_input_store));
-    text_input_reset(app->text_input);
+    text_input_reset(app->text_input);
 }

+ 7 - 8
mayhem_marauder/script/menu/wifi_marauder_script_stage_menu_sniffpmkid.c

@@ -11,7 +11,7 @@ static void wifi_marauder_sniffpmkid_stage_hop_channels_change_callback(Variable
 
     uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list);
     const WifiMarauderScriptMenuItem* menu_item =
-            &app->script_stage_menu->items[current_stage_index];
+        &app->script_stage_menu->items[current_stage_index];
 
     uint8_t option_index = variable_item_get_current_value_index(item);
     variable_item_set_current_value_text(item, menu_item->options[option_index]);
@@ -20,7 +20,6 @@ static void wifi_marauder_sniffpmkid_stage_hop_channels_change_callback(Variable
     stage->hop_channels = option_index;
 }
 
-
 static void wifi_marauder_sniffpmkid_stage_force_deauth_setup_callback(VariableItem* item) {
     WifiMarauderApp* app = variable_item_get_context(item);
     WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage;
@@ -110,10 +109,10 @@ void wifi_marauder_script_stage_menu_sniffpmkid_load(WifiMarauderScriptStageMenu
         .setup_callback = wifi_marauder_sniffpmkid_stage_timeout_setup_callback,
         .select_callback = wifi_marauder_sniffpmkid_stage_timeout_select_callback};
     stage_menu->items[3] = (WifiMarauderScriptMenuItem){
-            .name = strdup("Hop Channels"),
-            .type = WifiMarauderScriptMenuItemTypeOptionsString,
-            .num_options = 2,
-            .options = {"no", "yes"},
-            .setup_callback = wifi_marauder_sniffpmkid_stage_hop_channels_setup_callback,
-            .change_callback = wifi_marauder_sniffpmkid_stage_hop_channels_change_callback};
+        .name = strdup("Hop Channels"),
+        .type = WifiMarauderScriptMenuItemTypeOptionsString,
+        .num_options = 2,
+        .options = {"no", "yes"},
+        .setup_callback = wifi_marauder_sniffpmkid_stage_hop_channels_setup_callback,
+        .change_callback = wifi_marauder_sniffpmkid_stage_hop_channels_change_callback};
 }

+ 5 - 6
mayhem_marauder/script/wifi_marauder_script.c

@@ -247,20 +247,20 @@ WifiMarauderScriptStageSniffPmkid* _wifi_marauder_script_get_stage_sniff_pmkid(c
 
     cJSON* timeout_json = cJSON_GetObjectItem(sniffpmkid_stage_json, "timeout");
     int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) :
-                  WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF;
+                                         WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF;
 
     cJSON* force_deauth_json =
-            cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "forceDeauth");
+        cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "forceDeauth");
     bool force_deauth = cJSON_IsBool(force_deauth_json) ? force_deauth_json->valueint : true;
 
     cJSON* hop_channels_json =
-            cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "hopChannels");
+        cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "hopChannels");
     bool hop_channels = cJSON_IsBool(hop_channels_json) ? hop_channels_json->valueint : false;
 
     WifiMarauderScriptStageSniffPmkid* sniff_pmkid_stage =
-            (WifiMarauderScriptStageSniffPmkid*)malloc(sizeof(WifiMarauderScriptStageSniffPmkid));
+        (WifiMarauderScriptStageSniffPmkid*)malloc(sizeof(WifiMarauderScriptStageSniffPmkid));
 
-    if (sniff_pmkid_stage == NULL) {
+    if(sniff_pmkid_stage == NULL) {
         // Handle memory allocation error
         return NULL;
     }
@@ -272,7 +272,6 @@ WifiMarauderScriptStageSniffPmkid* _wifi_marauder_script_get_stage_sniff_pmkid(c
     return sniff_pmkid_stage;
 }
 
-
 WifiMarauderScriptStageSniffPwn* _wifi_marauder_script_get_stage_sniff_pwn(cJSON* stages) {
     cJSON* sniffpwn_stage_json = cJSON_GetObjectItem(stages, "sniffpwn");
     if(sniffpwn_stage_json == NULL) {

+ 4 - 6
mayhem_marauder/script/wifi_marauder_script_executor.c

@@ -14,7 +14,6 @@ void _send_line_break() {
     wifi_marauder_uart_tx((uint8_t*)("\n"), 1);
 }
 
-
 void _send_channel_select(int channel) {
     char command[30];
     _send_line_break();
@@ -138,9 +137,8 @@ void _wifi_marauder_script_execute_sniff_esp(
 }
 
 void _wifi_marauder_script_execute_sniff_pmkid(
-        WifiMarauderScriptStageSniffPmkid* stage,
-        WifiMarauderScriptWorker* worker) {
-
+    WifiMarauderScriptStageSniffPmkid* stage,
+    WifiMarauderScriptWorker* worker) {
     // If channel hopping is enabled, loop through channels 1-11
     if(stage->hop_channels) {
         for(int i = 1; i <= 11; i++) {
@@ -162,8 +160,8 @@ void _wifi_marauder_script_execute_sniff_pmkid(
         int len = strlen(attack_command);
 
         if(stage->channel > 0) {
-            len +=
-                    snprintf(attack_command + len, sizeof(attack_command) - len, " -c %d", stage->channel);
+            len += snprintf(
+                attack_command + len, sizeof(attack_command) - len, " -c %d", stage->channel);
         }
 
         if(stage->force_deauth) {

+ 0 - 1
mayhem_marauder/script/wifi_marauder_script_worker.c

@@ -1,7 +1,6 @@
 #include "../wifi_marauder_app_i.h"
 #include "wifi_marauder_script_worker.h"
 
-
 WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc() {
     WifiMarauderScriptWorker* worker = malloc(sizeof(WifiMarauderScriptWorker));
     if(worker == NULL) {

+ 3 - 2
mayhem_morseflash/scenes/uart_terminal_scene_console_output.c

@@ -35,8 +35,9 @@ void uart_terminal_scene_console_output_on_enter(void* context) {
         furi_string_reset(app->text_box_store);
         app->text_box_store_strlen = 0;
 
-        // app->show_stopscan_tip in the if is just a hack to get the help displayed since there is no commands in this app 
-        if(app->show_stopscan_tip || 0 == strncmp("help", app->selected_tx_string, strlen("help"))) {
+        // app->show_stopscan_tip in the if is just a hack to get the help displayed since there is no commands in this app
+        if(app->show_stopscan_tip ||
+           0 == strncmp("help", app->selected_tx_string, strlen("help"))) {
             const char* help_msg =
                 "Morse Flasher for\nMayhem Fin\n\nBased on UART terminal by\ncool4uma, which is a\nmodified WiFi Marauder\ncompanion by 0xchocolate\n\n";
             furi_string_cat_str(app->text_box_store, help_msg);

+ 8 - 1
mayhem_morseflash/scenes/uart_terminal_scene_start.c

@@ -27,7 +27,14 @@ const UART_TerminalItem items[NUM_MENU_ITEMS] = {
     {"Quick message",
      {"SOS", "CQD", "VVV", "Eureka", "E.T ph...", "what h...", "Mayhem", "Flipper"},
      8,
-     {"sos", "cqd", "vvv", "eureka", "e.t. phone home", "what hath god wrought!", "let the mayhem begin", "flipper zero in da housa"},
+     {"sos",
+      "cqd",
+      "vvv",
+      "eureka",
+      "e.t. phone home",
+      "what hath god wrought!",
+      "let the mayhem begin",
+      "flipper zero in da housa"},
      NO_ARGS,
      FOCUS_CONSOLE_END,
      NO_TIP},

+ 5 - 6
mayhem_morseflash/uart_terminal_app.c

@@ -90,20 +90,19 @@ void uart_terminal_app_free(UART_TerminalApp* app) {
 
 int32_t uart_terminal_app(void* p) {
     UNUSED(p);
-    
+
     // Enable uart listener
     furi_hal_console_disable();
     furi_hal_uart_set_br(UART_CH, BAUDRATE); // TODO: Clean this
     //furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_echo_on_irq_cb, app);
-  
+
     furi_hal_power_disable_external_3_3v();
     furi_hal_power_disable_otg();
     furi_delay_ms(200);
     furi_hal_power_enable_external_3_3v();
     furi_hal_power_enable_otg();
-    for(int i=0;i<2;i++)
-    {
-        furi_delay_ms(500); 
+    for(int i = 0; i < 2; i++) {
+        furi_delay_ms(500);
         furi_hal_uart_tx(UART_CH, (uint8_t[1]){'.'}, 1);
     }
     furi_delay_ms(1);
@@ -116,6 +115,6 @@ int32_t uart_terminal_app(void* p) {
     uart_terminal_app_free(uart_terminal_app);
 
     furi_hal_power_disable_otg();
-    
+
     return 0;
 }

+ 2 - 2
mayhem_morseflash/uart_terminal_uart.c

@@ -59,7 +59,7 @@ void uart_terminal_uart_tx(uint8_t* data, size_t len) {
 
 UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app) {
     UART_TerminalUart* uart = malloc(sizeof(UART_TerminalUart));
-    
+
     /*furi_hal_console_disable();
     if(app->BAUDRATE == 0) {
         app->BAUDRATE = 230400;
@@ -68,7 +68,7 @@ UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app) {
     furi_hal_uart_set_irq_cb(UART_CH, uart_terminal_uart_on_irq_cb, uart);*/
 
     uart->app = app;
-	uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
+    uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
     uart->rx_thread = furi_thread_alloc();
     furi_thread_set_name(uart->rx_thread, "UART_TerminalUartRxThread");
     furi_thread_set_stack_size(uart->rx_thread, 1024);

+ 3 - 4
mayhem_motion/uart_echo.c

@@ -52,7 +52,7 @@ static void uart_echo_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
 
 static void uart_echo_push_to_list(UartDumpModel* model, void* context, const char data) {
     // Alarm sound
-    if(data == '!'){
+    if(data == '!') {
         UartEchoApp* app = context;
         notification_message(app->notification, &sequence_alarm);
     }
@@ -185,9 +185,8 @@ static UartEchoApp* uart_echo_app_alloc() {
     furi_delay_ms(200);
     furi_hal_power_enable_external_3_3v();
     furi_hal_power_enable_otg();
-    for(int i=0;i<2;i++)
-    {
-        furi_delay_ms(500); 
+    for(int i = 0; i < 2; i++) {
+        furi_delay_ms(500);
         furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'m'}, 1);
     }
     furi_delay_ms(1);

+ 2 - 3
mayhem_nannycam/uart_echo.c

@@ -179,9 +179,8 @@ static UartEchoApp* uart_echo_app_alloc() {
     furi_delay_ms(200);
     furi_hal_power_enable_external_3_3v();
     furi_hal_power_enable_otg();
-    for(int i=0;i<2;i++)
-    {
-        furi_delay_ms(500); 
+    for(int i = 0; i < 2; i++) {
+        furi_delay_ms(500);
         furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'n'}, 1);
     }
     furi_delay_ms(1);

+ 2 - 3
mayhem_qrcode/uart_echo.c

@@ -179,9 +179,8 @@ static UartEchoApp* uart_echo_app_alloc() {
     furi_delay_ms(200);
     furi_hal_power_enable_external_3_3v();
     furi_hal_power_enable_otg();
-    for(int i=0;i<2;i++)
-    {
-        furi_delay_ms(500); 
+    for(int i = 0; i < 2; i++) {
+        furi_delay_ms(500);
         furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'q'}, 1);
     }
     furi_delay_ms(1);

+ 21 - 29
mifare_fuzzer/mifare_fuzzer.c

@@ -1,9 +1,9 @@
 #include "mifare_fuzzer_i.h"
 
 /// @brief mifare_fuzzer_custom_event_callback()
-/// @param context 
-/// @param event 
-/// @return 
+/// @param context
+/// @param event
+/// @return
 static bool mifare_fuzzer_custom_event_callback(void* context, uint32_t event) {
     furi_assert(context);
     MifareFuzzerApp* app = context;
@@ -11,8 +11,8 @@ static bool mifare_fuzzer_custom_event_callback(void* context, uint32_t event) {
 }
 
 /// @brief mifare_fuzzer_back_event_callback()
-/// @param context 
-/// @return 
+/// @param context
+/// @return
 static bool mifare_fuzzer_back_event_callback(void* context) {
     furi_assert(context);
     MifareFuzzerApp* app = context;
@@ -20,15 +20,15 @@ static bool mifare_fuzzer_back_event_callback(void* context) {
 }
 
 /// @brief mifare_fuzzer_tick_event_callback()
-/// @param context 
-static void mifare_fuzzer_tick_event_callback(void* context){
+/// @param context
+static void mifare_fuzzer_tick_event_callback(void* context) {
     furi_assert(context);
     MifareFuzzerApp* app = context;
     scene_manager_handle_tick_event(app->scene_manager);
 }
 
 /// @brief mifare_fuzzer_alloc()
-/// @return 
+/// @return
 MifareFuzzerApp* mifare_fuzzer_alloc() {
     MifareFuzzerApp* app = malloc(sizeof(MifareFuzzerApp));
 
@@ -36,43 +36,35 @@ MifareFuzzerApp* mifare_fuzzer_alloc() {
     app->scene_manager = scene_manager_alloc(&mifare_fuzzer_scene_handlers, app);
     view_dispatcher_enable_queue(app->view_dispatcher);
     view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
-    view_dispatcher_set_custom_event_callback(app->view_dispatcher, mifare_fuzzer_custom_event_callback);
-    view_dispatcher_set_navigation_event_callback(app->view_dispatcher, mifare_fuzzer_back_event_callback);
+    view_dispatcher_set_custom_event_callback(
+        app->view_dispatcher, mifare_fuzzer_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        app->view_dispatcher, mifare_fuzzer_back_event_callback);
 
     // 1000 ticks are about 1 sec
-    view_dispatcher_set_tick_event_callback(app->view_dispatcher, mifare_fuzzer_tick_event_callback, MIFARE_FUZZER_TICK_PERIOD);
+    view_dispatcher_set_tick_event_callback(
+        app->view_dispatcher, mifare_fuzzer_tick_event_callback, MIFARE_FUZZER_TICK_PERIOD);
 
     // Open GUI record
     app->gui = furi_record_open(RECORD_GUI);
-    view_dispatcher_attach_to_gui(
-        app->view_dispatcher,
-        app->gui,
-        ViewDispatcherTypeFullscreen
-    );
+    view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
 
     // view: select card type
     app->submenu_card = submenu_alloc();
     view_dispatcher_add_view(
-        app->view_dispatcher,
-        MifareFuzzerViewSelectCard,
-        submenu_get_view(app->submenu_card)
-    );
+        app->view_dispatcher, MifareFuzzerViewSelectCard, submenu_get_view(app->submenu_card));
 
     // view: select attack type
     app->submenu_attack = submenu_alloc();
     view_dispatcher_add_view(
-        app->view_dispatcher,
-        MifareFuzzerViewSelectAttack,
-        submenu_get_view(app->submenu_attack)
-    );
+        app->view_dispatcher, MifareFuzzerViewSelectAttack, submenu_get_view(app->submenu_attack));
 
     // view: emulator
     app->emulator_view = mifare_fuzzer_emulator_alloc();
     view_dispatcher_add_view(
         app->view_dispatcher,
         MifareFuzzerViewEmulator,
-        mifare_fuzzer_emulator_get_view(app->emulator_view)
-    );
+        mifare_fuzzer_emulator_get_view(app->emulator_view));
 
     // worker
     app->worker = mifare_fuzzer_worker_alloc();
@@ -95,7 +87,7 @@ MifareFuzzerApp* mifare_fuzzer_alloc() {
 }
 
 /// @brief mifare_fuzzer_free()
-/// @param app 
+/// @param app
 void mifare_fuzzer_free(MifareFuzzerApp* app) {
     furi_assert(app);
 
@@ -146,8 +138,8 @@ void mifare_fuzzer_free(MifareFuzzerApp* app) {
 }
 
 /// @brief mifare_fuzzer_app (ENTRYPOINT)
-/// @param p 
-/// @return 
+/// @param p
+/// @return
 int32_t mifare_fuzzer_app(void* p) {
     UNUSED(p);
     //FURI_LOG_D(TAG, "mifare_fuzzer_app()");

+ 0 - 2
mifare_fuzzer/mifare_fuzzer_i.h

@@ -48,7 +48,6 @@ typedef enum {
 } MifareFuzzerView;
 
 struct MifareFuzzerApp {
-
     Gui* gui;
 
     ViewDispatcher* view_dispatcher;
@@ -74,5 +73,4 @@ struct MifareFuzzerApp {
     FuriString* file_path;
     FuriString* uid_str;
     Stream* uids_stream;
-
 };

+ 20 - 24
mifare_fuzzer/mifare_fuzzer_worker.c

@@ -2,17 +2,18 @@
 #include "mifare_fuzzer_worker.h"
 
 /// @brief mifare_fuzzer_worker_alloc()
-/// @return 
+/// @return
 MifareFuzzerWorker* mifare_fuzzer_worker_alloc() {
     MifareFuzzerWorker* mifare_fuzzer_worker = malloc(sizeof(MifareFuzzerWorker));
     // Worker thread attributes
-    mifare_fuzzer_worker->thread = furi_thread_alloc_ex("MifareFuzzerWorker", 8192, mifare_fuzzer_worker_task, mifare_fuzzer_worker);
+    mifare_fuzzer_worker->thread = furi_thread_alloc_ex(
+        "MifareFuzzerWorker", 8192, mifare_fuzzer_worker_task, mifare_fuzzer_worker);
     mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
     return mifare_fuzzer_worker;
 }
 
 /// @brief mifare_fuzzer_worker_free()
-/// @param mifare_fuzzer_worker 
+/// @param mifare_fuzzer_worker
 void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker) {
     furi_assert(mifare_fuzzer_worker);
     furi_thread_free(mifare_fuzzer_worker->thread);
@@ -20,17 +21,17 @@ void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker) {
 }
 
 /// @brief mifare_fuzzer_worker_stop()
-/// @param mifare_fuzzer_worker 
+/// @param mifare_fuzzer_worker
 void mifare_fuzzer_worker_stop(MifareFuzzerWorker* mifare_fuzzer_worker) {
     furi_assert(mifare_fuzzer_worker);
-    if (mifare_fuzzer_worker->state != MifareFuzzerWorkerStateStop) {
+    if(mifare_fuzzer_worker->state != MifareFuzzerWorkerStateStop) {
         mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
         furi_thread_join(mifare_fuzzer_worker->thread);
     }
 }
 
 /// @brief mifare_fuzzer_worker_start()
-/// @param mifare_fuzzer_worker 
+/// @param mifare_fuzzer_worker
 void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker) {
     furi_assert(mifare_fuzzer_worker);
     mifare_fuzzer_worker->state = MifareFuzzerWorkerStateEmulate;
@@ -38,27 +39,20 @@ void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker) {
 }
 
 /// @brief mifare_fuzzer_worker_task()
-/// @param context 
-/// @return 
+/// @param context
+/// @return
 int32_t mifare_fuzzer_worker_task(void* context) {
     MifareFuzzerWorker* mifare_fuzzer_worker = context;
 
     if(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
-
         FuriHalNfcDevData params = mifare_fuzzer_worker->nfc_dev_data;
 
         furi_hal_nfc_exit_sleep();
         while(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
-            furi_hal_nfc_listen(
-                params.uid,
-                params.uid_len,
-                params.atqa,
-                params.sak, false, 500
-            );
+            furi_hal_nfc_listen(params.uid, params.uid_len, params.atqa, params.sak, false, 500);
             furi_delay_ms(50);
         }
         furi_hal_nfc_sleep();
-
     }
 
     mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
@@ -67,25 +61,27 @@ int32_t mifare_fuzzer_worker_task(void* context) {
 }
 
 /// @brief mifare_fuzzer_worker_is_emulating()
-/// @param mifare_fuzzer_worker 
-/// @return 
+/// @param mifare_fuzzer_worker
+/// @return
 bool mifare_fuzzer_worker_is_emulating(MifareFuzzerWorker* mifare_fuzzer_worker) {
-    if (mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
+    if(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
         return true;
     }
     return false;
 }
 
 /// @brief mifare_fuzzer_worker_set_nfc_dev_data()
-/// @param mifare_fuzzer_worker 
-/// @param nfc_dev_data 
-void mifare_fuzzer_worker_set_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker, FuriHalNfcDevData nfc_dev_data) {
+/// @param mifare_fuzzer_worker
+/// @param nfc_dev_data
+void mifare_fuzzer_worker_set_nfc_dev_data(
+    MifareFuzzerWorker* mifare_fuzzer_worker,
+    FuriHalNfcDevData nfc_dev_data) {
     mifare_fuzzer_worker->nfc_dev_data = nfc_dev_data;
 }
 
 /// @brief mifare_fuzzer_worker_get_nfc_dev_data()
-/// @param mifare_fuzzer_worker 
-/// @return 
+/// @param mifare_fuzzer_worker
+/// @return
 FuriHalNfcDevData mifare_fuzzer_worker_get_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker) {
     return mifare_fuzzer_worker->nfc_dev_data;
 }

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor