Dataset Viewer
Search is not available for this dataset
sample_type
stringclasses 3
values | node_type
stringclasses 6
values | file_path
stringlengths 13
93
| prefix
stringlengths 0
4.1k
| suffix
stringlengths 0
4.1k
| middle
stringlengths 1
1.6k
| text
stringlengths 131
8.36k
|
---|---|---|---|---|---|---|
masked_node | if_statement | src/fw/util/mbuf_iterator.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbuf_iterator.h"
bool prv_iter_to_valid_mbuf(MBufIterator *iter) {
// advance the iterator to the next MBuf with data
while ((iter->m != NULL) && (mbuf_get_length(iter->m) == 0)) {
iter->m = mbuf_get_next(iter->m);
iter->data_index = 0;
}
return iter->m != NULL;
}
void mbuf_iterator_init(MBufIterator *iter, MBuf *m) {
iter->m = m;
iter->data_index = 0;
prv_iter_to_valid_mbuf(iter);
}
bool mbuf_iterator_is_finished(MBufIterator *iter) {
if (!prv_iter_to_valid_mbuf(iter)) {
return true;
}
if (iter->data_index >= mbuf_get_length(iter->m)) {
// we're at the end of this MBuf so move to the next one
iter->m = mbuf_get_next(iter->m);
iter->data_index = 0;
// make sure this MBuf has data
if (!prv_iter_to_valid_mbuf(iter)) {
return true;
}
}
return false;
}
bool mbuf_iterator_read_byte(MBufIterator *iter, uint8_t *data) {
|
uint8_t *buffer = mbuf_get_data(iter->m);
*data = buffer[iter->data_index++];
return true;
}
bool mbuf_iterator_write_byte(MBufIterator *iter, uint8_t data) {
if (mbuf_iterator_is_finished(iter)) {
return false;
}
uint8_t *buffer = mbuf_get_data(iter->m);
buffer[iter->data_index++] = data;
return true;
}
MBuf *mbuf_iterator_get_current_mbuf(MBufIterator *iter) {
return iter->m;
}
| if (mbuf_iterator_is_finished(iter)) {
return false;
} | <|repo_name|>pebble
<|file_sep|>src/fw/util/mbuf_iterator.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbuf_iterator.h"
bool prv_iter_to_valid_mbuf(MBufIterator *iter) {
// advance the iterator to the next MBuf with data
while ((iter->m != NULL) && (mbuf_get_length(iter->m) == 0)) {
iter->m = mbuf_get_next(iter->m);
iter->data_index = 0;
}
return iter->m != NULL;
}
void mbuf_iterator_init(MBufIterator *iter, MBuf *m) {
iter->m = m;
iter->data_index = 0;
prv_iter_to_valid_mbuf(iter);
}
bool mbuf_iterator_is_finished(MBufIterator *iter) {
if (!prv_iter_to_valid_mbuf(iter)) {
return true;
}
if (iter->data_index >= mbuf_get_length(iter->m)) {
// we're at the end of this MBuf so move to the next one
iter->m = mbuf_get_next(iter->m);
iter->data_index = 0;
// make sure this MBuf has data
if (!prv_iter_to_valid_mbuf(iter)) {
return true;
}
}
return false;
}
bool mbuf_iterator_read_byte(MBufIterator *iter, uint8_t *data) {
<|fim_suffix|>
uint8_t *buffer = mbuf_get_data(iter->m);
*data = buffer[iter->data_index++];
return true;
}
bool mbuf_iterator_write_byte(MBufIterator *iter, uint8_t data) {
if (mbuf_iterator_is_finished(iter)) {
return false;
}
uint8_t *buffer = mbuf_get_data(iter->m);
buffer[iter->data_index++] = data;
return true;
}
MBuf *mbuf_iterator_get_current_mbuf(MBufIterator *iter) {
return iter->m;
}
<|fim_middle|>if (mbuf_iterator_is_finished(iter)) {
return false;
}<|endoftext|> |
masked_node | compound_statement | src/fw/process_management/app_menu_data_source.c | kLaunch);
const int override_cmp_rv = prv_app_override_comparator(app_node->install_id,
new_node->install_id);
if (is_app_quick_launch != is_new_quick_launch) {
// Quick Launch only apps are first
return (is_app_quick_launch ? 1 : 0) - (is_new_quick_launch ? 1 : 0);
} else if (override_cmp_rv) {
// Apps that override storage, record, and install order
return (override_cmp_rv);
} else if (app_node->storage_order != new_node->storage_order) {
// Storage order (smallest first)
return prv_comparator_ascending_zero_last(app_node->storage_order, new_node->storage_order);
} else if (app_node->record_order != new_node->record_order) {
// Record order (smallest first)
return prv_comparator_ascending_zero_last(app_node->record_order, new_node->record_order);
} else {
// AppInstallId (smallest first)
return new_node->install_id - app_node->install_id;
}
}
static void prv_set_storage_order(AppMenuDataSource *source, AppMenuNode *menu_node,
AppMenuOrderStorage *storage, bool update_and_take_ownership) {
if (!storage) {
return;
}
for (int i = 0; i < storage->list_length; i++) {
const AppInstallId storage_app_id = storage->id_list[i];
if (storage_app_id == INSTALL_ID_INVALID) {
continue;
}
const AppMenuStorageOrder new_storage_order =
(AppMenuStorageOrder)i + AppMenuStorageOrderGeneralOrderOffset;
if (menu_node && (menu_node->install_id == storage_app_id)) {
menu_node->storage_order = new_storage_order;
if (!update_and_take_ownership) {
break;
} else {
continue;
}
}
if (update_and_take_ownership) {
AppMenuNode *other_node = prv_find_node_with_install_id(storage_app_id, source);
if (other_node) {
other_node->storage_order = new_storage_order;
}
}
}
if (update_and_take_ownership) {
app_free(storage);
}
}
static void prv_sorted_add(AppMenuDataSource *source, AppMenuNode *menu_node) {
// Update the entire list order only if we've just read the order in this context. If we haven't
// just read the order, then we're building a list starting from an empty list, so just set the
// order for the new node.
prv_set_storage_order(source, menu_node, source->order_storage ?: app_order_read_order(),
(source->order_storage == NULL));
// If we're adding the Settings app node to the list and it hasn't received a storage order,
// then give it its default order
if ((menu_node->install_id == APP_ID_SETTINGS) &&
(menu_node->storage_order == AppMenuStorageOrder_NoOrder)) {
menu_node->storage_order = AppMenuStorageOrder_SettingsDefaultOrder;
}
source->list = (AppMenuNode *)list_sorted_add(&source->list->node, &menu_node->node,
prv_app_node_comparator, true /* ascending */);
}
////////////////////////////////
// AppInstallManager Callbacks
////////////////////////////////
typedef struct InstallData {
AppInstallId id;
AppMenuDataSource *source;
InstallEventType event_type;
} InstallData;
void prv_alert_data_source_changed(AppMenuDataSource *data_source) {
if (data_source->callbacks.changed) {
data_source->callbacks.changed(data_source->callback_context);
}
}
static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_db_cleared(AppMenuDataSource *source);
void prv_handle_app_event(void *data) {
InstallData *install_data = data;
AppMenuDataSource *source = install_data->source;
AppInstallId install_id = install_data->id;
switch (install_data->event_type) |
kernel_free(install_data);
}
void prv_send_callback_to_app(AppMenuDataSource *data_source, AppInstallId install_id,
InstallEventType event_type) {
InstallData *install_data = kernel_malloc_check(sizeof(InstallData));
*install_data = (InstallData) {
.id = install_id,
.source = data_source,
.event_type = event_type,
};
process_manager_send_callback_event_to_process(PebbleTask_App,
prv_handle_app_event,
install_data);
}
//! Must be run from the app task
static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id) {
AppInstallEntry entry;
if (!app_install_get_entry_for_install_id(install_id, &entry) ||
prv_is_app_filtered_out(&entry, source)) {
return;
}
add_app_with_install_id(&entry, source);
prv_alert_data_source_changed(source);
}
//! Called when an application is installed
static void prv_app_added_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_AVAILABLE);
}
//! Must be run from the app task
static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id) {
// Don't filter, just always try removing from the list:
const bool is_removed = remove_app_with_install_id(install_id, source);
if (is_removed) {
prv_alert_data_source_changed(source);
}
}
//! Called when an application is uninstalled
static void prv_app_removed_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_REMOVED);
}
//! Must be run from the app task
static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id) {
AppInstallEntry entry;
if (!app_install_get_entry_for_install_id(install_id, &entry)) {
return;
}
AppMenuNode *node = prv_find_node_with_install_id(install_id, source);
if (prv_is_app_filtered_out(&entry, source)) {
if (node == NULL) {
// Changed and still excluded:
return;
}
// Changed and is now excluded:
prv_unload_node(source, node);
} else {
// Changed and is now included:
if (node == NULL) {
add_app_with_install_id(&entry, source);
}
}
prv_alert_data_source_changed(source);
}
static void prv_app_icon_name_updated_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_ICON_NAME_UPDATED);
}
//! Must be run from the app task
static void prv_do_app_db_cleared(AppMenuDataSource *source) {
AppMenuNode *iter = source->list;
while (iter) {
AppMenuNode *temp = (AppMenuNode *)list_get_next((ListNode *)iter);
// if the node belonged to the app_db, remove
if (app_install_id_from_app_db(iter->install_id)) {
prv_unload_node(source, iter);
}
iter = temp;
}
prv_alert_data_source_changed(source);
}
static void prv_app_db_cleared_callback(const AppInstallId install_id, void *data) {
// data is just a pointer to the AppMenuDataSource
prv_send_callback_to_app((AppMenuDataSource *)data, INSTALL_ID_INVALID, APP_DB_CLEARED);
}
static bool prv_app_enumerate_callback(AppInstallEntry *entry, void *data) {
if (prv_is_app_filtered_out(entry, (AppMenuDataSource *)data)) {
return true; // continue
}
add_app_with_install_id(entry, data);
return true; // continue
}
////////////////////
// Add / remove helper functions:
// This function should only be called once per app entry. The icon from the app will either be
// loaded and cached or we will load the default system icon that is set by the client.
static void prv_load_list_item_icon(AppMenuDataSource *source, AppMenuNode *node) {
// Should only call this function if th | {
case APP_AVAILABLE:
prv_do_app_added(source, install_id);
break;
case APP_REMOVED:
prv_do_app_removed(source, install_id);
break;
case APP_ICON_NAME_UPDATED:
prv_do_app_icon_name_updated(source, install_id);
break;
case APP_DB_CLEARED:
prv_do_app_db_cleared(source);
break;
default:
break;
} | <|repo_name|>pebble
<|file_sep|>src/fw/process_management/app_menu_data_source.c
<|fim_prefix|>kLaunch);
const int override_cmp_rv = prv_app_override_comparator(app_node->install_id,
new_node->install_id);
if (is_app_quick_launch != is_new_quick_launch) {
// Quick Launch only apps are first
return (is_app_quick_launch ? 1 : 0) - (is_new_quick_launch ? 1 : 0);
} else if (override_cmp_rv) {
// Apps that override storage, record, and install order
return (override_cmp_rv);
} else if (app_node->storage_order != new_node->storage_order) {
// Storage order (smallest first)
return prv_comparator_ascending_zero_last(app_node->storage_order, new_node->storage_order);
} else if (app_node->record_order != new_node->record_order) {
// Record order (smallest first)
return prv_comparator_ascending_zero_last(app_node->record_order, new_node->record_order);
} else {
// AppInstallId (smallest first)
return new_node->install_id - app_node->install_id;
}
}
static void prv_set_storage_order(AppMenuDataSource *source, AppMenuNode *menu_node,
AppMenuOrderStorage *storage, bool update_and_take_ownership) {
if (!storage) {
return;
}
for (int i = 0; i < storage->list_length; i++) {
const AppInstallId storage_app_id = storage->id_list[i];
if (storage_app_id == INSTALL_ID_INVALID) {
continue;
}
const AppMenuStorageOrder new_storage_order =
(AppMenuStorageOrder)i + AppMenuStorageOrderGeneralOrderOffset;
if (menu_node && (menu_node->install_id == storage_app_id)) {
menu_node->storage_order = new_storage_order;
if (!update_and_take_ownership) {
break;
} else {
continue;
}
}
if (update_and_take_ownership) {
AppMenuNode *other_node = prv_find_node_with_install_id(storage_app_id, source);
if (other_node) {
other_node->storage_order = new_storage_order;
}
}
}
if (update_and_take_ownership) {
app_free(storage);
}
}
static void prv_sorted_add(AppMenuDataSource *source, AppMenuNode *menu_node) {
// Update the entire list order only if we've just read the order in this context. If we haven't
// just read the order, then we're building a list starting from an empty list, so just set the
// order for the new node.
prv_set_storage_order(source, menu_node, source->order_storage ?: app_order_read_order(),
(source->order_storage == NULL));
// If we're adding the Settings app node to the list and it hasn't received a storage order,
// then give it its default order
if ((menu_node->install_id == APP_ID_SETTINGS) &&
(menu_node->storage_order == AppMenuStorageOrder_NoOrder)) {
menu_node->storage_order = AppMenuStorageOrder_SettingsDefaultOrder;
}
source->list = (AppMenuNode *)list_sorted_add(&source->list->node, &menu_node->node,
prv_app_node_comparator, true /* ascending */);
}
////////////////////////////////
// AppInstallManager Callbacks
////////////////////////////////
typedef struct InstallData {
AppInstallId id;
AppMenuDataSource *source;
InstallEventType event_type;
} InstallData;
void prv_alert_data_source_changed(AppMenuDataSource *data_source) {
if (data_source->callbacks.changed) {
data_source->callbacks.changed(data_source->callback_context);
}
}
static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id);
static void prv_do_app_db_cleared(AppMenuDataSource *source);
void prv_handle_app_event(void *data) {
InstallData *install_data = data;
AppMenuDataSource *source = install_data->source;
AppInstallId install_id = install_data->id;
switch (install_data->event_type) <|fim_suffix|>
kernel_free(install_data);
}
void prv_send_callback_to_app(AppMenuDataSource *data_source, AppInstallId install_id,
InstallEventType event_type) {
InstallData *install_data = kernel_malloc_check(sizeof(InstallData));
*install_data = (InstallData) {
.id = install_id,
.source = data_source,
.event_type = event_type,
};
process_manager_send_callback_event_to_process(PebbleTask_App,
prv_handle_app_event,
install_data);
}
//! Must be run from the app task
static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id) {
AppInstallEntry entry;
if (!app_install_get_entry_for_install_id(install_id, &entry) ||
prv_is_app_filtered_out(&entry, source)) {
return;
}
add_app_with_install_id(&entry, source);
prv_alert_data_source_changed(source);
}
//! Called when an application is installed
static void prv_app_added_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_AVAILABLE);
}
//! Must be run from the app task
static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id) {
// Don't filter, just always try removing from the list:
const bool is_removed = remove_app_with_install_id(install_id, source);
if (is_removed) {
prv_alert_data_source_changed(source);
}
}
//! Called when an application is uninstalled
static void prv_app_removed_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_REMOVED);
}
//! Must be run from the app task
static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id) {
AppInstallEntry entry;
if (!app_install_get_entry_for_install_id(install_id, &entry)) {
return;
}
AppMenuNode *node = prv_find_node_with_install_id(install_id, source);
if (prv_is_app_filtered_out(&entry, source)) {
if (node == NULL) {
// Changed and still excluded:
return;
}
// Changed and is now excluded:
prv_unload_node(source, node);
} else {
// Changed and is now included:
if (node == NULL) {
add_app_with_install_id(&entry, source);
}
}
prv_alert_data_source_changed(source);
}
static void prv_app_icon_name_updated_callback(const AppInstallId install_id, void *data) {
AppMenuDataSource *data_source = data;
prv_send_callback_to_app(data_source, install_id, APP_ICON_NAME_UPDATED);
}
//! Must be run from the app task
static void prv_do_app_db_cleared(AppMenuDataSource *source) {
AppMenuNode *iter = source->list;
while (iter) {
AppMenuNode *temp = (AppMenuNode *)list_get_next((ListNode *)iter);
// if the node belonged to the app_db, remove
if (app_install_id_from_app_db(iter->install_id)) {
prv_unload_node(source, iter);
}
iter = temp;
}
prv_alert_data_source_changed(source);
}
static void prv_app_db_cleared_callback(const AppInstallId install_id, void *data) {
// data is just a pointer to the AppMenuDataSource
prv_send_callback_to_app((AppMenuDataSource *)data, INSTALL_ID_INVALID, APP_DB_CLEARED);
}
static bool prv_app_enumerate_callback(AppInstallEntry *entry, void *data) {
if (prv_is_app_filtered_out(entry, (AppMenuDataSource *)data)) {
return true; // continue
}
add_app_with_install_id(entry, data);
return true; // continue
}
////////////////////
// Add / remove helper functions:
// This function should only be called once per app entry. The icon from the app will either be
// loaded and cached or we will load the default system icon that is set by the client.
static void prv_load_list_item_icon(AppMenuDataSource *source, AppMenuNode *node) {
// Should only call this function if th<|fim_middle|>{
case APP_AVAILABLE:
prv_do_app_added(source, install_id);
break;
case APP_REMOVED:
prv_do_app_removed(source, install_id);
break;
case APP_ICON_NAME_UPDATED:
prv_do_app_icon_name_updated(source, install_id);
break;
case APP_DB_CLEARED:
prv_do_app_db_cleared(source);
break;
default:
break;
}<|endoftext|> |
masked_node | argument_list | tests/fw/comm/test_gatt_client_subscriptions.c | scover_all(&s_device), BTErrnoOK);
prv_simulate_and_assert_discovery_of_one_service(&s_device);
fake_event_clear_last();
}
void test_gatt_client_subscriptions__cleanup(void) {
for (GAPLEClient c = 0; c < GAPLEClientNum; ++c) {
gatt_client_subscriptions_cleanup_by_client(c);
}
gap_le_connection_deinit();
gatt_client_subscription_cleanup();
fake_pbl_malloc_check_net_allocs();
fake_pbl_malloc_clear_tracking();
}
// -------------------------------------------------------------------------------------------------
// gatt_client_subscriptions_subscribe
void test_gatt_client_subscriptions__subscribe_invalid_characteristic(void) {
fake_kernel_malloc_mark();
BTErrno e = gatt_client_subscriptions_subscribe(BOGUS_CHARACTERISTIC,
BLESubscriptionAny, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_no_cccd(void) {
// The random 128-bit Service UUID:
Uuid service_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63,
0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB0);
BLEService service;
uint8_t num_copied = gatt_client_copy_service_refs_matching_uuid(&s_device, &service, 1,
&service_uuid);
cl_assert_equal_i(num_copied, 1);
// UUID for Characteristic that has no CCCD:
Uuid characteristic_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63,
0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB1);
BLECharacteristic characteristic;
num_copied = gatt_client_service_get_characteristics_matching_uuids(service, &characteristic,
&characteristic_uuid, 1);
cl_assert_equal_i(num_copied, 1);
fake_kernel_malloc_mark();
// Try to subscribe to the non-subscribe-able characteristic:
BTErrno e = gatt_client_subscriptions_subscribe(characteristic,
BLESubscriptionAny, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_unsupported_subscription_type(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
fake_kernel_malloc_mark();
// Try to subscribe for notifications to the indicatable (but not notify-able) characteristic:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNotifications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
// Try to subscribe for indications to the indicatable characteristic:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
}
void test_gatt_client_subscriptions__subscribe_already_subscribed(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
fake_event_clear_last();
fake_kernel_malloc_mark();
// Subscribe again:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_pending_subscription(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe | ;
cl_assert_equal_i(e, BTErrnoOK);
fake_event_clear_last();
fake_kernel_malloc_mark();
// Un-subscribe, while subscribing process is still pending:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_oom_for_subscription_allocation(void) {
fake_kernel_malloc_mark();
fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode) - 1);
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoNotEnoughResources);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_oom_for_buffer_allocation(void) {
fake_kernel_malloc_mark();
fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode));
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoNotEnoughResources);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_cccd_write_error(void) {
s_write_descriptor_cccd_result = -1;
fake_kernel_malloc_mark();
// Try to subscribe for indications to the indicatable characteristic:
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, -1);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_no_clients_subscribed(void) {
fake_kernel_malloc_mark();
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_not_subscribed_but_other_client_is(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientApp);
cl_assert_equal_i(e, BTErrnoOK);
fake_kernel_malloc_mark();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_first_subscriber(void) {
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications);
prv_confirm_cccd_write(BLEGATTErrorSuccess);
prv_assert_subscription_event(characteristic, BLESubscriptionIndications, BLEGATTErrorSuccess,
true /* kernel */, false /* app */);
}
void test_gatt_client_subscriptions__subscribe_not_first_subscriber(void) {
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
// Subscribe kernel:
BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications);
// Simulate ge | (characteristic, BLESubscriptionIndications,
GAPLEClientKernel) | <|repo_name|>pebble
<|file_sep|>tests/fw/comm/test_gatt_client_subscriptions.c
<|fim_prefix|>scover_all(&s_device), BTErrnoOK);
prv_simulate_and_assert_discovery_of_one_service(&s_device);
fake_event_clear_last();
}
void test_gatt_client_subscriptions__cleanup(void) {
for (GAPLEClient c = 0; c < GAPLEClientNum; ++c) {
gatt_client_subscriptions_cleanup_by_client(c);
}
gap_le_connection_deinit();
gatt_client_subscription_cleanup();
fake_pbl_malloc_check_net_allocs();
fake_pbl_malloc_clear_tracking();
}
// -------------------------------------------------------------------------------------------------
// gatt_client_subscriptions_subscribe
void test_gatt_client_subscriptions__subscribe_invalid_characteristic(void) {
fake_kernel_malloc_mark();
BTErrno e = gatt_client_subscriptions_subscribe(BOGUS_CHARACTERISTIC,
BLESubscriptionAny, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_no_cccd(void) {
// The random 128-bit Service UUID:
Uuid service_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63,
0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB0);
BLEService service;
uint8_t num_copied = gatt_client_copy_service_refs_matching_uuid(&s_device, &service, 1,
&service_uuid);
cl_assert_equal_i(num_copied, 1);
// UUID for Characteristic that has no CCCD:
Uuid characteristic_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63,
0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB1);
BLECharacteristic characteristic;
num_copied = gatt_client_service_get_characteristics_matching_uuids(service, &characteristic,
&characteristic_uuid, 1);
cl_assert_equal_i(num_copied, 1);
fake_kernel_malloc_mark();
// Try to subscribe to the non-subscribe-able characteristic:
BTErrno e = gatt_client_subscriptions_subscribe(characteristic,
BLESubscriptionAny, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_unsupported_subscription_type(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
fake_kernel_malloc_mark();
// Try to subscribe for notifications to the indicatable (but not notify-able) characteristic:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNotifications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidParameter);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
// Try to subscribe for indications to the indicatable characteristic:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
}
void test_gatt_client_subscriptions__subscribe_already_subscribed(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
fake_event_clear_last();
fake_kernel_malloc_mark();
// Subscribe again:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_pending_subscription(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe<|fim_suffix|>;
cl_assert_equal_i(e, BTErrnoOK);
fake_event_clear_last();
fake_kernel_malloc_mark();
// Un-subscribe, while subscribing process is still pending:
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_oom_for_subscription_allocation(void) {
fake_kernel_malloc_mark();
fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode) - 1);
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoNotEnoughResources);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_oom_for_buffer_allocation(void) {
fake_kernel_malloc_mark();
fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode));
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoNotEnoughResources);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_cccd_write_error(void) {
s_write_descriptor_cccd_result = -1;
fake_kernel_malloc_mark();
// Try to subscribe for indications to the indicatable characteristic:
BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(),
BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, -1);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_no_clients_subscribed(void) {
fake_kernel_malloc_mark();
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__unsubscribe_not_subscribed_but_other_client_is(void) {
BTErrno e;
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientApp);
cl_assert_equal_i(e, BTErrnoOK);
fake_kernel_malloc_mark();
e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoInvalidState);
fake_kernel_malloc_mark_assert_equal();
prv_assert_no_event();
}
void test_gatt_client_subscriptions__subscribe_first_subscriber(void) {
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications);
prv_confirm_cccd_write(BLEGATTErrorSuccess);
prv_assert_subscription_event(characteristic, BLESubscriptionIndications, BLEGATTErrorSuccess,
true /* kernel */, false /* app */);
}
void test_gatt_client_subscriptions__subscribe_not_first_subscriber(void) {
BLECharacteristic characteristic = prv_get_indicatable_characteristic();
// Subscribe kernel:
BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications,
GAPLEClientKernel);
cl_assert_equal_i(e, BTErrnoOK);
cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications);
// Simulate ge<|fim_middle|>(characteristic, BLESubscriptionIndications,
GAPLEClientKernel)<|endoftext|> |
masked_node | call_expression | src/fw/kernel/util/factory_reset.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kernel/util/factory_reset.h"
#include "drivers/rtc.h"
#include "drivers/task_watchdog.h"
#include "flash_region/filesystem_regions.h"
#include "kernel/event_loop.h"
#include "kernel/util/standby.h"
#include "process_management/worker_manager.h"
#include "services/common/event_service.h"
#include "services/common/shared_prf_storage/shared_prf_storage.h"
#include "services/common/system_task.h"
#include "services/runlevel.h"
#include "shell/normal/app_idle_timeout.h"
#include "system/bootbits.h"
#include "system/logging.h"
#include "system/reboot_reason.h"
#include "system/reset.h"
#include "kernel/util/sleep.h"
#if !RECOVERY_FW
#include "services/normal/blob_db/pin_db.h"
#include "services/normal/blob_db/reminder_db.h"
#include "services/normal/filesystem/pfs.h"
#include "services/normal/timeline/event.h"
#endif
static bool s_in_factory_reset = false;
static void prv_factory_reset_non_pfs_data() {
PBL_LOG_SYNC(LOG_LEVEL_INFO, "Factory resetting...");
// This function can block the system task for a long time.
// Prevent callbacks being added to the system task so it doesn't overflow.
system_task_block_callbacks(true /* block callbacks */);
launcher_block_popups(true);
worker_manager_disable();
event_service_clear_process_subscriptions(PebbleTask_App);
shared_prf_storage_wipe_all();
services_set_runlevel(RunLevel_BareMinimum);
app_idle_timeout_stop();
while (worker_manager_get_current_worker_md()) {
// busy loop until the worker is killed
psleep(3);
}
rtc_timezone_clear();
}
void factory_reset_set_reason_and_reset(void) {
RebootReason reason = { RebootReasonCode_FactoryResetReset, 0 };
reboot_reason_set(&reason);
system_reset();
}
static void prv_factory_reset_post(bool should_shutdown) {
if (should_shutdown) {
enter_standby(RebootReasonCode_FactoryResetShutdown);
} else {
factory_reset_set_reason_and_reset();
}
}
void factory_reset(bool should_shutdown) {
s_in_factory_reset = true;
prv_factory_reset_non_pfs_data();
// TODO: wipe the registry on tintin?
filesystem_regions_erase_all();
#if !defined(RECOVERY_FW)
// "First use" is part of the PRF image for Snowy
boot_bit_set(BOOT_BIT_FORCE_PRF);
#endif
prv_factory_reset_post(should_shutdown);
}
#if !RECOVERY_FW
void close_db_files() {
// Deinit the databases and any clients
timeline_event_deinit();
reminder_db_deinit();
pin_db_deinit();
}
void factory_reset_fast(void *unused) {
s_in_factory_reset = true;
// disable the watchdog... we've got lots to do before we reset
task_watchdog_mask_clear(pebble_task_get_current());
| ;
prv_factory_reset_non_pfs_data();
pfs_remove_files(NULL);
prv_factory_reset_post(false /* should_shutdown */);
}
#endif // !RECOVERY_FW
//! Used by the mfg flow to kick us out the MFG firmware and into the conumer PRF that's stored
//! on the external flash.
void command_enter_consumer_mode(void) {
boot_bit_set(BOOT_BIT_FORCE_PRF);
factory_reset(true /* should_shutdown */);
}
bool factory_reset_ongoing(void) {
return s_in_factory_reset;
}
| close_db_files() | <|repo_name|>pebble
<|file_sep|>src/fw/kernel/util/factory_reset.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kernel/util/factory_reset.h"
#include "drivers/rtc.h"
#include "drivers/task_watchdog.h"
#include "flash_region/filesystem_regions.h"
#include "kernel/event_loop.h"
#include "kernel/util/standby.h"
#include "process_management/worker_manager.h"
#include "services/common/event_service.h"
#include "services/common/shared_prf_storage/shared_prf_storage.h"
#include "services/common/system_task.h"
#include "services/runlevel.h"
#include "shell/normal/app_idle_timeout.h"
#include "system/bootbits.h"
#include "system/logging.h"
#include "system/reboot_reason.h"
#include "system/reset.h"
#include "kernel/util/sleep.h"
#if !RECOVERY_FW
#include "services/normal/blob_db/pin_db.h"
#include "services/normal/blob_db/reminder_db.h"
#include "services/normal/filesystem/pfs.h"
#include "services/normal/timeline/event.h"
#endif
static bool s_in_factory_reset = false;
static void prv_factory_reset_non_pfs_data() {
PBL_LOG_SYNC(LOG_LEVEL_INFO, "Factory resetting...");
// This function can block the system task for a long time.
// Prevent callbacks being added to the system task so it doesn't overflow.
system_task_block_callbacks(true /* block callbacks */);
launcher_block_popups(true);
worker_manager_disable();
event_service_clear_process_subscriptions(PebbleTask_App);
shared_prf_storage_wipe_all();
services_set_runlevel(RunLevel_BareMinimum);
app_idle_timeout_stop();
while (worker_manager_get_current_worker_md()) {
// busy loop until the worker is killed
psleep(3);
}
rtc_timezone_clear();
}
void factory_reset_set_reason_and_reset(void) {
RebootReason reason = { RebootReasonCode_FactoryResetReset, 0 };
reboot_reason_set(&reason);
system_reset();
}
static void prv_factory_reset_post(bool should_shutdown) {
if (should_shutdown) {
enter_standby(RebootReasonCode_FactoryResetShutdown);
} else {
factory_reset_set_reason_and_reset();
}
}
void factory_reset(bool should_shutdown) {
s_in_factory_reset = true;
prv_factory_reset_non_pfs_data();
// TODO: wipe the registry on tintin?
filesystem_regions_erase_all();
#if !defined(RECOVERY_FW)
// "First use" is part of the PRF image for Snowy
boot_bit_set(BOOT_BIT_FORCE_PRF);
#endif
prv_factory_reset_post(should_shutdown);
}
#if !RECOVERY_FW
void close_db_files() {
// Deinit the databases and any clients
timeline_event_deinit();
reminder_db_deinit();
pin_db_deinit();
}
void factory_reset_fast(void *unused) {
s_in_factory_reset = true;
// disable the watchdog... we've got lots to do before we reset
task_watchdog_mask_clear(pebble_task_get_current());
<|fim_suffix|>;
prv_factory_reset_non_pfs_data();
pfs_remove_files(NULL);
prv_factory_reset_post(false /* should_shutdown */);
}
#endif // !RECOVERY_FW
//! Used by the mfg flow to kick us out the MFG firmware and into the conumer PRF that's stored
//! on the external flash.
void command_enter_consumer_mode(void) {
boot_bit_set(BOOT_BIT_FORCE_PRF);
factory_reset(true /* should_shutdown */);
}
bool factory_reset_ongoing(void) {
return s_in_factory_reset;
}
<|fim_middle|>close_db_files()<|endoftext|> |
masked_node | call_expression | src/fw/services/normal/activity/health_util.c | 0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "health_util.h"
#include "services/common/i18n/i18n.h"
#include "services/normal/activity/activity.h"
#include "shell/prefs.h"
#include "util/time/time.h"
#include "util/units.h"
#include "util/string.h"
#include <limits.h>
#include <stdio.h>
#include <string.h>
static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) {
*hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN;
*minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN;
if (*minutes == INT_MIN && *hours == INT_MIN) {
*hours = 0;
}
}
int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s,
void *i18n_owner) {
int hours;
int minutes;
prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes);
int pos = 0;
if (hours != INT_MIN) {
pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours);
if (minutes != INT_MIN && pos < (int)buffer_size - 1) {
buffer[pos++] = ' ';
}
}
if (minutes != INT_MIN) {
pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes);
}
return pos;
}
int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s,
bool leading_zero, void *i18n_owner) {
const int hours = duration_s / SECONDS_PER_HOUR;
const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE;
if (hours > 0) {
const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d";
return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds);
} else {
const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d";
return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds);
}
}
int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s,
void *i18n_owner) {
int minutes = duration_s / SECONDS_PER_MINUTE;
int seconds = duration_s % SECONDS_PER_MINUTE;
return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds);
}
GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color,
GTextNodeContainer *container) {
GTextNodeText *text_node = graphics_text_node_create_text(buffer_size);
if (container) {
graphics_text_node_container_add_child(container, &text_node->node);
}
text_node->font = font;
text_node->color = color;
return text_node;
}
GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color,
GTextNodeContainer *container) {
GTextNodeText *text_node = health_util_create_text_node(0, font, color, container);
text_node->text = text;
return text_node;
}
void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner,
GFont number_font, GFont units_font,
GColor color,
GTextNodeContainer *container) {
int hours;
int minutes;
prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes);
const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font);
const int hours_and_minutes_buffer_size = sizeof("00");
if (hours != INT_MIN) {
GTextNodeText *hours_text_node = | ;
snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size,
i18n_get("%d", i18n_owner), hours);
GTextNodeText *hours_units_text_node = health_util_create_text_node_with_text(
i18n_get("H", i18n_owner), units_font, color, container);
hours_units_text_node->node.offset.y = units_offset_y;
}
if (hours != INT_MIN && minutes != INT_MIN) {
// add a space between the H and the number of minutes
health_util_create_text_node_with_text(i18n_get(" ", i18n_owner), units_font, color, container);
}
if (minutes != INT_MIN) {
GTextNodeText *minutes_text_node = health_util_create_text_node(hours_and_minutes_buffer_size,
number_font, color, container);
snprintf((char *) minutes_text_node->text, hours_and_minutes_buffer_size,
i18n_get("%d", i18n_owner), minutes);
GTextNodeText *minutes_units_text_node = health_util_create_text_node_with_text(
i18n_get("M", i18n_owner), units_font, color, container);
minutes_units_text_node->node.offset.y = units_offset_y;
}
}
void health_util_convert_fraction_to_whole_and_decimal_part(int numerator, int denominator,
int* whole_part, int *decimal_part) {
const int figure = ROUND(numerator * 100, denominator * 10);
*whole_part = figure / 10;
*decimal_part = figure % 10;
}
int health_util_format_whole_and_decimal(char *buffer, size_t buffer_size, int numerator,
int denominator) {
int converted_distance_whole_part = 0;
int converted_distance_decimal_part = 0;
health_util_convert_fraction_to_whole_and_decimal_part(numerator, denominator,
&converted_distance_whole_part,
&converted_distance_decimal_part);
const char *fmt_i18n = i18n_noop("%d.%d");
const int rv = snprintf(buffer, buffer_size, i18n_get(fmt_i18n, buffer),
converted_distance_whole_part, converted_distance_decimal_part);
i18n_free(fmt_i18n, buffer);
return rv;
}
int health_util_get_distance_factor(void) {
switch (shell_prefs_get_units_distance()) {
case UnitsDistance_Miles:
return METERS_PER_MILE;
case UnitsDistance_KM:
return METERS_PER_KM;
case UnitsDistanceCount:
break;
}
return 1;
}
const char *health_util_get_distance_string(const char *miles_string, const char *km_string) {
switch (shell_prefs_get_units_distance()) {
case UnitsDistance_Miles:
return miles_string;
case UnitsDistance_KM:
return km_string;
case UnitsDistanceCount:
break;
}
return "";
}
int health_util_format_distance(char *buffer, size_t buffer_size, uint32_t distance_m) {
return health_util_format_whole_and_decimal(buffer, buffer_size, distance_m,
health_util_get_distance_factor());
}
void health_util_convert_distance_to_whole_and_decimal_part(int distance_m, int *whole_part,
int *decimal_part) {
const int conversion_factor = health_util_get_distance_factor();
health_util_convert_fraction_to_whole_and_decimal_part(distance_m, conversion_factor,
whole_part, decimal_part);
}
time_t health_util_get_pace(int time_s, int distance_meter) {
if (!distance_meter) {
return 0;
}
return ROUND(time_s * health_util_get_distance_factor(), distance_meter);
}
| health_util_create_text_node(hours_and_minutes_buffer_size,
number_font, color, container) | <|repo_name|>pebble
<|file_sep|>src/fw/services/normal/activity/health_util.c
<|fim_prefix|>0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "health_util.h"
#include "services/common/i18n/i18n.h"
#include "services/normal/activity/activity.h"
#include "shell/prefs.h"
#include "util/time/time.h"
#include "util/units.h"
#include "util/string.h"
#include <limits.h>
#include <stdio.h>
#include <string.h>
static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) {
*hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN;
*minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN;
if (*minutes == INT_MIN && *hours == INT_MIN) {
*hours = 0;
}
}
int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s,
void *i18n_owner) {
int hours;
int minutes;
prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes);
int pos = 0;
if (hours != INT_MIN) {
pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours);
if (minutes != INT_MIN && pos < (int)buffer_size - 1) {
buffer[pos++] = ' ';
}
}
if (minutes != INT_MIN) {
pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes);
}
return pos;
}
int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s,
bool leading_zero, void *i18n_owner) {
const int hours = duration_s / SECONDS_PER_HOUR;
const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE;
if (hours > 0) {
const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d";
return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds);
} else {
const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d";
return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds);
}
}
int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s,
void *i18n_owner) {
int minutes = duration_s / SECONDS_PER_MINUTE;
int seconds = duration_s % SECONDS_PER_MINUTE;
return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds);
}
GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color,
GTextNodeContainer *container) {
GTextNodeText *text_node = graphics_text_node_create_text(buffer_size);
if (container) {
graphics_text_node_container_add_child(container, &text_node->node);
}
text_node->font = font;
text_node->color = color;
return text_node;
}
GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color,
GTextNodeContainer *container) {
GTextNodeText *text_node = health_util_create_text_node(0, font, color, container);
text_node->text = text;
return text_node;
}
void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner,
GFont number_font, GFont units_font,
GColor color,
GTextNodeContainer *container) {
int hours;
int minutes;
prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes);
const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font);
const int hours_and_minutes_buffer_size = sizeof("00");
if (hours != INT_MIN) {
GTextNodeText *hours_text_node = <|fim_suffix|>;
snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size,
i18n_get("%d", i18n_owner), hours);
GTextNodeText *hours_units_text_node = health_util_create_text_node_with_text(
i18n_get("H", i18n_owner), units_font, color, container);
hours_units_text_node->node.offset.y = units_offset_y;
}
if (hours != INT_MIN && minutes != INT_MIN) {
// add a space between the H and the number of minutes
health_util_create_text_node_with_text(i18n_get(" ", i18n_owner), units_font, color, container);
}
if (minutes != INT_MIN) {
GTextNodeText *minutes_text_node = health_util_create_text_node(hours_and_minutes_buffer_size,
number_font, color, container);
snprintf((char *) minutes_text_node->text, hours_and_minutes_buffer_size,
i18n_get("%d", i18n_owner), minutes);
GTextNodeText *minutes_units_text_node = health_util_create_text_node_with_text(
i18n_get("M", i18n_owner), units_font, color, container);
minutes_units_text_node->node.offset.y = units_offset_y;
}
}
void health_util_convert_fraction_to_whole_and_decimal_part(int numerator, int denominator,
int* whole_part, int *decimal_part) {
const int figure = ROUND(numerator * 100, denominator * 10);
*whole_part = figure / 10;
*decimal_part = figure % 10;
}
int health_util_format_whole_and_decimal(char *buffer, size_t buffer_size, int numerator,
int denominator) {
int converted_distance_whole_part = 0;
int converted_distance_decimal_part = 0;
health_util_convert_fraction_to_whole_and_decimal_part(numerator, denominator,
&converted_distance_whole_part,
&converted_distance_decimal_part);
const char *fmt_i18n = i18n_noop("%d.%d");
const int rv = snprintf(buffer, buffer_size, i18n_get(fmt_i18n, buffer),
converted_distance_whole_part, converted_distance_decimal_part);
i18n_free(fmt_i18n, buffer);
return rv;
}
int health_util_get_distance_factor(void) {
switch (shell_prefs_get_units_distance()) {
case UnitsDistance_Miles:
return METERS_PER_MILE;
case UnitsDistance_KM:
return METERS_PER_KM;
case UnitsDistanceCount:
break;
}
return 1;
}
const char *health_util_get_distance_string(const char *miles_string, const char *km_string) {
switch (shell_prefs_get_units_distance()) {
case UnitsDistance_Miles:
return miles_string;
case UnitsDistance_KM:
return km_string;
case UnitsDistanceCount:
break;
}
return "";
}
int health_util_format_distance(char *buffer, size_t buffer_size, uint32_t distance_m) {
return health_util_format_whole_and_decimal(buffer, buffer_size, distance_m,
health_util_get_distance_factor());
}
void health_util_convert_distance_to_whole_and_decimal_part(int distance_m, int *whole_part,
int *decimal_part) {
const int conversion_factor = health_util_get_distance_factor();
health_util_convert_fraction_to_whole_and_decimal_part(distance_m, conversion_factor,
whole_part, decimal_part);
}
time_t health_util_get_pace(int time_s, int distance_meter) {
if (!distance_meter) {
return 0;
}
return ROUND(time_s * health_util_get_distance_factor(), distance_meter);
}
<|fim_middle|>health_util_create_text_node(hours_and_minutes_buffer_size,
number_font, color, container)<|endoftext|> |
masked_node | call_expression | src/fw/services/normal/comm_session/app_session_capabilities.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "process_management/app_install_types.h"
#include "process_management/app_manager.h"
#include "services/common/comm_session/app_session_capabilities.h"
#include "services/normal/settings/settings_file.h"
#include "util/units.h"
#define APP_SESSION_CAPABILITIES_CACHE_FILENAME "app_comm"
#define APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE (KiBYTES(2))
static status_t prv_open(SettingsFile *settings_file) {
return settings_file_open(settings_file, APP_SESSION_CAPABILITIES_CACHE_FILENAME,
APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE);
}
bool comm_session_current_app_session_cache_has_capability(CommSessionCapability capability) {
CommSession *app_session = comm_session_get_current_app_session();
const Uuid app_uuid = app_manager_get_current_app_md()->uuid;
SettingsFile settings_file;
status_t open_status = prv_open(&settings_file);
uint64_t cached_capabilities = 0;
if (PASSED(open_status)) {
settings_file_get(&settings_file,
&app_uuid, sizeof(app_uuid),
&cached_capabilities, sizeof(cached_capabilities));
}
uint64_t new_capabilities = cached_capabilities;
if (app_session) {
// Connected, grab fresh capabilities data:
new_capabilities = comm_session_get_capabilities(app_session);
if (FAILED(open_status)) {
// File open failed, return live data without saving to cache
goto done;
}
if (new_capabilities != cached_capabilities) {
settings_file_set(&settings_file,
&app_uuid, sizeof(app_uuid),
&new_capabilities, sizeof(new_capabilities));
}
} else {
// Not connected, use cached data.
if (FAILED(open_status)) {
// File open failed, no cache available
goto done;
}
}
settings_file_close(&settings_file);
done:
return ((new_capabilities & capability) != 0);
}
static void prv_rewrite_cb(SettingsFile *old_file,
SettingsFile *new_file,
SettingsRecordInfo *info,
void *context) {
if (!info->val_len) {
return; // Cache for this app has been deleted, don't rewrite it
}
Uuid key;
uint64_t val;
info->get_key(old_file, &key, sizeof(key));
info->get_val(old_file, &val, sizeof(val));
settings_file_set(new_file, &key, sizeof(key), &val, sizeof(val));
}
void comm_session_app_session_capabilities_evict(const Uuid *app_uuid) {
SettingsFile settings_file;
if (PASSED(prv_open(&settings_file))) {
| ;
settings_file_close(&settings_file);
}
}
void comm_session_app_session_capabilities_init(void) {
SettingsFile settings_file;
if (PASSED(prv_open(&settings_file))) {
settings_file_rewrite(&settings_file, prv_rewrite_cb, NULL);
settings_file_close(&settings_file);
}
}
| settings_file_delete(&settings_file, app_uuid, sizeof(*app_uuid)) | <|repo_name|>pebble
<|file_sep|>src/fw/services/normal/comm_session/app_session_capabilities.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "process_management/app_install_types.h"
#include "process_management/app_manager.h"
#include "services/common/comm_session/app_session_capabilities.h"
#include "services/normal/settings/settings_file.h"
#include "util/units.h"
#define APP_SESSION_CAPABILITIES_CACHE_FILENAME "app_comm"
#define APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE (KiBYTES(2))
static status_t prv_open(SettingsFile *settings_file) {
return settings_file_open(settings_file, APP_SESSION_CAPABILITIES_CACHE_FILENAME,
APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE);
}
bool comm_session_current_app_session_cache_has_capability(CommSessionCapability capability) {
CommSession *app_session = comm_session_get_current_app_session();
const Uuid app_uuid = app_manager_get_current_app_md()->uuid;
SettingsFile settings_file;
status_t open_status = prv_open(&settings_file);
uint64_t cached_capabilities = 0;
if (PASSED(open_status)) {
settings_file_get(&settings_file,
&app_uuid, sizeof(app_uuid),
&cached_capabilities, sizeof(cached_capabilities));
}
uint64_t new_capabilities = cached_capabilities;
if (app_session) {
// Connected, grab fresh capabilities data:
new_capabilities = comm_session_get_capabilities(app_session);
if (FAILED(open_status)) {
// File open failed, return live data without saving to cache
goto done;
}
if (new_capabilities != cached_capabilities) {
settings_file_set(&settings_file,
&app_uuid, sizeof(app_uuid),
&new_capabilities, sizeof(new_capabilities));
}
} else {
// Not connected, use cached data.
if (FAILED(open_status)) {
// File open failed, no cache available
goto done;
}
}
settings_file_close(&settings_file);
done:
return ((new_capabilities & capability) != 0);
}
static void prv_rewrite_cb(SettingsFile *old_file,
SettingsFile *new_file,
SettingsRecordInfo *info,
void *context) {
if (!info->val_len) {
return; // Cache for this app has been deleted, don't rewrite it
}
Uuid key;
uint64_t val;
info->get_key(old_file, &key, sizeof(key));
info->get_val(old_file, &val, sizeof(val));
settings_file_set(new_file, &key, sizeof(key), &val, sizeof(val));
}
void comm_session_app_session_capabilities_evict(const Uuid *app_uuid) {
SettingsFile settings_file;
if (PASSED(prv_open(&settings_file))) {
<|fim_suffix|>;
settings_file_close(&settings_file);
}
}
void comm_session_app_session_capabilities_init(void) {
SettingsFile settings_file;
if (PASSED(prv_open(&settings_file))) {
settings_file_rewrite(&settings_file, prv_rewrite_cb, NULL);
settings_file_close(&settings_file);
}
}
<|fim_middle|>settings_file_delete(&settings_file, app_uuid, sizeof(*app_uuid))<|endoftext|> |
masked_node | compound_statement | tests/libc/printf/test_sprintf.c |
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%llnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, llntest);
cl_assert_equal_i(llntest[0], 280);
cl_assert_equal_i(llntest[1], 0);
jntest[0] = jntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%jnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, jntest);
cl_assert_equal_i(jntest[0], 280);
cl_assert_equal_i(jntest[1], 0);
zntest[0] = zntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%znaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, zntest);
cl_assert_equal_i(zntest[0], 280);
cl_assert_equal_i(zntest[1], 0);
tntest[0] = tntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%tnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, tntest);
cl_assert_equal_i(tntest[0], 280);
| cl_assert_equal_i(tntest[1], 0);
} | <|repo_name|>pebble
<|file_sep|>tests/libc/printf/test_sprintf.c
<|fim_prefix|>
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%llnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, llntest);
cl_assert_equal_i(llntest[0], 280);
cl_assert_equal_i(llntest[1], 0);
jntest[0] = jntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%jnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, jntest);
cl_assert_equal_i(jntest[0], 280);
cl_assert_equal_i(jntest[1], 0);
zntest[0] = zntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%znaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, zntest);
cl_assert_equal_i(zntest[0], 280);
cl_assert_equal_i(zntest[1], 0);
tntest[0] = tntest[1] = 0;
snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20
"aaaa aaaa aaaa aaaa " // 20- 40
"aaaa aaaa aaaa aaaa " // 40- 60
"aaaa aaaa aaaa aaaa " // 60- 80
"aaaa aaaa aaaa aaaa " // 80-100
"aaaa aaaa aaaa aaaa " //100-120
"aaaa aaaa aaaa aaaa " //120-140
"aaaa aaaa aaaa aaaa " //140-160
"aaaa aaaa aaaa aaaa " //160-180
"aaaa aaaa aaaa aaaa " //180-200
"aaaa aaaa aaaa aaaa " //200-220
"aaaa aaaa aaaa aaaa " //220-240
"aaaa aaaa aaaa aaaa " //240-260
"aaaa aaaa aaaa aaaa " //260-280
"%tnaaaa aaaa aaaa aaaa " //280-300
"aaaa aaaa aaaa aaaa " //300-320
, tntest);
cl_assert_equal_i(tntest[0], 280);
<|fim_suffix|>
<|fim_middle|> cl_assert_equal_i(tntest[1], 0);
}<|endoftext|> |
|
prefix_only | call_expression | tests/libutil/test_math.c | check_atan2(1, -32768); // <- causes overflow for int16
check_atan2(20001, 20000); // <- causes overflow if numbers are added in an int16
check_atan2(32767, 1);
check_atan2(1, 32767);
check_atan2(32767, 0);
check_atan2(0, 32767);
check_atan2(23400, -25300);
check_atan2(30500, -1930);
check_atan2(-6, -310);
check_atan2(15000, -19);
check_atan2(34, -3200);
check_atan2(-1508, 299);
check_atan2(1020, 1002);
}
void test_math__ceil_log_two(void) {
check_ceil_log_two(4);
check_ceil_log_two(5);
check_ceil_log_two(100);
check_ceil_log_two(256);
check_ceil_log_two(123456);
}
void test_math__sign_extend(void) {
cl_assert_equal_i(sign_extend(0, 32), 0);
cl_assert_equal_i(sign_extend(0, 3), 0);
cl_assert_equal_i(sign_extend(1, 32), 1);
cl_assert_equal_i(sign_extend(1, 3), 1);
cl_assert_equal_i(sign_extend(-1, 32), -1);
cl_assert_equal_i(sign_extend(-1, 3), -1);
cl_assert_equal_i(sign_extend(7, 32), 7);
cl_assert_equal_i(sign_extend(7, 3), -1);
}
void test_math__serial_distance32(void) {
{
int32_t dist = serial_distance32(0x0, 0x1);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance32(0x1, 0x0);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance32(0x0, 0xffffffff);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance32(0xffffffff, 0x0);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance32(0x0, 0x7fffffff);
cl_assert_equal_i(dist, 0x7fffffff);
}
}
void test_math__serial_distance3(void) {
{
int32_t dist = serial_distance(0, 1, 3);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance(1, 0, 3);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance(0, 7, 3);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance(7, 0, 3);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance(6, 0, 3);
cl_assert_equal_i(dist, 2);
}
{
int32_t dist = serial_distance(7, 1, 3);
cl_assert_equal_i(dist, 2);
}
{
int32_t dist = serial_distance(6, 1, 3);
cl_assert_equal_i(dist, 3);
}
}
void test_math__is_signed_macro(void) {
cl_assert(IS_SIGNED((int)-1) == true);
cl_assert(IS_SIGNED((unsigned int)1) == false);
}
void test_math__test_within_macro(void) {
int16_t min;
int16_t max;
// Min and max are both positive
////////////////////////////////
min = 5;
max = 10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_b(WITHIN(7, min, max), true);
// Just out of bounds
cl_assert_equal_b(WITHIN(4, min, max), false);
cl_assert_equal_b(WITHIN(11, min, max), false);
// Negative out of bounds
cl_assert_equal_i(WITHIN(-5, min, max), false);
// Positive out of bounds
cl_assert_equal_i(WITHIN(0, min, max), false);
// Min negative, max positive
////////////////////////////////
min = -10;
max = 10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_i(WITHIN(-5, min, max), true);
cl_assert_equal_i(WITHIN(0, min, max), true);
cl_assert_equal_i(WITHIN(5, min, max), true);
// Just out of bounds
cl_assert_equal_i(WITHIN(-11, min, max), false);
cl_assert_equal_i(WITHIN(11, min, max), false);
// Min and max are both negative
////////////////////////////////
min = -20;
max = -10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_i(WITHIN(-15, min, max), true);
// Just out of bounds
cl_assert_equal_i(WITHIN(-21, min, max), false);
cl_assert_equal_i(WITHIN(-9, min, max), false);
// Positive out of bounds
cl_assert_equal_i(WITHIN(0, min, max), false);
cl_assert_equal_i( | WITHIN(5, min, max) | <|repo_name|>pebble
<|file_sep|>tests/libutil/test_math.c
<|fim_prefix|> check_atan2(1, -32768); // <- causes overflow for int16
check_atan2(20001, 20000); // <- causes overflow if numbers are added in an int16
check_atan2(32767, 1);
check_atan2(1, 32767);
check_atan2(32767, 0);
check_atan2(0, 32767);
check_atan2(23400, -25300);
check_atan2(30500, -1930);
check_atan2(-6, -310);
check_atan2(15000, -19);
check_atan2(34, -3200);
check_atan2(-1508, 299);
check_atan2(1020, 1002);
}
void test_math__ceil_log_two(void) {
check_ceil_log_two(4);
check_ceil_log_two(5);
check_ceil_log_two(100);
check_ceil_log_two(256);
check_ceil_log_two(123456);
}
void test_math__sign_extend(void) {
cl_assert_equal_i(sign_extend(0, 32), 0);
cl_assert_equal_i(sign_extend(0, 3), 0);
cl_assert_equal_i(sign_extend(1, 32), 1);
cl_assert_equal_i(sign_extend(1, 3), 1);
cl_assert_equal_i(sign_extend(-1, 32), -1);
cl_assert_equal_i(sign_extend(-1, 3), -1);
cl_assert_equal_i(sign_extend(7, 32), 7);
cl_assert_equal_i(sign_extend(7, 3), -1);
}
void test_math__serial_distance32(void) {
{
int32_t dist = serial_distance32(0x0, 0x1);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance32(0x1, 0x0);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance32(0x0, 0xffffffff);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance32(0xffffffff, 0x0);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance32(0x0, 0x7fffffff);
cl_assert_equal_i(dist, 0x7fffffff);
}
}
void test_math__serial_distance3(void) {
{
int32_t dist = serial_distance(0, 1, 3);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance(1, 0, 3);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance(0, 7, 3);
cl_assert_equal_i(dist, -1);
}
{
int32_t dist = serial_distance(7, 0, 3);
cl_assert_equal_i(dist, 1);
}
{
int32_t dist = serial_distance(6, 0, 3);
cl_assert_equal_i(dist, 2);
}
{
int32_t dist = serial_distance(7, 1, 3);
cl_assert_equal_i(dist, 2);
}
{
int32_t dist = serial_distance(6, 1, 3);
cl_assert_equal_i(dist, 3);
}
}
void test_math__is_signed_macro(void) {
cl_assert(IS_SIGNED((int)-1) == true);
cl_assert(IS_SIGNED((unsigned int)1) == false);
}
void test_math__test_within_macro(void) {
int16_t min;
int16_t max;
// Min and max are both positive
////////////////////////////////
min = 5;
max = 10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_b(WITHIN(7, min, max), true);
// Just out of bounds
cl_assert_equal_b(WITHIN(4, min, max), false);
cl_assert_equal_b(WITHIN(11, min, max), false);
// Negative out of bounds
cl_assert_equal_i(WITHIN(-5, min, max), false);
// Positive out of bounds
cl_assert_equal_i(WITHIN(0, min, max), false);
// Min negative, max positive
////////////////////////////////
min = -10;
max = 10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_i(WITHIN(-5, min, max), true);
cl_assert_equal_i(WITHIN(0, min, max), true);
cl_assert_equal_i(WITHIN(5, min, max), true);
// Just out of bounds
cl_assert_equal_i(WITHIN(-11, min, max), false);
cl_assert_equal_i(WITHIN(11, min, max), false);
// Min and max are both negative
////////////////////////////////
min = -20;
max = -10;
// Min and max themselves should satisfy WITHIN
cl_assert_equal_b(WITHIN(min, min, max), true);
cl_assert_equal_b(WITHIN(max, min, max), true);
// In the middle of the bounds
cl_assert_equal_i(WITHIN(-15, min, max), true);
// Just out of bounds
cl_assert_equal_i(WITHIN(-21, min, max), false);
cl_assert_equal_i(WITHIN(-9, min, max), false);
// Positive out of bounds
cl_assert_equal_i(WITHIN(0, min, max), false);
cl_assert_equal_i(<|fim_suffix|><|fim_middle|>WITHIN(5, min, max)<|endoftext|> |
|
masked_node | argument_list | tests/fw/services/test_pfs.c | ce Avail = %d\n", bytes_available);
uint8_t *bigbuf = (uint8_t *)calloc(large_file_size, 1);
uint16_t curr = 0;
for (int i = 0; i < 2; i++) {
snprintf(file_large, sizeof(file_large), "large%d", i);
for (int i = 0; i < large_file_size / 4; i++) {
*(((uint32_t *)((uint8_t *)bigbuf)) + i) = curr | (curr << 16);
curr++;
}
int fd = pfs_open(file_large, OP_FLAG_WRITE, FILE_TYPE_STATIC, large_file_size);
printf("the fd is: %d\n", fd);
cl_assert(fd >= 0);
cl_assert(pfs_write(fd, bigbuf, large_file_size) == large_file_size);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
free(bigbuf);
// now read back the large files
curr = 0;
for (int i = 0; i < 2; i++) {
snprintf(file_large, sizeof(file_large), "large%d", i);
int fd = pfs_open(file_large, OP_FLAG_READ, 0, 0);
cl_assert(fd >= 0);
size_t sz = pfs_get_file_size(fd);
cl_assert(sz == large_file_size);
uint8_t *b = calloc(sz, 1);
cl_assert(pfs_read(fd, b, sz) == sz);
for (int j = 0; j < large_file_size / 4; j++) {
uint32_t *val = ((uint32_t *)((uint8_t *)b)) + j;
cl_assert(*val == (curr | (curr << 16)));
curr++;
}
cl_assert(pfs_close(fd) == S_SUCCESS);
free(b);
}
}
void test_pfs__file_span_regions(void) {
pfs_format(false /* write erase headers */); // start with an empty flash
pfs_init(false);
char name[128];
snprintf(name, sizeof(name), "bigfile");
//Fill up entire memory section, subtract 32768 for header space.
int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, pfs_get_size() - (num_pages()*128));
printf("%d\n", pfs_get_size() - 1024);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
cl_assert(pfs_remove(name) == S_SUCCESS);
}
void test_pfs__active_regions(void) {
pfs_format(false);
cl_assert(!pfs_active_in_region(0, pfs_get_size()));
// erase every page and make sure pfs is active
pfs_format(true);
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// write something on every page and make sure pfs is active
char file_name[10];
for (int i = 0; i < num_pages(); i++) {
snprintf(file_name, sizeof(file_name), "file%d", i);
int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// delete every page and make sure pfs is active
for (int i = 0; i < num_pages(); i++) {
snprintf(file_name, sizeof(file_name), "file%d", i);
cl_assert(pfs_remove(file_name) == S_SUCCESS);
}
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// continuation page on region and make sure pfs is active
pfs_format(true);
int fd = pfs_open("testfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 68000);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
cl_assert(pfs_active_in_region(32000, 68000));
}
int run_full_flash_region_test(void) {
char name[128];
// assumes # pages is a multiple of 2
int st_val = 0;
const int f_size = (((PFS_SECTOR_SIZE * 2) - 400) / sizeof(st_val)) * sizeof(st_val);
int num_vals = f_size / sizeof(st_val);
int idx = 0;
int fd, rv;
while (true) {
snprintf(name, sizeof(name), "file%d", idx);
if ((fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, f_size)) < 0) {
break;
}
for (int i = 0; i < num_vals; i++) {
st_val = st_val + i;
rv = pfs_write(fd, (uint8_t *)&st_val, sizeof(st_val));
cl_assert_equal_i(rv, sizeof(st_val));
}
pfs_close(fd);
idx++;
}
cl_assert_equal_i((status_t)fd, E_OUT_OF_STORAGE);
// read back files to make sure they are all correct
st_val = 0;
for (int i = 0; i < idx; i++) {
snprintf(name, sizeof(name), "file%d", i);
if ((fd = pfs_open(name, OP_FLAG_READ, FILE_TYPE_STATIC, f_size)) < 0) {
break;
}
for (int j = 0; j < num_vals; j++) {
st_val = st_val + j;
int out_val;
rv = pfs_read(fd, (uint8_t *)&out_val, sizeof(out_val));
cl_assert_equal_i(rv, sizeof(st_val));
cl_assert_equal_i | ;
}
pfs_close(fd);
}
return (idx);
}
void test_pfs__out_of_space(void) {
pfs_format(false /* write erase headers */); // start with an empty flash
pfs_init(false);
int num_iters = 30;
for (int i = 0; i < num_iters; i++) {
int files_written = run_full_flash_region_test();
if ((i % 2) == 0) {
pfs_init(true); // simulate a reboot
}
// delete all files
for (int i = (files_written - 1); i >= 0; i--) {
char name[128];
snprintf(name, sizeof(name), "file%d", i);
cl_assert_equal_i(pfs_remove(name), S_SUCCESS);
}
}
}
void test_pfs__active_in_region(void) {
cl_assert(pfs_active_in_region(0, pfs_get_size()));
}
void test_pfs__get_size(void) {
cl_assert(pfs_get_size() == (ftl_get_size() - SECTOR_SIZE_BYTES));
}
void test_pfs__migration(void) {
// reset the flash
fake_spi_flash_cleanup();
fake_spi_flash_init(0, 0x1000000);
extern void ftl_force_version(int version_idx);
pfs_init(true);
ftl_force_version(1);
// simulate a migration by leaving leaving files in various states
// in the first region. Then try to add another region and confirm
// none of the files have been corrupted
char file_small[10];
char buf[50];
const int erase_count = 3;
for (int num_erases = 0; num_erases < erase_count; num_erases++) {
for (int i = 0; i < num_pages(); i++) {
snprintf(file_small, sizeof(file_small), "file%d", i);
snprintf(buf, sizeof(buf), "This is small buf %d!", i);
int len = strlen(buf);
int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, len);
cl_assert(fd >= 0);
cl_assert(pfs_write(fd, (uint8_t *)buf, len) == len);
cl_assert(pfs_close(fd) == S_SUCCESS);
if (num_erases != (erase_count - 1)) {
cl_assert(pfs_remove(file_small) == S_SUCCESS);
}
}
}
int original_page_count = num_pages();
ftl_populate_region_list();
// make sure something was added
PBL_LOG(LOG_LEVEL_DEBUG, "original pages %u, num pages: %u", original_page_count, num_pages());
cl_assert(original_page_count < num_pages());
for (int i = 0; i < original_page_count; i++) {
snprintf(file_small, sizeof(file_small), "file%d", i);
snprintf(buf, sizeof(buf), "This is small buf %d!", i);
int len = strlen(buf);
char rbuf[len];
int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, 0);
cl_assert(fd >= 0);
cl_assert_equal_i(pfs_read(fd, (uint8_t *)rbuf, len), len);
cl_assert(memcmp(rbuf, buf, len) == 0);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
}
static uint32_t s_watch_file_callback_called_count = 0;
static void prv_file_changed_callback(void *data) {
s_watch_file_callback_called_count++;
}
void test_pfs__watch_file_callbacks(void) {
const char* file_name = "newfile";
PFSCallbackHandle cb_handle = pfs_watch_file(file_name, prv_file_changed_callback,
FILE_CHANGED_EVENT_ALL, NULL);
// Callback should get invoked if we close with write access
s_watch_file_callback_called_count = 0;
int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 1);
// Callback should not get invoked if we close with read access
s_watch_file_callback_called_count = 0;
fd = pfs_open(file_name, OP_FLAG_READ, 0, 0);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 0);
// Callback should get invoked if we remove the file
s_watch_file_callback_called_count = 0;
pfs_remove(file_name);
cl_assert(s_watch_file_callback_called_count == 1);
pfs_unwatch_file(cb_handle);
// Callback should not get invoked anymore
s_watch_file_callback_called_count = 0;
fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 0);
}
extern status_t test_scan_for_last_written(void);
void test_pfs__last_written_page(void) {
pfs_format(true);
pfs_init(false | (out_val, st_val) | <|repo_name|>pebble
<|file_sep|>tests/fw/services/test_pfs.c
<|fim_prefix|>ce Avail = %d\n", bytes_available);
uint8_t *bigbuf = (uint8_t *)calloc(large_file_size, 1);
uint16_t curr = 0;
for (int i = 0; i < 2; i++) {
snprintf(file_large, sizeof(file_large), "large%d", i);
for (int i = 0; i < large_file_size / 4; i++) {
*(((uint32_t *)((uint8_t *)bigbuf)) + i) = curr | (curr << 16);
curr++;
}
int fd = pfs_open(file_large, OP_FLAG_WRITE, FILE_TYPE_STATIC, large_file_size);
printf("the fd is: %d\n", fd);
cl_assert(fd >= 0);
cl_assert(pfs_write(fd, bigbuf, large_file_size) == large_file_size);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
free(bigbuf);
// now read back the large files
curr = 0;
for (int i = 0; i < 2; i++) {
snprintf(file_large, sizeof(file_large), "large%d", i);
int fd = pfs_open(file_large, OP_FLAG_READ, 0, 0);
cl_assert(fd >= 0);
size_t sz = pfs_get_file_size(fd);
cl_assert(sz == large_file_size);
uint8_t *b = calloc(sz, 1);
cl_assert(pfs_read(fd, b, sz) == sz);
for (int j = 0; j < large_file_size / 4; j++) {
uint32_t *val = ((uint32_t *)((uint8_t *)b)) + j;
cl_assert(*val == (curr | (curr << 16)));
curr++;
}
cl_assert(pfs_close(fd) == S_SUCCESS);
free(b);
}
}
void test_pfs__file_span_regions(void) {
pfs_format(false /* write erase headers */); // start with an empty flash
pfs_init(false);
char name[128];
snprintf(name, sizeof(name), "bigfile");
//Fill up entire memory section, subtract 32768 for header space.
int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, pfs_get_size() - (num_pages()*128));
printf("%d\n", pfs_get_size() - 1024);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
cl_assert(pfs_remove(name) == S_SUCCESS);
}
void test_pfs__active_regions(void) {
pfs_format(false);
cl_assert(!pfs_active_in_region(0, pfs_get_size()));
// erase every page and make sure pfs is active
pfs_format(true);
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// write something on every page and make sure pfs is active
char file_name[10];
for (int i = 0; i < num_pages(); i++) {
snprintf(file_name, sizeof(file_name), "file%d", i);
int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// delete every page and make sure pfs is active
for (int i = 0; i < num_pages(); i++) {
snprintf(file_name, sizeof(file_name), "file%d", i);
cl_assert(pfs_remove(file_name) == S_SUCCESS);
}
cl_assert(pfs_active_in_region(0, pfs_get_size()));
// continuation page on region and make sure pfs is active
pfs_format(true);
int fd = pfs_open("testfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 68000);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
cl_assert(pfs_active_in_region(32000, 68000));
}
int run_full_flash_region_test(void) {
char name[128];
// assumes # pages is a multiple of 2
int st_val = 0;
const int f_size = (((PFS_SECTOR_SIZE * 2) - 400) / sizeof(st_val)) * sizeof(st_val);
int num_vals = f_size / sizeof(st_val);
int idx = 0;
int fd, rv;
while (true) {
snprintf(name, sizeof(name), "file%d", idx);
if ((fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, f_size)) < 0) {
break;
}
for (int i = 0; i < num_vals; i++) {
st_val = st_val + i;
rv = pfs_write(fd, (uint8_t *)&st_val, sizeof(st_val));
cl_assert_equal_i(rv, sizeof(st_val));
}
pfs_close(fd);
idx++;
}
cl_assert_equal_i((status_t)fd, E_OUT_OF_STORAGE);
// read back files to make sure they are all correct
st_val = 0;
for (int i = 0; i < idx; i++) {
snprintf(name, sizeof(name), "file%d", i);
if ((fd = pfs_open(name, OP_FLAG_READ, FILE_TYPE_STATIC, f_size)) < 0) {
break;
}
for (int j = 0; j < num_vals; j++) {
st_val = st_val + j;
int out_val;
rv = pfs_read(fd, (uint8_t *)&out_val, sizeof(out_val));
cl_assert_equal_i(rv, sizeof(st_val));
cl_assert_equal_i<|fim_suffix|>;
}
pfs_close(fd);
}
return (idx);
}
void test_pfs__out_of_space(void) {
pfs_format(false /* write erase headers */); // start with an empty flash
pfs_init(false);
int num_iters = 30;
for (int i = 0; i < num_iters; i++) {
int files_written = run_full_flash_region_test();
if ((i % 2) == 0) {
pfs_init(true); // simulate a reboot
}
// delete all files
for (int i = (files_written - 1); i >= 0; i--) {
char name[128];
snprintf(name, sizeof(name), "file%d", i);
cl_assert_equal_i(pfs_remove(name), S_SUCCESS);
}
}
}
void test_pfs__active_in_region(void) {
cl_assert(pfs_active_in_region(0, pfs_get_size()));
}
void test_pfs__get_size(void) {
cl_assert(pfs_get_size() == (ftl_get_size() - SECTOR_SIZE_BYTES));
}
void test_pfs__migration(void) {
// reset the flash
fake_spi_flash_cleanup();
fake_spi_flash_init(0, 0x1000000);
extern void ftl_force_version(int version_idx);
pfs_init(true);
ftl_force_version(1);
// simulate a migration by leaving leaving files in various states
// in the first region. Then try to add another region and confirm
// none of the files have been corrupted
char file_small[10];
char buf[50];
const int erase_count = 3;
for (int num_erases = 0; num_erases < erase_count; num_erases++) {
for (int i = 0; i < num_pages(); i++) {
snprintf(file_small, sizeof(file_small), "file%d", i);
snprintf(buf, sizeof(buf), "This is small buf %d!", i);
int len = strlen(buf);
int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, len);
cl_assert(fd >= 0);
cl_assert(pfs_write(fd, (uint8_t *)buf, len) == len);
cl_assert(pfs_close(fd) == S_SUCCESS);
if (num_erases != (erase_count - 1)) {
cl_assert(pfs_remove(file_small) == S_SUCCESS);
}
}
}
int original_page_count = num_pages();
ftl_populate_region_list();
// make sure something was added
PBL_LOG(LOG_LEVEL_DEBUG, "original pages %u, num pages: %u", original_page_count, num_pages());
cl_assert(original_page_count < num_pages());
for (int i = 0; i < original_page_count; i++) {
snprintf(file_small, sizeof(file_small), "file%d", i);
snprintf(buf, sizeof(buf), "This is small buf %d!", i);
int len = strlen(buf);
char rbuf[len];
int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, 0);
cl_assert(fd >= 0);
cl_assert_equal_i(pfs_read(fd, (uint8_t *)rbuf, len), len);
cl_assert(memcmp(rbuf, buf, len) == 0);
cl_assert(fd >= 0);
cl_assert(pfs_close(fd) == S_SUCCESS);
}
}
static uint32_t s_watch_file_callback_called_count = 0;
static void prv_file_changed_callback(void *data) {
s_watch_file_callback_called_count++;
}
void test_pfs__watch_file_callbacks(void) {
const char* file_name = "newfile";
PFSCallbackHandle cb_handle = pfs_watch_file(file_name, prv_file_changed_callback,
FILE_CHANGED_EVENT_ALL, NULL);
// Callback should get invoked if we close with write access
s_watch_file_callback_called_count = 0;
int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 1);
// Callback should not get invoked if we close with read access
s_watch_file_callback_called_count = 0;
fd = pfs_open(file_name, OP_FLAG_READ, 0, 0);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 0);
// Callback should get invoked if we remove the file
s_watch_file_callback_called_count = 0;
pfs_remove(file_name);
cl_assert(s_watch_file_callback_called_count == 1);
pfs_unwatch_file(cb_handle);
// Callback should not get invoked anymore
s_watch_file_callback_called_count = 0;
fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10);
cl_assert(fd >= 0);
pfs_close(fd);
cl_assert(s_watch_file_callback_called_count == 0);
}
extern status_t test_scan_for_last_written(void);
void test_pfs__last_written_page(void) {
pfs_format(true);
pfs_init(false<|fim_middle|>(out_val, st_val)<|endoftext|> |
masked_node | call_expression | src/fw/services/normal/activity/activity_insights.c | int32_t sleep_total_seconds,
ActivityScalarStore sleep_average_seconds, Uuid *uuid) {
prv_generate_sleep_pin_strings(sleep_enter_seconds, sleep_exit_seconds, sleep_total_seconds);
// Insert or update the pin
return prv_push_summary_pin(pin_time_utc, now_utc, uuid, sleep_total_seconds,
sleep_average_seconds, &SLEEP_SUMMARY_PIN_CONFIG);
}
// -----------------------------------------------------------------------------------------
static NOINLINE TimelineItem *prv_create_nap_pin(time_t now_utc, ActivitySession *session) {
AttributeList pin_attr_list = {};
attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconPin, TIMELINE_RESOURCE_SLEEP);
attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthInsightType,
ActivityInsightType_ActivitySessionNap);
attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthActivityType,
ActivitySessionType_Nap);
attribute_list_add_uint32(&pin_attr_list, AttributeIdTimestamp, session->start_utc);
attribute_list_add_cstring(&pin_attr_list, AttributeIdShortTitle,
i18n_get("Nap Time", &pin_attr_list));
// Fits the maximum strings "10H 30M of sleep", "10:00AM - 11:00PM" and i18n variants
const size_t max_attr_length = 64;
char *elapsed = kernel_zalloc_check(max_attr_length);
char *short_subtitle = kernel_zalloc_check(max_attr_length);
const uint32_t duration_s = session->length_min * SECONDS_PER_MINUTE;
health_util_format_hours_and_minutes(elapsed, max_attr_length, duration_s, &pin_attr_list);
const char *short_subtitle_fmt = i18n_get("%s of sleep", &pin_attr_list); /// "10H 30M of sleep"
snprintf(short_subtitle, max_attr_length, short_subtitle_fmt, elapsed);
attribute_list_add_cstring(&pin_attr_list, AttributeIdShortSubtitle, short_subtitle);
attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, elapsed);
const char *title_i18n = PBL_IF_RECT_ELSE(i18n_noop("YOU NAPPED"),
i18n_noop("Of napping"));
attribute_list_add_cstring(&pin_attr_list,
PBL_IF_RECT_ELSE(AttributeIdTitle, AttributeIdLocationName),
i18n_get(title_i18n, &pin_attr_list));
char *start_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH);
char *end_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH);
char *time_range = kernel_zalloc_check(max_attr_length);
const char *time_range_fmt = i18n_get("%s - %s", &pin_attr_list); /// "10:00AM - 11:00PM"
clock_copy_time_string_timestamp(start_time, TIME_STRING_TIME_LENGTH, session->start_utc);
clock_copy_time_string_timestamp(end_time, TIME_STRING_TIME_LENGTH,
session->start_utc + duration_s);
snprintf(time_range, max_attr_length, time_range_fmt, start_time, end_time);
attribute_list_add_cstring(&pin_attr_list,
PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle),
time_range);
// Don't display the time in the title
attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None);
attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc);
attribute_list_add_uint8(&pin_attr_list, AttributeIdBgColor, GColorSunsetOrangeARGB8);
const int num_responses = 2;
ResponseItem *response_items = kernel_zalloc_check(num_responses * sizeof(ResponseItem));
response_items[0] = (ResponseItem) {
.type = ActivityInsightResponseTypePositive,
.text = i18n_noop("I feel great!"),
};
response_items[1] = (ResponseItem) {
.type = ActivityInsightResponseTypeNegative,
.text = i18n_noop("I need more"),
};
TimelineItem *item = prv_create_pin_with_response_items(
session->start_utc, now_utc, session->length_min, LayoutIdWeather, &pin_attr_list,
HealthCardType_Sleep, num_responses, response_items);
kernel_free(response_items);
kernel_free(time_range);
| ;
kernel_free(start_time);
kernel_free(short_subtitle);
kernel_free(elapsed);
i18n_free_all(&pin_attr_list);
attribute_list_destroy_list(&pin_attr_list);
return item;
}
// ------------------------------------------------------------------------------------------------
// Creates a notification to notify the user of the nap session
static void prv_push_nap_session_notification(time_t notif_time, ActivitySession *session,
Uuid *pin_uuid) {
const int hours = session->length_min / MINUTES_PER_HOUR;
const int minutes = session->length_min % MINUTES_PER_HOUR;
// Enough to fit the filled out format string below and i18n variants
const int max_notif_length = 128;
char *body = kernel_malloc_check(max_notif_length);
snprintf(body, max_notif_length,
i18n_get("Aren't naps great? You knocked out for %dH %dM!", body),
hours, minutes);
i18n_free_all(body);
const NotificationConfig config = {
.notif_time = notif_time,
.session = session,
.insight_type = ActivityInsightType_ActivitySessionNap,
.icon_id = TIMELINE_RESOURCE_SLEEP,
.body = body,
.open_pin = {
.enabled = true,
.uuid = pin_uuid,
},
.response = {
.enabled = true,
.type = ActivityInsightResponseTypeMisclassified,
.title = i18n_noop("I didn't nap!?"),
},
};
prv_create_and_push_notification(&config);
kernel_free(body);
}
// -----------------------------------------------------------------------------------------
static void prv_push_nap_session(time_t now_utc, ActivitySession *session) {
Uuid pin_uuid = UUID_INVALID;
TimelineItem *pin_item = prv_create_nap_pin(now_utc, session);
if (prv_push_pin(pin_item, &pin_uuid) &&
activity_prefs_sleep_insights_are_enabled()) {
prv_push_nap_session_notification(now_utc, session, &pin_uuid);
}
}
// -----------------------------------------------------------------------------------------
static void prv_do_nap_session(time_t now_utc, ActivitySession *session) {
if (s_nap_pin_state.last_triggered_utc >= session->start_utc) {
INSIGHTS_LOG_DEBUG("Not adding nap pin - already added");
return;
}
s_nap_pin_state.last_triggered_utc = session->start_utc;
prv_save_state(ActivitySettingsKeyInsightNapSessionTime,
&s_nap_pin_state.last_triggered_utc,
sizeof(s_nap_pin_state.last_triggered_utc));
prv_push_nap_session(now_utc, session);
}
// -----------------------------------------------------------------------------------------
static void prv_do_sleep_notification(time_t now_utc, time_t sleep_exit_utc,
int32_t sleep_total_seconds) {
if (!activity_prefs_sleep_insights_are_enabled()) {
return;
}
if (s_sleep_pin_state.notified) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - already notified");
return;
}
// Notify about the pin after a certain amount of time
const time_t since_exited = now_utc - sleep_exit_utc;
if (since_exited < s_sleep_summary_settings.summary.sleep.trigger_notif_seconds) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not trigger time yet (%ld)", since_exited);
return;
}
// Notify only if they are above the minimum activity since the delay time
const int trigger_active_minutes =
s_sleep_summary_settings.summary.sleep.trigger_notif_active_minutes;
if (s_sleep_pin_state.active_minutes < trigger_active_minutes) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not active enough (%d < %d)",
s_sleep_pin_state.active_minutes, trigger_active_minutes);
return;
}
s_sleep_pin_state.notified = true;
prv_push_sleep_summary_notification(now_utc, sleep_total_seconds, s_sleep_stats.mean,
VARIANT_RANDOM);
prv_save_state(ActivitySettingsKeyInsightSleepSummaryState, &s_sleep_pin_state,
sizeof(s_sleep_pin_state));
}
// -----------------------------------------------------------------------------------------
static void prv | kernel_free(end_time) | <|repo_name|>pebble
<|file_sep|>src/fw/services/normal/activity/activity_insights.c
<|fim_prefix|> int32_t sleep_total_seconds,
ActivityScalarStore sleep_average_seconds, Uuid *uuid) {
prv_generate_sleep_pin_strings(sleep_enter_seconds, sleep_exit_seconds, sleep_total_seconds);
// Insert or update the pin
return prv_push_summary_pin(pin_time_utc, now_utc, uuid, sleep_total_seconds,
sleep_average_seconds, &SLEEP_SUMMARY_PIN_CONFIG);
}
// -----------------------------------------------------------------------------------------
static NOINLINE TimelineItem *prv_create_nap_pin(time_t now_utc, ActivitySession *session) {
AttributeList pin_attr_list = {};
attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconPin, TIMELINE_RESOURCE_SLEEP);
attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthInsightType,
ActivityInsightType_ActivitySessionNap);
attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthActivityType,
ActivitySessionType_Nap);
attribute_list_add_uint32(&pin_attr_list, AttributeIdTimestamp, session->start_utc);
attribute_list_add_cstring(&pin_attr_list, AttributeIdShortTitle,
i18n_get("Nap Time", &pin_attr_list));
// Fits the maximum strings "10H 30M of sleep", "10:00AM - 11:00PM" and i18n variants
const size_t max_attr_length = 64;
char *elapsed = kernel_zalloc_check(max_attr_length);
char *short_subtitle = kernel_zalloc_check(max_attr_length);
const uint32_t duration_s = session->length_min * SECONDS_PER_MINUTE;
health_util_format_hours_and_minutes(elapsed, max_attr_length, duration_s, &pin_attr_list);
const char *short_subtitle_fmt = i18n_get("%s of sleep", &pin_attr_list); /// "10H 30M of sleep"
snprintf(short_subtitle, max_attr_length, short_subtitle_fmt, elapsed);
attribute_list_add_cstring(&pin_attr_list, AttributeIdShortSubtitle, short_subtitle);
attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, elapsed);
const char *title_i18n = PBL_IF_RECT_ELSE(i18n_noop("YOU NAPPED"),
i18n_noop("Of napping"));
attribute_list_add_cstring(&pin_attr_list,
PBL_IF_RECT_ELSE(AttributeIdTitle, AttributeIdLocationName),
i18n_get(title_i18n, &pin_attr_list));
char *start_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH);
char *end_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH);
char *time_range = kernel_zalloc_check(max_attr_length);
const char *time_range_fmt = i18n_get("%s - %s", &pin_attr_list); /// "10:00AM - 11:00PM"
clock_copy_time_string_timestamp(start_time, TIME_STRING_TIME_LENGTH, session->start_utc);
clock_copy_time_string_timestamp(end_time, TIME_STRING_TIME_LENGTH,
session->start_utc + duration_s);
snprintf(time_range, max_attr_length, time_range_fmt, start_time, end_time);
attribute_list_add_cstring(&pin_attr_list,
PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle),
time_range);
// Don't display the time in the title
attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None);
attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc);
attribute_list_add_uint8(&pin_attr_list, AttributeIdBgColor, GColorSunsetOrangeARGB8);
const int num_responses = 2;
ResponseItem *response_items = kernel_zalloc_check(num_responses * sizeof(ResponseItem));
response_items[0] = (ResponseItem) {
.type = ActivityInsightResponseTypePositive,
.text = i18n_noop("I feel great!"),
};
response_items[1] = (ResponseItem) {
.type = ActivityInsightResponseTypeNegative,
.text = i18n_noop("I need more"),
};
TimelineItem *item = prv_create_pin_with_response_items(
session->start_utc, now_utc, session->length_min, LayoutIdWeather, &pin_attr_list,
HealthCardType_Sleep, num_responses, response_items);
kernel_free(response_items);
kernel_free(time_range);
<|fim_suffix|>;
kernel_free(start_time);
kernel_free(short_subtitle);
kernel_free(elapsed);
i18n_free_all(&pin_attr_list);
attribute_list_destroy_list(&pin_attr_list);
return item;
}
// ------------------------------------------------------------------------------------------------
// Creates a notification to notify the user of the nap session
static void prv_push_nap_session_notification(time_t notif_time, ActivitySession *session,
Uuid *pin_uuid) {
const int hours = session->length_min / MINUTES_PER_HOUR;
const int minutes = session->length_min % MINUTES_PER_HOUR;
// Enough to fit the filled out format string below and i18n variants
const int max_notif_length = 128;
char *body = kernel_malloc_check(max_notif_length);
snprintf(body, max_notif_length,
i18n_get("Aren't naps great? You knocked out for %dH %dM!", body),
hours, minutes);
i18n_free_all(body);
const NotificationConfig config = {
.notif_time = notif_time,
.session = session,
.insight_type = ActivityInsightType_ActivitySessionNap,
.icon_id = TIMELINE_RESOURCE_SLEEP,
.body = body,
.open_pin = {
.enabled = true,
.uuid = pin_uuid,
},
.response = {
.enabled = true,
.type = ActivityInsightResponseTypeMisclassified,
.title = i18n_noop("I didn't nap!?"),
},
};
prv_create_and_push_notification(&config);
kernel_free(body);
}
// -----------------------------------------------------------------------------------------
static void prv_push_nap_session(time_t now_utc, ActivitySession *session) {
Uuid pin_uuid = UUID_INVALID;
TimelineItem *pin_item = prv_create_nap_pin(now_utc, session);
if (prv_push_pin(pin_item, &pin_uuid) &&
activity_prefs_sleep_insights_are_enabled()) {
prv_push_nap_session_notification(now_utc, session, &pin_uuid);
}
}
// -----------------------------------------------------------------------------------------
static void prv_do_nap_session(time_t now_utc, ActivitySession *session) {
if (s_nap_pin_state.last_triggered_utc >= session->start_utc) {
INSIGHTS_LOG_DEBUG("Not adding nap pin - already added");
return;
}
s_nap_pin_state.last_triggered_utc = session->start_utc;
prv_save_state(ActivitySettingsKeyInsightNapSessionTime,
&s_nap_pin_state.last_triggered_utc,
sizeof(s_nap_pin_state.last_triggered_utc));
prv_push_nap_session(now_utc, session);
}
// -----------------------------------------------------------------------------------------
static void prv_do_sleep_notification(time_t now_utc, time_t sleep_exit_utc,
int32_t sleep_total_seconds) {
if (!activity_prefs_sleep_insights_are_enabled()) {
return;
}
if (s_sleep_pin_state.notified) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - already notified");
return;
}
// Notify about the pin after a certain amount of time
const time_t since_exited = now_utc - sleep_exit_utc;
if (since_exited < s_sleep_summary_settings.summary.sleep.trigger_notif_seconds) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not trigger time yet (%ld)", since_exited);
return;
}
// Notify only if they are above the minimum activity since the delay time
const int trigger_active_minutes =
s_sleep_summary_settings.summary.sleep.trigger_notif_active_minutes;
if (s_sleep_pin_state.active_minutes < trigger_active_minutes) {
INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not active enough (%d < %d)",
s_sleep_pin_state.active_minutes, trigger_active_minutes);
return;
}
s_sleep_pin_state.notified = true;
prv_push_sleep_summary_notification(now_utc, sleep_total_seconds, s_sleep_stats.mean,
VARIANT_RANDOM);
prv_save_state(ActivitySettingsKeyInsightSleepSummaryState, &s_sleep_pin_state,
sizeof(s_sleep_pin_state));
}
// -----------------------------------------------------------------------------------------
static void prv<|fim_middle|>kernel_free(end_time)<|endoftext|> |
prefix_only | argument_list | src/fw/apps/core_apps/spinner_ui_window.c | f 1.
// This means that the the lag occurs once less frequently and is less noticable
#define LOOPS_PER_ANIMATION 10
#define LOOP_DURATION_MS 1500
static void prv_draw_spinner_circles(Layer *layer, GContext* ctx) {
// Drawing the circles with aa is just too slow and we end up backing up the rest of the system.
// See PBL-16184
graphics_context_set_antialiased(ctx, false);
SpinnerUIData *data = window_get_user_data(layer_get_window(layer));
// This is the background image's circle.
#if PLATFORM_ROBERT || PLATFORM_CALCULUS
const unsigned int center_of_circle_y_val = 103;
#else
const unsigned int center_of_circle_y_val = PBL_IF_RECT_ELSE(72, layer->bounds.size.h / 2);
#endif
const unsigned int radius_of_path = 37;
const unsigned int radius_of_spinner_circles = 9;
const GPoint circle_center_point = GPoint(layer->bounds.size.w / 2, center_of_circle_y_val);
const unsigned int angle = (TRIG_MAX_ANGLE * data->cur_distance_normalized *
LOOPS_PER_ANIMATION) / ANIMATION_NORMALIZED_MAX;
const GPoint circle1_location = {
.x = (sin_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.x,
.y = (-cos_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.y,
};
const GPoint circle2_location = {
.x = (-sin_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.x,
.y = (-cos_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.y,
};
graphics_context_set_fill_color(ctx, data->spinner_color);
graphics_context_set_stroke_color(ctx, GColorBlack);
graphics_fill_circle(ctx, circle1_location, radius_of_spinner_circles);
graphics_draw_circle(ctx, circle1_location, radius_of_spinner_circles);
graphics_fill_circle(ctx, circle2_location, radius_of_spinner_circles);
graphics_draw_circle(ctx, circle2_location, radius_of_spinner_circles);
}
static void prv_anim_impl(struct Animation *animation,
const AnimationProgress distance_normalized) {
SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation);
// We need to artificially limit how frequent we attempt to update the screen. If we update
// it too fast the thing we wanted to do in the background never gets done. This isn't quite
// ideal, as around 60 steps is when things are actually smooth, but 60 is too fast and does
// restrict the speed of our core dump. See PBL-16184
const uint32_t steps_per_loop = 25;
const int32_t min_delta = (ANIMATION_NORMALIZED_MAX/LOOPS_PER_ANIMATION) / steps_per_loop;
if (data->cur_distance_normalized + min_delta < distance_normalized) {
data->cur_distance_normalized = distance_normalized;
layer_mark_dirty(&data->anim_layer);
}
}
static void prv_anim_stopped(Animation *animation, bool finished, void *context) {
SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation);
if (!data->should_cancel_animation) {
data->cur_distance_normalized = 0;
animation_schedule(property_animation_get_animation(data->spinner_animation));
}
}
////////////////////////////////////////////////////////////
// Window loading, unloading, initializing
static void prv_window_unload_handler(Window* window) {
SpinnerUIData *data = window_get_user_data(window);
if (data) {
gbitmap_destroy(data->bitmap);
data->should_cancel_animation = true;
property_animation_destroy(data->spinner_animation);
kernel_free(data);
}
}
static void prv_window_load_handler(Window* window) {
SpinnerUIData *data = window_get_user_data(window);
GRect spinner_bounds = window->layer.bounds;
spinner_bounds.origin.y += PBL_IF_RECT_ELSE(0, 10);
window_set_background_color(window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite));
BitmapLayer *bitmap_layer = &data->bitmap_layer;
bitmap_layer_init(bitmap_layer, &window->layer.bounds);
bitmap_layer_set_alignment(bitmap_layer, PBL_IF_RECT_ELSE(GAlignTopLeft, GAlignCenter));
layer_set_frame(&bitmap_layer->layer, &spinner_bounds);
data->bitmap = gbitmap_create_with_resource | (RESOURCE_ID_SPINNER_BACKGROUND) | <|repo_name|>pebble
<|file_sep|>src/fw/apps/core_apps/spinner_ui_window.c
<|fim_prefix|>f 1.
// This means that the the lag occurs once less frequently and is less noticable
#define LOOPS_PER_ANIMATION 10
#define LOOP_DURATION_MS 1500
static void prv_draw_spinner_circles(Layer *layer, GContext* ctx) {
// Drawing the circles with aa is just too slow and we end up backing up the rest of the system.
// See PBL-16184
graphics_context_set_antialiased(ctx, false);
SpinnerUIData *data = window_get_user_data(layer_get_window(layer));
// This is the background image's circle.
#if PLATFORM_ROBERT || PLATFORM_CALCULUS
const unsigned int center_of_circle_y_val = 103;
#else
const unsigned int center_of_circle_y_val = PBL_IF_RECT_ELSE(72, layer->bounds.size.h / 2);
#endif
const unsigned int radius_of_path = 37;
const unsigned int radius_of_spinner_circles = 9;
const GPoint circle_center_point = GPoint(layer->bounds.size.w / 2, center_of_circle_y_val);
const unsigned int angle = (TRIG_MAX_ANGLE * data->cur_distance_normalized *
LOOPS_PER_ANIMATION) / ANIMATION_NORMALIZED_MAX;
const GPoint circle1_location = {
.x = (sin_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.x,
.y = (-cos_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.y,
};
const GPoint circle2_location = {
.x = (-sin_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.x,
.y = (-cos_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.y,
};
graphics_context_set_fill_color(ctx, data->spinner_color);
graphics_context_set_stroke_color(ctx, GColorBlack);
graphics_fill_circle(ctx, circle1_location, radius_of_spinner_circles);
graphics_draw_circle(ctx, circle1_location, radius_of_spinner_circles);
graphics_fill_circle(ctx, circle2_location, radius_of_spinner_circles);
graphics_draw_circle(ctx, circle2_location, radius_of_spinner_circles);
}
static void prv_anim_impl(struct Animation *animation,
const AnimationProgress distance_normalized) {
SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation);
// We need to artificially limit how frequent we attempt to update the screen. If we update
// it too fast the thing we wanted to do in the background never gets done. This isn't quite
// ideal, as around 60 steps is when things are actually smooth, but 60 is too fast and does
// restrict the speed of our core dump. See PBL-16184
const uint32_t steps_per_loop = 25;
const int32_t min_delta = (ANIMATION_NORMALIZED_MAX/LOOPS_PER_ANIMATION) / steps_per_loop;
if (data->cur_distance_normalized + min_delta < distance_normalized) {
data->cur_distance_normalized = distance_normalized;
layer_mark_dirty(&data->anim_layer);
}
}
static void prv_anim_stopped(Animation *animation, bool finished, void *context) {
SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation);
if (!data->should_cancel_animation) {
data->cur_distance_normalized = 0;
animation_schedule(property_animation_get_animation(data->spinner_animation));
}
}
////////////////////////////////////////////////////////////
// Window loading, unloading, initializing
static void prv_window_unload_handler(Window* window) {
SpinnerUIData *data = window_get_user_data(window);
if (data) {
gbitmap_destroy(data->bitmap);
data->should_cancel_animation = true;
property_animation_destroy(data->spinner_animation);
kernel_free(data);
}
}
static void prv_window_load_handler(Window* window) {
SpinnerUIData *data = window_get_user_data(window);
GRect spinner_bounds = window->layer.bounds;
spinner_bounds.origin.y += PBL_IF_RECT_ELSE(0, 10);
window_set_background_color(window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite));
BitmapLayer *bitmap_layer = &data->bitmap_layer;
bitmap_layer_init(bitmap_layer, &window->layer.bounds);
bitmap_layer_set_alignment(bitmap_layer, PBL_IF_RECT_ELSE(GAlignTopLeft, GAlignCenter));
layer_set_frame(&bitmap_layer->layer, &spinner_bounds);
data->bitmap = gbitmap_create_with_resource<|fim_suffix|><|fim_middle|>(RESOURCE_ID_SPINNER_BACKGROUND)<|endoftext|> |
|
masked_node | compound_statement | src/fw/drivers/backlight.c | | | | | | | | |
// | | | | | | | |
// ------- ------- ------- --------
//
// The resulting waveform has a frequency of PWM_OUTPUT_FREQUENCY_HZ. Inside each period, the timer
// counts up to TIMER_PERIOD_RESOLUTION. This means the counter increments at a rate of
// PWM_OUTPUT_FREQUENCY_HZ * TIMER_PERIOD_RESOLUTION, which is the frequency that our timer
// prescalar has to calculate. The duty cycle is defined by the TIM_Pulse parameter, which
// controls after which counter value the output waveform will become active. For example, a
// TIM_Pulse value of TIMER_PERIOD_RESOLUTION / 4 will result in an output waveform that will go
// active after 25% of it's period has elapsed.
//! The counter reload value. The timer will count from 0 to this value and then reset again.
//! The TIM_Pulse member below controls for how many of these counts the resulting PWM signal is
//! active for.
static const uint32_t TIMER_PERIOD_RESOLUTION = 1024;
//! The number of periods we have per second.
//! Note that we want BOARD_CONFIG_BACKLIGHT.timer.peripheral to have as short a period as
//! possible for power reasons.
static const uint32_t PWM_OUTPUT_FREQUENCY_HZ = 256;
static bool s_initialized = false;
static bool s_backlight_pwm_enabled = false;
//! Bitmask of who wants to hold the LED enable on.
//! see \ref led_enable, \ref led_disable, \ref LEDEnabler
static uint32_t s_led_enable;
static void prv_backlight_pwm_enable(bool on) {
pwm_enable(&BOARD_CONFIG_BACKLIGHT.pwm, on);
if (on != s_backlight_pwm_enabled) {
if (on) {
stop_mode_disable(InhibitorBacklight);
} else {
stop_mode_enable(InhibitorBacklight);
}
}
s_backlight_pwm_enabled = on;
}
void backlight_init(void) {
if (s_initialized) {
return;
}
s_led_enable = 0;
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) {
periph_config_acquire_lock();
gpio_output_init(&BOARD_CONFIG_BACKLIGHT.ctl, GPIO_OType_PP, GPIO_Speed_2MHz);
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false);
periph_config_release_lock();
s_initialized = true;
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) {
periph_config_acquire_lock();
pwm_init(&BOARD_CONFIG_BACKLIGHT.pwm,
TIMER_PERIOD_RESOLUTION,
TIMER_PERIOD_RESOLUTION * PWM_OUTPUT_FREQUENCY_HZ);
periph_config_release_lock();
s_initialized = true;
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) {
led_controller_init();
s_initialized = true;
}
}
// TODO: PBL-36077 Move to a generic 4v5 enable
void led_enable(LEDEnabler enabler) {
if (s_led_enable == 0) {
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, true);
}
s_led_enable |= enabler;
}
// TODO: PBL-36077 Move to a generic 4v5 disable
void led_disable(LEDEnabler enabler) {
s_led_enable &= ~enabler;
if (s_led_enable == 0) {
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false);
}
}
void backlight_set_brightness(uint16_t brightness) {
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) {
if (brightness == 0) {
led_disable(LEDEnablerBacklight);
} else {
led_enable(LEDEnablerBacklight);
}
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) {
if (brightness == 0) {
if (s_backlight_pwm_enabled) {
prv_backlight_pwm_enable(false);
}
PWR_TRACK_BACKLIGHT("OFF", PWM_OUTPUT_FREQUENCY_HZ, 0);
} else |
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) {
led_controller_backlight_set_brightness(brightness >> 8);
}
}
void command_backlight_ctl(const char *arg) {
const int bright_percent = atoi(arg);
if (bright_percent < 0 || bright_percent > 100) {
prompt_send_response("Invalid Brightness");
return;
}
backlight_set_brightness((BACKLIGHT_BRIGHTNESS_MAX * bright_percent) / 100);
prompt_send_response("OK");
}
| {
if (!s_backlight_pwm_enabled) {
prv_backlight_pwm_enable(true);
}
// By setting higher values in the TIM_Pulse register, we're causing the output waveform
// to be low for a longer period of time, which causes the backlight to be brighter.
//
// The brightness value has a range of 0 to 0x3fff which is 2^15. The period of the timer
// counter is 2^10. We want to rescale the brightness range into a subset of the timer
// counter range. Different boards will have a different duty cycle that represent the
// "fully on" state.
const uint32_t pwm_scaling_factor = BACKLIGHT_BRIGHTNESS_MAX / TIMER_PERIOD_RESOLUTION;
const uint32_t desired_duty_cycle = brightness * BOARD_CONFIG.backlight_max_duty_cycle_percent
/ pwm_scaling_factor / 100;
pwm_set_duty_cycle(&BOARD_CONFIG_BACKLIGHT.pwm, desired_duty_cycle);
PWR_TRACK_BACKLIGHT("ON", PWM_OUTPUT_FREQUENCY_HZ,
(desired_duty_cycle * 100) / TIMER_PERIOD_RESOLUTION);
} | <|repo_name|>pebble
<|file_sep|>src/fw/drivers/backlight.c
<|fim_prefix|> | | | | | | | |
// | | | | | | | |
// ------- ------- ------- --------
//
// The resulting waveform has a frequency of PWM_OUTPUT_FREQUENCY_HZ. Inside each period, the timer
// counts up to TIMER_PERIOD_RESOLUTION. This means the counter increments at a rate of
// PWM_OUTPUT_FREQUENCY_HZ * TIMER_PERIOD_RESOLUTION, which is the frequency that our timer
// prescalar has to calculate. The duty cycle is defined by the TIM_Pulse parameter, which
// controls after which counter value the output waveform will become active. For example, a
// TIM_Pulse value of TIMER_PERIOD_RESOLUTION / 4 will result in an output waveform that will go
// active after 25% of it's period has elapsed.
//! The counter reload value. The timer will count from 0 to this value and then reset again.
//! The TIM_Pulse member below controls for how many of these counts the resulting PWM signal is
//! active for.
static const uint32_t TIMER_PERIOD_RESOLUTION = 1024;
//! The number of periods we have per second.
//! Note that we want BOARD_CONFIG_BACKLIGHT.timer.peripheral to have as short a period as
//! possible for power reasons.
static const uint32_t PWM_OUTPUT_FREQUENCY_HZ = 256;
static bool s_initialized = false;
static bool s_backlight_pwm_enabled = false;
//! Bitmask of who wants to hold the LED enable on.
//! see \ref led_enable, \ref led_disable, \ref LEDEnabler
static uint32_t s_led_enable;
static void prv_backlight_pwm_enable(bool on) {
pwm_enable(&BOARD_CONFIG_BACKLIGHT.pwm, on);
if (on != s_backlight_pwm_enabled) {
if (on) {
stop_mode_disable(InhibitorBacklight);
} else {
stop_mode_enable(InhibitorBacklight);
}
}
s_backlight_pwm_enabled = on;
}
void backlight_init(void) {
if (s_initialized) {
return;
}
s_led_enable = 0;
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) {
periph_config_acquire_lock();
gpio_output_init(&BOARD_CONFIG_BACKLIGHT.ctl, GPIO_OType_PP, GPIO_Speed_2MHz);
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false);
periph_config_release_lock();
s_initialized = true;
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) {
periph_config_acquire_lock();
pwm_init(&BOARD_CONFIG_BACKLIGHT.pwm,
TIMER_PERIOD_RESOLUTION,
TIMER_PERIOD_RESOLUTION * PWM_OUTPUT_FREQUENCY_HZ);
periph_config_release_lock();
s_initialized = true;
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) {
led_controller_init();
s_initialized = true;
}
}
// TODO: PBL-36077 Move to a generic 4v5 enable
void led_enable(LEDEnabler enabler) {
if (s_led_enable == 0) {
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, true);
}
s_led_enable |= enabler;
}
// TODO: PBL-36077 Move to a generic 4v5 disable
void led_disable(LEDEnabler enabler) {
s_led_enable &= ~enabler;
if (s_led_enable == 0) {
gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false);
}
}
void backlight_set_brightness(uint16_t brightness) {
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) {
if (brightness == 0) {
led_disable(LEDEnablerBacklight);
} else {
led_enable(LEDEnablerBacklight);
}
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) {
if (brightness == 0) {
if (s_backlight_pwm_enabled) {
prv_backlight_pwm_enable(false);
}
PWR_TRACK_BACKLIGHT("OFF", PWM_OUTPUT_FREQUENCY_HZ, 0);
} else <|fim_suffix|>
}
if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) {
led_controller_backlight_set_brightness(brightness >> 8);
}
}
void command_backlight_ctl(const char *arg) {
const int bright_percent = atoi(arg);
if (bright_percent < 0 || bright_percent > 100) {
prompt_send_response("Invalid Brightness");
return;
}
backlight_set_brightness((BACKLIGHT_BRIGHTNESS_MAX * bright_percent) / 100);
prompt_send_response("OK");
}
<|fim_middle|>{
if (!s_backlight_pwm_enabled) {
prv_backlight_pwm_enable(true);
}
// By setting higher values in the TIM_Pulse register, we're causing the output waveform
// to be low for a longer period of time, which causes the backlight to be brighter.
//
// The brightness value has a range of 0 to 0x3fff which is 2^15. The period of the timer
// counter is 2^10. We want to rescale the brightness range into a subset of the timer
// counter range. Different boards will have a different duty cycle that represent the
// "fully on" state.
const uint32_t pwm_scaling_factor = BACKLIGHT_BRIGHTNESS_MAX / TIMER_PERIOD_RESOLUTION;
const uint32_t desired_duty_cycle = brightness * BOARD_CONFIG.backlight_max_duty_cycle_percent
/ pwm_scaling_factor / 100;
pwm_set_duty_cycle(&BOARD_CONFIG_BACKLIGHT.pwm, desired_duty_cycle);
PWR_TRACK_BACKLIGHT("ON", PWM_OUTPUT_FREQUENCY_HZ,
(desired_duty_cycle * 100) / TIMER_PERIOD_RESOLUTION);
}<|endoftext|> |
masked_node | compound_statement | tests/fw/ui/test_text_layer.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "clar.h"
#include "applib/ui/text_layer.h"
// Stubs
/////////////////////
#include "stubs_app_state.h"
#include "stubs_graphics.h"
#include "stubs_heap.h"
#include "stubs_logging.h"
#include "stubs_passert.h"
#include "stubs_pbl_malloc.h"
#include "stubs_pebble_tasks.h"
#include "stubs_process_manager.h"
#include "stubs_system_theme.h"
#include "stubs_ui_window.h"
#include "stubs_unobstructed_area.h"
GFont fonts_get_system_font(const char *font_key) |
void graphics_context_set_fill_color(GContext* ctx, GColor color){}
void graphics_context_set_text_color(GContext* ctx, GColor color){}
// Fakes
////////////////////////
#define MOCKED_CREATED_LAYOUT (GTextLayoutCacheRef)123456
void graphics_text_layout_cache_init(GTextLayoutCacheRef *layout_cache) {
*layout_cache = MOCKED_CREATED_LAYOUT;
}
void graphics_text_layout_cache_deinit(GTextLayoutCacheRef *layout_cache) {}
void graphics_text_layout_set_line_spacing_delta(GTextLayoutCacheRef layout, int16_t delta) {}
int16_t graphics_text_layout_get_line_spacing_delta(const GTextLayoutCacheRef layout) {
return 0;
}
GSize graphics_text_layout_get_max_used_size(GContext *ctx, const char *text,
GFont const font, const GRect box,
const GTextOverflowMode overflow_mode,
const GTextAlignment alignment,
GTextLayoutCacheRef layout) {
return GSizeZero;
}
typedef struct {
struct {
GTextLayoutCacheRef layout;
} disable_text_flow;
struct {
GTextLayoutCacheRef layout;
uint8_t inset;
} enable_text_flow;
struct {
GTextLayoutCacheRef layout;
} disable_paging;
struct {
GTextLayoutCacheRef layout;
GPoint origin;
GRect paging;
} enable_paging;
} MockValues;
static MockValues s_actual;
void graphics_text_attributes_restore_default_text_flow(GTextLayoutCacheRef layout) {
s_actual.disable_text_flow.layout = layout;
}
void graphics_text_attributes_enable_screen_text_flow(GTextLayoutCacheRef layout, uint8_t inset) {
s_actual.enable_text_flow.layout = layout;
s_actual.enable_text_flow.inset = inset;
}
void graphics_text_attributes_restore_default_paging(GTextLayoutCacheRef layout) {
s_actual.disable_paging.layout = layout;
}
void graphics_text_attributes_enable_paging(GTextLayoutCacheRef layout,
GPoint content_origin_on_screen, GRect paging_on_screen) {
s_actual.enable_paging.layout = layout;
s_actual.enable_paging.origin = content_origin_on_screen;
s_actual.enable_paging.paging = paging_on_screen;
}
#define MOCKED_PAGING_ORIGIN GPoint(1 ,2)
#define MOCKED_PAGING_PAGE GRect(3, 4, 5, 6)
bool s_text_layer_calc_text_flow_paging_values_result;
bool text_layer_calc_text_flow_paging_values(const TextLayer *text_layer,
GPoint *content_origin_on_screen,
GRect *page_rect_on_screen) {
*content_origin_on_screen = MOCKED_PAGING_ORIGIN;
*page_rect_on_screen = MOCKED_PAGING_PAGE;
return s_text_layer_calc_text_flow_paging_values_result;
}
// Tests
//////////////////////
#define cl_assert_mocks_called(expected) \
do { \
cl_assert_equal_p((expected).disable_text_flow.layout, s_actual.disable_text_flow.layout); \
cl_assert_equal_p((expected).enable_text_flow.layout, s_actual.enable_text_flow.layout); \
cl_assert_equal_i((expected).enable_text_flow.inset, s_actual.enable_text_flow.inset); \
cl_assert_equal_p((expected).disable_paging.layout, s_actual.disable_paging.layout); \
cl_assert_equal_p((expected).enable_paging.layout, s_actual.enable_paging.layout); \
cl_assert_equal_i((expected).enable_paging.origin.x, s_actual.enable_paging.origin.x); \
cl_assert_equal_i((expected).enable_paging.origin.y, s_actual.enable_paging.origin.y); \
cl_assert_equal_i((expected).enable_paging.paging.origin.x, s_actual.enable_paging.paging.origin.x); \
cl_assert_equal_i((expected).enable_paging.paging.origin.y, s_actual.enable_paging.paging.origin.y); \
cl_assert_equal_i((expected).enable_paging.paging.size.w, s_actual.enable_paging.paging.size.w); \
cl_assert_equal_i((expected).enable_paging.paging.size.h, s_actual.enable_paging.paging.size.h); \
} while(0)
Window window;
TextLayer text_layer;
void test_text_layer__initialize(void) {
s_actual = (MockValues){};
window = (Window){};
text_layer_init(&text_layer, &GRect(10, 20, 30, 40));
s_text_layer_calc_ | {
return NULL;
} | <|repo_name|>pebble
<|file_sep|>tests/fw/ui/test_text_layer.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "clar.h"
#include "applib/ui/text_layer.h"
// Stubs
/////////////////////
#include "stubs_app_state.h"
#include "stubs_graphics.h"
#include "stubs_heap.h"
#include "stubs_logging.h"
#include "stubs_passert.h"
#include "stubs_pbl_malloc.h"
#include "stubs_pebble_tasks.h"
#include "stubs_process_manager.h"
#include "stubs_system_theme.h"
#include "stubs_ui_window.h"
#include "stubs_unobstructed_area.h"
GFont fonts_get_system_font(const char *font_key) <|fim_suffix|>
void graphics_context_set_fill_color(GContext* ctx, GColor color){}
void graphics_context_set_text_color(GContext* ctx, GColor color){}
// Fakes
////////////////////////
#define MOCKED_CREATED_LAYOUT (GTextLayoutCacheRef)123456
void graphics_text_layout_cache_init(GTextLayoutCacheRef *layout_cache) {
*layout_cache = MOCKED_CREATED_LAYOUT;
}
void graphics_text_layout_cache_deinit(GTextLayoutCacheRef *layout_cache) {}
void graphics_text_layout_set_line_spacing_delta(GTextLayoutCacheRef layout, int16_t delta) {}
int16_t graphics_text_layout_get_line_spacing_delta(const GTextLayoutCacheRef layout) {
return 0;
}
GSize graphics_text_layout_get_max_used_size(GContext *ctx, const char *text,
GFont const font, const GRect box,
const GTextOverflowMode overflow_mode,
const GTextAlignment alignment,
GTextLayoutCacheRef layout) {
return GSizeZero;
}
typedef struct {
struct {
GTextLayoutCacheRef layout;
} disable_text_flow;
struct {
GTextLayoutCacheRef layout;
uint8_t inset;
} enable_text_flow;
struct {
GTextLayoutCacheRef layout;
} disable_paging;
struct {
GTextLayoutCacheRef layout;
GPoint origin;
GRect paging;
} enable_paging;
} MockValues;
static MockValues s_actual;
void graphics_text_attributes_restore_default_text_flow(GTextLayoutCacheRef layout) {
s_actual.disable_text_flow.layout = layout;
}
void graphics_text_attributes_enable_screen_text_flow(GTextLayoutCacheRef layout, uint8_t inset) {
s_actual.enable_text_flow.layout = layout;
s_actual.enable_text_flow.inset = inset;
}
void graphics_text_attributes_restore_default_paging(GTextLayoutCacheRef layout) {
s_actual.disable_paging.layout = layout;
}
void graphics_text_attributes_enable_paging(GTextLayoutCacheRef layout,
GPoint content_origin_on_screen, GRect paging_on_screen) {
s_actual.enable_paging.layout = layout;
s_actual.enable_paging.origin = content_origin_on_screen;
s_actual.enable_paging.paging = paging_on_screen;
}
#define MOCKED_PAGING_ORIGIN GPoint(1 ,2)
#define MOCKED_PAGING_PAGE GRect(3, 4, 5, 6)
bool s_text_layer_calc_text_flow_paging_values_result;
bool text_layer_calc_text_flow_paging_values(const TextLayer *text_layer,
GPoint *content_origin_on_screen,
GRect *page_rect_on_screen) {
*content_origin_on_screen = MOCKED_PAGING_ORIGIN;
*page_rect_on_screen = MOCKED_PAGING_PAGE;
return s_text_layer_calc_text_flow_paging_values_result;
}
// Tests
//////////////////////
#define cl_assert_mocks_called(expected) \
do { \
cl_assert_equal_p((expected).disable_text_flow.layout, s_actual.disable_text_flow.layout); \
cl_assert_equal_p((expected).enable_text_flow.layout, s_actual.enable_text_flow.layout); \
cl_assert_equal_i((expected).enable_text_flow.inset, s_actual.enable_text_flow.inset); \
cl_assert_equal_p((expected).disable_paging.layout, s_actual.disable_paging.layout); \
cl_assert_equal_p((expected).enable_paging.layout, s_actual.enable_paging.layout); \
cl_assert_equal_i((expected).enable_paging.origin.x, s_actual.enable_paging.origin.x); \
cl_assert_equal_i((expected).enable_paging.origin.y, s_actual.enable_paging.origin.y); \
cl_assert_equal_i((expected).enable_paging.paging.origin.x, s_actual.enable_paging.paging.origin.x); \
cl_assert_equal_i((expected).enable_paging.paging.origin.y, s_actual.enable_paging.paging.origin.y); \
cl_assert_equal_i((expected).enable_paging.paging.size.w, s_actual.enable_paging.paging.size.w); \
cl_assert_equal_i((expected).enable_paging.paging.size.h, s_actual.enable_paging.paging.size.h); \
} while(0)
Window window;
TextLayer text_layer;
void test_text_layer__initialize(void) {
s_actual = (MockValues){};
window = (Window){};
text_layer_init(&text_layer, &GRect(10, 20, 30, 40));
s_text_layer_calc_<|fim_middle|>{
return NULL;
}<|endoftext|> |
masked_node | argument_list | src/fw/applib/ui/dialogs/bt_conn_dialog.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bt_conn_dialog.h"
#include "applib/applib_malloc.auto.h"
#include "applib/ui/dialogs/dialog.h"
#include "applib/ui/dialogs/dialog_private.h"
#include "applib/ui/window.h"
#include "kernel/events.h"
#include "kernel/pebble_tasks.h"
#include "kernel/ui/modals/modal_manager.h"
#include "process_state/app_state/app_state.h"
#include "resource/resource_ids.auto.h"
#include "services/common/i18n/i18n.h"
#include "syscall/syscall.h"
#include "system/passert.h"
static void prv_handle_comm_session_event(PebbleEvent *e, void *context) {
BtConnDialog *bt_dialog = context;
if (!e->bluetooth.comm_session_event.is_system) {
return;
}
if (e->bluetooth.comm_session_event.is_open) {
if (bt_dialog->connected_handler) {
bt_dialog->connected_handler(true, bt_dialog->context);
}
// handler to NULL so it won't be called again during the unload
bt_dialog->connected_handler = NULL;
dialog_pop(&bt_dialog->dialog.dialog);
}
}
static void prv_bt_dialog_unload(void *context) {
BtConnDialog *bt_dialog = context;
event_service_client_unsubscribe(&bt_dialog->pebble_app_event_sub);
if (bt_dialog->connected_handler) {
bt_dialog->connected_handler(false, bt_dialog->context);
}
if (bt_dialog->owns_buffer) {
applib_free(bt_dialog->text_buffer);
}
}
void bt_conn_dialog_push(BtConnDialog *bt_dialog, BtConnDialogResultHandler handler,
void *context) {
if (!bt_dialog) {
bt_dialog = bt_conn_dialog_create();
if (!bt_dialog) {
return;
}
}
bt_dialog->connected_handler = handler;
bt_dialog->context = context;
bt_dialog->pebble_app_event_sub = (EventServiceInfo) {
.type = PEBBLE_COMM_SESSION_EVENT,
.handler = prv_handle_comm_session_event,
.context = bt_dialog
};
event_service_client_subscribe(&bt_dialog->pebble_app_event_sub);
WindowStack *window_stack = NULL;
if (pebble_task_get_current() == PebbleTask_App) {
window_stack = app_state_get_window_stack();
} else {
// Bluetooth disconnection events are always displayed at maximum priority.
window_stack = modal_manager_get_window_stack | ;
}
simple_dialog_push(&bt_dialog->dialog, window_stack);
}
BtConnDialog *bt_conn_dialog_create(void) {
BtConnDialog *bt_dialog = applib_malloc(sizeof(BtConnDialog));
bt_conn_dialog_init(bt_dialog, NULL, 0);
return bt_dialog;
}
void bt_conn_dialog_init(BtConnDialog *bt_dialog, char *text_buffer, size_t buffer_size) {
memset(bt_dialog, 0, sizeof(BtConnDialog));
simple_dialog_init(&bt_dialog->dialog, "Bluetooth Disconnected");
Dialog *dialog = &bt_dialog->dialog.dialog;
size_t len = sys_i18n_get_length("Check bluetooth connection");
if (text_buffer) {
PBL_ASSERTN(len < buffer_size);
bt_dialog->text_buffer = text_buffer;
bt_dialog->owns_buffer = false;
} else {
buffer_size = len + 1;
bt_dialog->text_buffer = applib_malloc(buffer_size);
bt_dialog->owns_buffer = true;
}
sys_i18n_get_with_buffer("Check bluetooth connection", bt_dialog->text_buffer, buffer_size);
dialog_set_text(dialog, bt_dialog->text_buffer);
dialog_set_icon(dialog, RESOURCE_ID_WATCH_DISCONNECTED_LARGE);
dialog_show_status_bar_layer(dialog, true);
dialog_set_callbacks(dialog, &(DialogCallbacks) {
.unload = prv_bt_dialog_unload
}, bt_dialog);
}
| (ModalPriorityCritical) | <|repo_name|>pebble
<|file_sep|>src/fw/applib/ui/dialogs/bt_conn_dialog.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bt_conn_dialog.h"
#include "applib/applib_malloc.auto.h"
#include "applib/ui/dialogs/dialog.h"
#include "applib/ui/dialogs/dialog_private.h"
#include "applib/ui/window.h"
#include "kernel/events.h"
#include "kernel/pebble_tasks.h"
#include "kernel/ui/modals/modal_manager.h"
#include "process_state/app_state/app_state.h"
#include "resource/resource_ids.auto.h"
#include "services/common/i18n/i18n.h"
#include "syscall/syscall.h"
#include "system/passert.h"
static void prv_handle_comm_session_event(PebbleEvent *e, void *context) {
BtConnDialog *bt_dialog = context;
if (!e->bluetooth.comm_session_event.is_system) {
return;
}
if (e->bluetooth.comm_session_event.is_open) {
if (bt_dialog->connected_handler) {
bt_dialog->connected_handler(true, bt_dialog->context);
}
// handler to NULL so it won't be called again during the unload
bt_dialog->connected_handler = NULL;
dialog_pop(&bt_dialog->dialog.dialog);
}
}
static void prv_bt_dialog_unload(void *context) {
BtConnDialog *bt_dialog = context;
event_service_client_unsubscribe(&bt_dialog->pebble_app_event_sub);
if (bt_dialog->connected_handler) {
bt_dialog->connected_handler(false, bt_dialog->context);
}
if (bt_dialog->owns_buffer) {
applib_free(bt_dialog->text_buffer);
}
}
void bt_conn_dialog_push(BtConnDialog *bt_dialog, BtConnDialogResultHandler handler,
void *context) {
if (!bt_dialog) {
bt_dialog = bt_conn_dialog_create();
if (!bt_dialog) {
return;
}
}
bt_dialog->connected_handler = handler;
bt_dialog->context = context;
bt_dialog->pebble_app_event_sub = (EventServiceInfo) {
.type = PEBBLE_COMM_SESSION_EVENT,
.handler = prv_handle_comm_session_event,
.context = bt_dialog
};
event_service_client_subscribe(&bt_dialog->pebble_app_event_sub);
WindowStack *window_stack = NULL;
if (pebble_task_get_current() == PebbleTask_App) {
window_stack = app_state_get_window_stack();
} else {
// Bluetooth disconnection events are always displayed at maximum priority.
window_stack = modal_manager_get_window_stack<|fim_suffix|>;
}
simple_dialog_push(&bt_dialog->dialog, window_stack);
}
BtConnDialog *bt_conn_dialog_create(void) {
BtConnDialog *bt_dialog = applib_malloc(sizeof(BtConnDialog));
bt_conn_dialog_init(bt_dialog, NULL, 0);
return bt_dialog;
}
void bt_conn_dialog_init(BtConnDialog *bt_dialog, char *text_buffer, size_t buffer_size) {
memset(bt_dialog, 0, sizeof(BtConnDialog));
simple_dialog_init(&bt_dialog->dialog, "Bluetooth Disconnected");
Dialog *dialog = &bt_dialog->dialog.dialog;
size_t len = sys_i18n_get_length("Check bluetooth connection");
if (text_buffer) {
PBL_ASSERTN(len < buffer_size);
bt_dialog->text_buffer = text_buffer;
bt_dialog->owns_buffer = false;
} else {
buffer_size = len + 1;
bt_dialog->text_buffer = applib_malloc(buffer_size);
bt_dialog->owns_buffer = true;
}
sys_i18n_get_with_buffer("Check bluetooth connection", bt_dialog->text_buffer, buffer_size);
dialog_set_text(dialog, bt_dialog->text_buffer);
dialog_set_icon(dialog, RESOURCE_ID_WATCH_DISCONNECTED_LARGE);
dialog_show_status_bar_layer(dialog, true);
dialog_set_callbacks(dialog, &(DialogCallbacks) {
.unload = prv_bt_dialog_unload
}, bt_dialog);
}
<|fim_middle|>(ModalPriorityCritical)<|endoftext|> |
masked_node | compound_statement | src/fw/apps/system_apps/alarms/alarm_editor.c | ////////////////////////////////////////////////////////////////////////////////
//! Day Picker
static void prv_day_picker_window_unload(Window *window) {
AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window);
if (!data->day_picker_was_completed && data->time_picker_was_completed) {
// If we cancel the day picker go back to the time picker
data->time_picker_was_completed = false;
return;
}
if (data->creating_alarm) {
time_selection_window_deinit(&data->time_picker_window);
}
// Editing recurrence
menu_layer_deinit(&data->day_picker_menu_layer);
prv_remove_windows(data);
i18n_free_all(&data->day_picker_window);
task_free(data);
data = NULL;
}
static void prv_handle_selection(int index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
data->day_picker_was_completed = true;
data->alarm_kind = prv_index_to_alarm_kind(index);
if (data->creating_alarm) {
const AlarmInfo info = {
.hour = data->alarm_hour,
.minute = data->alarm_minute,
.kind = data->alarm_kind,
.is_smart = (data->alarm_type == AlarmType_Smart),
};
data->alarm_id = alarm_create(&info);
data->complete_callback(CREATED, data->alarm_id, data->callback_context);
app_window_stack_remove(&data->day_picker_window, true);
} else {
alarm_set_kind(data->alarm_id, data->alarm_kind);
data->complete_callback(EDITED, data->alarm_id, data->callback_context);
app_window_stack_pop(true);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Custom Day Picker
static void prv_custom_day_picker_window_unload(Window *window) {
AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window);
if (!data->custom_day_picker_was_completed) {
// If we cancel the custom day picker go back to the day picker
data->day_picker_was_completed = false;
i18n_free_all(&data->custom_day_picker_window);
return;
}
menu_layer_deinit(&data->custom_day_picker_menu_layer);
prv_remove_windows(data);
i18n_free_all(&data->custom_day_picker_window);
}
static void prv_handle_custom_day_selection(int index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
prv_setup_custom_day_picker_window(data);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Menu Layer Callbacks
static uint16_t prv_day_picker_get_num_sections(struct MenuLayer *menu_layer,
void *callback_context) {
return 1;
}
static uint16_t prv_day_picker_get_num_rows(struct MenuLayer *menu_layer,
uint16_t section_index,
void *callback_context) {
return DayPickerMenuItemsNumItems;
}
static int16_t prv_day_picker_get_cell_height(struct MenuLayer *menu_layer,
MenuIndex *cell_index,
void *callback_context) {
return ALARM_DAY_LIST_CELL_HEIGHT;
}
static void prv_day_picker_draw_row(GContext *ctx, const Layer *cell_layer,
MenuIndex *cell_index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
AlarmKind kind = prv_index_to_alarm_kind(cell_index->row);
const bool all_caps = false;
const char *cell_text = alarm_get_string_for_kind(kind, all_caps);
menu_cell_basic_draw(ctx, cell_layer, i18n_get(cell_text, &data->day_picker_window), NULL, NULL);
}
static void prv_day_picker_handle_selection(MenuLayer *menu_layer, MenuIndex *cell_index,
void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
data->day_picker_was_completed = false;
if (cell_index->row == DayPickerMenuItemsCustom) {
prv_handle_custom_day_selection(cell_index->row, callback_context);
} else |
}
static void prv_setup_day_picker_window(AlarmEditorData *data) {
window_init(&data->day_picker_window, WINDOW_NAME("Alarm Day Picker"));
window_set_user_data(&data->day_picker_window, data);
data->day_picker_window.window_handlers.unload = prv_day_picker_window_unload;
GRect bounds = data->day_picker_window.layer.bounds;
#if PBL_ROUND
bounds = grect_inset_internal(bounds, 0, STATUS_BAR_LAYER_HEIGHT);
#endif
menu_layer_init(&data->day_picker_menu_layer, &bounds);
menu_layer_set_callbacks(&data->day_picker_menu_layer, data, &(MenuLayerCallbacks) {
.get_num_sections = prv_day_picker_get_num_sections,
.get_num_rows = prv_day_picker_get_num_rows,
.get_cell_height = prv_day_picker_get_cell_height,
.draw_row = prv_day_picker_draw_row,
.select_click = prv_day_picker_handle_selection,
});
menu_layer_set_highlight_colors(&data->day_picker_menu_layer,
ALARMS_APP_HIGHLIGHT_COLOR,
GColorWhite);
menu_layer_set_click_config_onto_window(&data->day_picker_menu_layer, &data->day_picker_window);
layer_add_child(&data->day_picker_window.layer,
menu_layer_get_layer(&data->day_picker_menu_layer));
if (!alarm_get_kind(data->alarm_id, &data->alarm_kind)) {
data->alarm_kind = ALARM_KIND_JUST_ONCE;
}
menu_layer_set_selected_index(&data->day_picker_menu_layer,
(MenuIndex) { 0, prv_alarm_kind_to_index(data->alarm_kind) },
MenuRowAlignCenter, false);
}
static uint16_t prv_custom_day_picker_get_num_sections(struct MenuLayer *menu_layer,
void *callback_context) {
return 1;
}
static uint16_t prv_custom_day_picker_get_num_rows(struct MenuLayer *menu_layer,
uint16_t section_index, void *callback_context) {
return DAYS_PER_WEEK + 1;
}
static int16_t prv_custom_day_picker_get_cell_height(struct MenuLayer *menu_layer,
MenuIndex *cell_index,
void *callback_context) {
return ALARM_DAY_LIST_CELL_HEIGHT;
}
static void prv_custom_day_picker_draw_row(GContext *ctx, const Layer *cell_layer,
MenuIndex *cell_index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
GBitmap *ptr_bitmap;
if (cell_index->row == 0) { // "completed selection" row
GRect box;
uint32_t new_resource_id = RESOURCE_ID_CHECKMARK_ICON_BLACK;
if (!prv_is_custom_day_scheduled(data)) {
// no days selected
if (menu_cell_layer_is_highlighted(cell_layer)) {
if (data->show_check_something_first_text) { // clicking "complete" when no days selected
box.size = GSize(cell_layer->bounds.size.w, ALARM_DAY_LIST_CELL_HEIGHT);
box.origin = GPoint(0, 4);
graphics_draw_text(ctx, i18n_get("Check something first.",
&data->custom_day_picker_window),
fonts_get_system_font(FONT_KEY_GOTHIC_18), box, GTextOverflowModeFill,
GTextAlignmentCenter, NULL);
return;
} else { // row highlighted and no days selected
new_resource_id = RESOURCE_ID_CHECKMARK_ICON_DOTTED;
}
}
}
if (new_resource_id != data->current_checkmark_icon_resource_id) {
data->current_checkmark_icon_resource_id = new_resource_id;
gbitmap_deinit(&data->checkmark_icon);
gbitmap_init_with_resource(&data->checkmark_icon, data->current_checkmark_icon_resource_id);
}
box.origin = GPoint((((cell_layer->bounds.size.w)/2)-((data->checkmark_icon.bounds.size.w)/2)),
(((cell_layer->bounds.size.h)/2)-((data->checkmark_icon.bounds.size.h)/2)));
box.size = data->checkmark_icon.bounds.size;
graphics_context_set_compositing_mode(ctx, GCompOpTint);
| {
data->day_picker_was_completed = true;
prv_handle_selection(cell_index->row, callback_context);
} | <|repo_name|>pebble
<|file_sep|>src/fw/apps/system_apps/alarms/alarm_editor.c
<|fim_prefix|>////////////////////////////////////////////////////////////////////////////////
//! Day Picker
static void prv_day_picker_window_unload(Window *window) {
AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window);
if (!data->day_picker_was_completed && data->time_picker_was_completed) {
// If we cancel the day picker go back to the time picker
data->time_picker_was_completed = false;
return;
}
if (data->creating_alarm) {
time_selection_window_deinit(&data->time_picker_window);
}
// Editing recurrence
menu_layer_deinit(&data->day_picker_menu_layer);
prv_remove_windows(data);
i18n_free_all(&data->day_picker_window);
task_free(data);
data = NULL;
}
static void prv_handle_selection(int index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
data->day_picker_was_completed = true;
data->alarm_kind = prv_index_to_alarm_kind(index);
if (data->creating_alarm) {
const AlarmInfo info = {
.hour = data->alarm_hour,
.minute = data->alarm_minute,
.kind = data->alarm_kind,
.is_smart = (data->alarm_type == AlarmType_Smart),
};
data->alarm_id = alarm_create(&info);
data->complete_callback(CREATED, data->alarm_id, data->callback_context);
app_window_stack_remove(&data->day_picker_window, true);
} else {
alarm_set_kind(data->alarm_id, data->alarm_kind);
data->complete_callback(EDITED, data->alarm_id, data->callback_context);
app_window_stack_pop(true);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Custom Day Picker
static void prv_custom_day_picker_window_unload(Window *window) {
AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window);
if (!data->custom_day_picker_was_completed) {
// If we cancel the custom day picker go back to the day picker
data->day_picker_was_completed = false;
i18n_free_all(&data->custom_day_picker_window);
return;
}
menu_layer_deinit(&data->custom_day_picker_menu_layer);
prv_remove_windows(data);
i18n_free_all(&data->custom_day_picker_window);
}
static void prv_handle_custom_day_selection(int index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
prv_setup_custom_day_picker_window(data);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Menu Layer Callbacks
static uint16_t prv_day_picker_get_num_sections(struct MenuLayer *menu_layer,
void *callback_context) {
return 1;
}
static uint16_t prv_day_picker_get_num_rows(struct MenuLayer *menu_layer,
uint16_t section_index,
void *callback_context) {
return DayPickerMenuItemsNumItems;
}
static int16_t prv_day_picker_get_cell_height(struct MenuLayer *menu_layer,
MenuIndex *cell_index,
void *callback_context) {
return ALARM_DAY_LIST_CELL_HEIGHT;
}
static void prv_day_picker_draw_row(GContext *ctx, const Layer *cell_layer,
MenuIndex *cell_index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
AlarmKind kind = prv_index_to_alarm_kind(cell_index->row);
const bool all_caps = false;
const char *cell_text = alarm_get_string_for_kind(kind, all_caps);
menu_cell_basic_draw(ctx, cell_layer, i18n_get(cell_text, &data->day_picker_window), NULL, NULL);
}
static void prv_day_picker_handle_selection(MenuLayer *menu_layer, MenuIndex *cell_index,
void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
data->day_picker_was_completed = false;
if (cell_index->row == DayPickerMenuItemsCustom) {
prv_handle_custom_day_selection(cell_index->row, callback_context);
} else <|fim_suffix|>
}
static void prv_setup_day_picker_window(AlarmEditorData *data) {
window_init(&data->day_picker_window, WINDOW_NAME("Alarm Day Picker"));
window_set_user_data(&data->day_picker_window, data);
data->day_picker_window.window_handlers.unload = prv_day_picker_window_unload;
GRect bounds = data->day_picker_window.layer.bounds;
#if PBL_ROUND
bounds = grect_inset_internal(bounds, 0, STATUS_BAR_LAYER_HEIGHT);
#endif
menu_layer_init(&data->day_picker_menu_layer, &bounds);
menu_layer_set_callbacks(&data->day_picker_menu_layer, data, &(MenuLayerCallbacks) {
.get_num_sections = prv_day_picker_get_num_sections,
.get_num_rows = prv_day_picker_get_num_rows,
.get_cell_height = prv_day_picker_get_cell_height,
.draw_row = prv_day_picker_draw_row,
.select_click = prv_day_picker_handle_selection,
});
menu_layer_set_highlight_colors(&data->day_picker_menu_layer,
ALARMS_APP_HIGHLIGHT_COLOR,
GColorWhite);
menu_layer_set_click_config_onto_window(&data->day_picker_menu_layer, &data->day_picker_window);
layer_add_child(&data->day_picker_window.layer,
menu_layer_get_layer(&data->day_picker_menu_layer));
if (!alarm_get_kind(data->alarm_id, &data->alarm_kind)) {
data->alarm_kind = ALARM_KIND_JUST_ONCE;
}
menu_layer_set_selected_index(&data->day_picker_menu_layer,
(MenuIndex) { 0, prv_alarm_kind_to_index(data->alarm_kind) },
MenuRowAlignCenter, false);
}
static uint16_t prv_custom_day_picker_get_num_sections(struct MenuLayer *menu_layer,
void *callback_context) {
return 1;
}
static uint16_t prv_custom_day_picker_get_num_rows(struct MenuLayer *menu_layer,
uint16_t section_index, void *callback_context) {
return DAYS_PER_WEEK + 1;
}
static int16_t prv_custom_day_picker_get_cell_height(struct MenuLayer *menu_layer,
MenuIndex *cell_index,
void *callback_context) {
return ALARM_DAY_LIST_CELL_HEIGHT;
}
static void prv_custom_day_picker_draw_row(GContext *ctx, const Layer *cell_layer,
MenuIndex *cell_index, void *callback_context) {
AlarmEditorData *data = (AlarmEditorData *)callback_context;
GBitmap *ptr_bitmap;
if (cell_index->row == 0) { // "completed selection" row
GRect box;
uint32_t new_resource_id = RESOURCE_ID_CHECKMARK_ICON_BLACK;
if (!prv_is_custom_day_scheduled(data)) {
// no days selected
if (menu_cell_layer_is_highlighted(cell_layer)) {
if (data->show_check_something_first_text) { // clicking "complete" when no days selected
box.size = GSize(cell_layer->bounds.size.w, ALARM_DAY_LIST_CELL_HEIGHT);
box.origin = GPoint(0, 4);
graphics_draw_text(ctx, i18n_get("Check something first.",
&data->custom_day_picker_window),
fonts_get_system_font(FONT_KEY_GOTHIC_18), box, GTextOverflowModeFill,
GTextAlignmentCenter, NULL);
return;
} else { // row highlighted and no days selected
new_resource_id = RESOURCE_ID_CHECKMARK_ICON_DOTTED;
}
}
}
if (new_resource_id != data->current_checkmark_icon_resource_id) {
data->current_checkmark_icon_resource_id = new_resource_id;
gbitmap_deinit(&data->checkmark_icon);
gbitmap_init_with_resource(&data->checkmark_icon, data->current_checkmark_icon_resource_id);
}
box.origin = GPoint((((cell_layer->bounds.size.w)/2)-((data->checkmark_icon.bounds.size.w)/2)),
(((cell_layer->bounds.size.h)/2)-((data->checkmark_icon.bounds.size.h)/2)));
box.size = data->checkmark_icon.bounds.size;
graphics_context_set_compositing_mode(ctx, GCompOpTint);
<|fim_middle|>{
data->day_picker_was_completed = true;
prv_handle_selection(cell_index->row, callback_context);
}<|endoftext|> |
masked_node | compound_statement | src/fw/services/normal/send_text_service.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "send_text_service.h"
#include "applib/event_service_client.h"
#include "kernel/events.h"
#include "services/common/bluetooth/bluetooth_persistent_storage.h"
#include "services/normal/blob_db/ios_notif_pref_db.h"
#include "services/normal/notifications/notification_constants.h"
static bool s_has_send_text_reply_action = false;
static bool prv_has_send_text_reply_action(void) {
iOSNotifPrefs *notif_prefs = ios_notif_pref_db_get_prefs((uint8_t *)SEND_TEXT_NOTIF_PREF_KEY,
strlen(SEND_TEXT_NOTIF_PREF_KEY));
if (!notif_prefs) {
return false;
}
bool has_reply_action =
(timeline_item_action_group_find_reply_action(¬if_prefs->action_group) != NULL);
ios_notif_pref_db_free_prefs(notif_prefs);
return has_reply_action;
}
static void prv_blobdb_event_handler(PebbleEvent *event, void *context) {
const PebbleBlobDBEvent *blobdb_event = &event->blob_db;
if (blobdb_event->db_id != BlobDBIdiOSNotifPref) {
return;
}
if (blobdb_event->type != BlobDBEventTypeFlush &&
memcmp(blobdb_event->key, (uint8_t *)SEND_TEXT_NOTIF_PREF_KEY,
strlen(SEND_TEXT_NOTIF_PREF_KEY))) |
s_has_send_text_reply_action = prv_has_send_text_reply_action();
}
void send_text_service_init(void) {
// Save the initial state
s_has_send_text_reply_action = prv_has_send_text_reply_action();;
// Register for updates
static EventServiceInfo s_blobdb_event_info = {
.type = PEBBLE_BLOBDB_EVENT,
.handler = prv_blobdb_event_handler,
};
event_service_client_subscribe(&s_blobdb_event_info);
}
bool send_text_service_is_send_text_supported(void) {
PebbleProtocolCapabilities capabilities;
bt_persistent_storage_get_cached_system_capabilities(&capabilities);
return (capabilities.send_text_support && s_has_send_text_reply_action);
}
| {
return;
} | <|repo_name|>pebble
<|file_sep|>src/fw/services/normal/send_text_service.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "send_text_service.h"
#include "applib/event_service_client.h"
#include "kernel/events.h"
#include "services/common/bluetooth/bluetooth_persistent_storage.h"
#include "services/normal/blob_db/ios_notif_pref_db.h"
#include "services/normal/notifications/notification_constants.h"
static bool s_has_send_text_reply_action = false;
static bool prv_has_send_text_reply_action(void) {
iOSNotifPrefs *notif_prefs = ios_notif_pref_db_get_prefs((uint8_t *)SEND_TEXT_NOTIF_PREF_KEY,
strlen(SEND_TEXT_NOTIF_PREF_KEY));
if (!notif_prefs) {
return false;
}
bool has_reply_action =
(timeline_item_action_group_find_reply_action(¬if_prefs->action_group) != NULL);
ios_notif_pref_db_free_prefs(notif_prefs);
return has_reply_action;
}
static void prv_blobdb_event_handler(PebbleEvent *event, void *context) {
const PebbleBlobDBEvent *blobdb_event = &event->blob_db;
if (blobdb_event->db_id != BlobDBIdiOSNotifPref) {
return;
}
if (blobdb_event->type != BlobDBEventTypeFlush &&
memcmp(blobdb_event->key, (uint8_t *)SEND_TEXT_NOTIF_PREF_KEY,
strlen(SEND_TEXT_NOTIF_PREF_KEY))) <|fim_suffix|>
s_has_send_text_reply_action = prv_has_send_text_reply_action();
}
void send_text_service_init(void) {
// Save the initial state
s_has_send_text_reply_action = prv_has_send_text_reply_action();;
// Register for updates
static EventServiceInfo s_blobdb_event_info = {
.type = PEBBLE_BLOBDB_EVENT,
.handler = prv_blobdb_event_handler,
};
event_service_client_subscribe(&s_blobdb_event_info);
}
bool send_text_service_is_send_text_supported(void) {
PebbleProtocolCapabilities capabilities;
bt_persistent_storage_get_cached_system_capabilities(&capabilities);
return (capabilities.send_text_support && s_has_send_text_reply_action);
}
<|fim_middle|>{
return;
}<|endoftext|> |
masked_node | call_expression | src/fw/apps/demo_apps/flash_prof.c | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "process_management/pebble_process_md.h"
#include "applib/app.h"
#include "system/logging.h"
#include "drivers/flash.h"
#include "drivers/rtc.h"
#include "flash_region/flash_region.h"
#include "system/passert.h"
#include "kernel/pbl_malloc.h"
#include "applib/ui/app_window_stack.h"
#include "applib/ui/number_window.h"
#include "applib/ui/window_stack.h"
#include "FreeRTOS.h"
static NumberWindow number_window;
static uint32_t timed_read_bytes(uint32_t num_bytes) {
uint8_t *buffer = kernel_malloc_check(num_bytes);
time_t start_time_s;
uint16_t start_time_ms;
rtc_get_time_ms(&start_time_s, &start_time_ms);
flash_read_bytes(buffer, FLASH_REGION_FILESYSTEM_BEGIN, num_bytes);
time_t stop_time_s;
uint16_t stop_time_ms;
rtc_get_time_ms(&stop_time_s, &stop_time_ms);
kernel_free(buffer);
return ((stop_time_s * 1000 + stop_time_ms) - (start_time_s * 1000 + start_time_ms));
}
static void do_timed_read(NumberWindow *nw, void *data) {
uint32_t num_bytes = nw->value;
uint32_t predicted_time = num_bytes * 8 / 16000;
uint32_t time = timed_read_bytes(num_bytes);
PBL_LOG(LOG_LEVEL_DEBUG, "time to read %lu bytes: predicted %lu, actual %lu", num_bytes, predicted_time, time);
window_stack_remove(&number_window.window, false);
app_window_stack_push(&number_window.window, true);
}
#define NUM_BYTES 1000
static void handle_init(void) {
number_window_init(&number_window, "Num Writes", (NumberWindowCallbacks) {
.selected = (NumberWindowCallback) do_timed_read,
}, NULL);
number_window_set_min(&number_window, 1000);
number_window_set_max(&number_window, 1000000);
number_window_set_step_size(&number_window, 1000);
| ;
}
static void handle_deinit(void) {
}
static void s_main(void) {
handle_init();
app_event_loop();
handle_deinit();
}
const PebbleProcessMd* flash_prof_get_app_info() {
static const PebbleProcessMdSystem s_app_info = {
.common.main_func = &s_main,
.name = "Flash Prof"
};
return (const PebbleProcessMd*) &s_app_info;
}
| app_window_stack_push((Window *)&number_window, true) | <|repo_name|>pebble
<|file_sep|>src/fw/apps/demo_apps/flash_prof.c
<|fim_prefix|>/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "process_management/pebble_process_md.h"
#include "applib/app.h"
#include "system/logging.h"
#include "drivers/flash.h"
#include "drivers/rtc.h"
#include "flash_region/flash_region.h"
#include "system/passert.h"
#include "kernel/pbl_malloc.h"
#include "applib/ui/app_window_stack.h"
#include "applib/ui/number_window.h"
#include "applib/ui/window_stack.h"
#include "FreeRTOS.h"
static NumberWindow number_window;
static uint32_t timed_read_bytes(uint32_t num_bytes) {
uint8_t *buffer = kernel_malloc_check(num_bytes);
time_t start_time_s;
uint16_t start_time_ms;
rtc_get_time_ms(&start_time_s, &start_time_ms);
flash_read_bytes(buffer, FLASH_REGION_FILESYSTEM_BEGIN, num_bytes);
time_t stop_time_s;
uint16_t stop_time_ms;
rtc_get_time_ms(&stop_time_s, &stop_time_ms);
kernel_free(buffer);
return ((stop_time_s * 1000 + stop_time_ms) - (start_time_s * 1000 + start_time_ms));
}
static void do_timed_read(NumberWindow *nw, void *data) {
uint32_t num_bytes = nw->value;
uint32_t predicted_time = num_bytes * 8 / 16000;
uint32_t time = timed_read_bytes(num_bytes);
PBL_LOG(LOG_LEVEL_DEBUG, "time to read %lu bytes: predicted %lu, actual %lu", num_bytes, predicted_time, time);
window_stack_remove(&number_window.window, false);
app_window_stack_push(&number_window.window, true);
}
#define NUM_BYTES 1000
static void handle_init(void) {
number_window_init(&number_window, "Num Writes", (NumberWindowCallbacks) {
.selected = (NumberWindowCallback) do_timed_read,
}, NULL);
number_window_set_min(&number_window, 1000);
number_window_set_max(&number_window, 1000000);
number_window_set_step_size(&number_window, 1000);
<|fim_suffix|>;
}
static void handle_deinit(void) {
}
static void s_main(void) {
handle_init();
app_event_loop();
handle_deinit();
}
const PebbleProcessMd* flash_prof_get_app_info() {
static const PebbleProcessMdSystem s_app_info = {
.common.main_func = &s_main,
.name = "Flash Prof"
};
return (const PebbleProcessMd*) &s_app_info;
}
<|fim_middle|>app_window_stack_push((Window *)&number_window, true)<|endoftext|> |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 22