diff --git a/CODEOWNERS b/.gitee/CODEOWNERS similarity index 95% rename from CODEOWNERS rename to .gitee/CODEOWNERS index 1119e9eddd73153543d2b0ab9557d4d7dbd4a10f..1110287e69e88d693e7ea45bf19c9619190d5488 100644 --- a/CODEOWNERS +++ b/.gitee/CODEOWNERS @@ -13,13 +13,7 @@ * limitations under the License. */ -# any change to interfaces/inner_api/hdi/hdf_device_manager_interface_code.h needs to be reviewed by @leonchan5 -interfaces/inner_api/hdi/hdf_device_manager_interface_code.h @leonchan5 - -# Code reviewers for adapter adapter/ @time_zhang - -# Code reviewers for framework framework/ @time_zhang framework/model/input/ @time_zhang framework/model/audio/ @whoselettlelion @@ -36,3 +30,6 @@ framework/include/wifi/ @danny_liuxu framework/include/bluetooth/ @danny_liuxu framework/include/ethernet/ @danny_liuxu framework/include/net/ @danny_liuxu + +# any change to interfaces/inner_api/hdi/hdf_device_manager_interface_code.h needs to be reviewed by @leonchan5 +interfaces/inner_api/hdi/hdf_device_manager_interface_code.h @leonchan5 \ No newline at end of file diff --git a/adapter/khdf/linux/model/display/Kconfig b/adapter/khdf/linux/model/display/Kconfig index ad06d9fb66ec06c4548cd46e4507effd716b4807..99bf3a9f6bed834246ef1da03ee6ff2c0cdad2d7 100644 --- a/adapter/khdf/linux/model/display/Kconfig +++ b/adapter/khdf/linux/model/display/Kconfig @@ -22,3 +22,9 @@ config DRIVERS_HDF_LCD_ST7789 depends on DRIVERS_HDF_DISP help Answer Y to enable HDF St7789 driver. +config DRIVERS_HDF_DUAL_LCD_ICN9700_ST7701SN + bool "Enable HDF Icn9700&ST7701SN drivers" + default n + depends on DRIVERS_HDF_DISP + help + Answer Y to enable HDF Icn9700&ST7701SN drivers. \ No newline at end of file diff --git a/adapter/khdf/linux/model/display/Makefile b/adapter/khdf/linux/model/display/Makefile index d71abc771b19bf4fb830642f73ff7200d5669ff5..c990ef9daba2e05b8bdcf09ee11ff5792cef92d7 100644 --- a/adapter/khdf/linux/model/display/Makefile +++ b/adapter/khdf/linux/model/display/Makefile @@ -11,7 +11,7 @@ # GNU General Public License for more details. # # - +KHDF_DISPLAY_BASE_ROOT_DIR = ../../../../../../.. DISPLAY_ROOT_DIR = ../../../../../framework/model/display/driver ifeq ($(CONFIG_DRIVERS_HDF_DISP), y) @@ -39,6 +39,8 @@ obj-$(CONFIG_DRIVERS_HDF_LCDKIT) += \ $(DISPLAY_ROOT_DIR)/lcdkit/lcdkit_parse_config.o obj-$(CONFIG_DRIVERS_HDF_LCD_ICN9700) += \ $(DISPLAY_ROOT_DIR)/panel/mipi_icn9700.o +obj-$(CONFIG_DRIVERS_HDF_DUAL_LCD_ICN9700_ST7701SN) += \ + $(KHDF_DISPLAY_BASE_ROOT_DIR)/device/board/hisilicon/hispark_taurus/display_drivers/ obj-$(CONFIG_DRIVERS_HDF_LCD_ST7789) += \ $(DISPLAY_ROOT_DIR)/panel/ssp_st7789.o obj-$(CONFIG_ARCH_ROCKCHIP) += \ diff --git a/adapter/khdf/linux/platform/Kconfig b/adapter/khdf/linux/platform/Kconfig index c2c59a56d516937aaf96cfe347e61a3cd63dc876..eef06d38e3fd9e4d01dd2b3c392add73d9287026 100644 --- a/adapter/khdf/linux/platform/Kconfig +++ b/adapter/khdf/linux/platform/Kconfig @@ -114,6 +114,13 @@ config DRIVERS_HDF_PLATFORM_ADC help Answer Y to enable HDF platform adc driver. +config DRIVERS_HDF_PLATFORM_CLOCK + bool "Enable HDF platform clock driver" + default n + depends on DRIVERS_HDF_PLATFORM + help + Answer Y to enable HDF platform clock driver. + config DRIVERS_HDF_PLATFORM_TRACE bool "Enable HDF platform trace driver" default n diff --git a/adapter/khdf/linux/platform/Makefile b/adapter/khdf/linux/platform/Makefile index 793693e3a2327ebb4dd84c5267c1be1f3d4c1d0f..690c5904651b48316ae99952fd6f7a76a02edb39 100644 --- a/adapter/khdf/linux/platform/Makefile +++ b/adapter/khdf/linux/platform/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. +# Copyright (c) 2020-2023 Huawei Device Co., Ltd. # # This software is licensed under the terms of the GNU General Public # License version 2, as published by the Free Software Foundation, and @@ -23,4 +23,5 @@ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_UART) += uart/ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_SPI) += spi/ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_RTC) += rtc/ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_ADC) += adc/ +obj-$(CONFIG_DRIVERS_HDF_PLATFORM_CLOCK) += clock/ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_REGULATOR) += regulator/ diff --git a/adapter/khdf/linux/platform/clock/Makefile b/adapter/khdf/linux/platform/clock/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..25af0de7f58d9f0b2f57d1048c4ff3740a973f56 --- /dev/null +++ b/adapter/khdf/linux/platform/clock/Makefile @@ -0,0 +1,19 @@ +# +# Copyright (c) 2023 Huawei Device Co., Ltd. +# +# This software is licensed under the terms of the GNU General Public +# License version 2, as published by the Free Software Foundation, and +# may be copied, distributed, and modified under those terms. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# + +include drivers/hdf/khdf/platform/platform.mk + +obj-y += $(HDF_PLATFORM_FRAMEWORKS_ROOT)/src/clock/clock_core.o \ + $(HDF_PLATFORM_FRAMEWORKS_ROOT)/src/clock/clock_if.o \ + ./clock_adapter.o diff --git a/adapter/khdf/linux/platform/clock/clock_adapter.c b/adapter/khdf/linux/platform/clock/clock_adapter.c new file mode 100644 index 0000000000000000000000000000000000000000..b635322c9fc819301659667c100ef8aa4a50433e --- /dev/null +++ b/adapter/khdf/linux/platform/clock/clock_adapter.c @@ -0,0 +1,374 @@ +/* + * clock driver adapter of linux + * + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY;without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include + +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#include "clock_core.h" + +#define HDF_LOG_TAG clock_adapter_c + +static int32_t ClockStart(struct ClockDevice *device) +{ + struct clk *clk = NULL; + struct device_node *node = NULL; + + if (device->clk != NULL) { + HDF_LOGI("device->clk already start\n"); + return HDF_SUCCESS; + } + + if (IS_ERR_OR_NULL(device->deviceName)) { + HDF_LOGE("ClockStart: deviceName IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + node = of_find_node_by_path(device->deviceName); + if (IS_ERR_OR_NULL(node)) { + HDF_LOGE("ClockStart: can not get node \n"); + return HDF_ERR_INVALID_PARAM; + } + + clk = of_clk_get_by_name(node, device->clockName); + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockStart: can not get clk \n"); + return HDF_ERR_INVALID_PARAM; + } + + device->clk = clk; + return HDF_SUCCESS; +} + +static int32_t ClockLinuxSetRate(struct ClockDevice *device, uint32_t rate) +{ + struct clk *clk = NULL; + int32_t ret; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxSetRate: clk IS_ERR_OR_NULL\n"); + return HDF_FAILURE; + } + ret = clk_set_rate(clk, rate); + return ret; +} + +static int32_t ClockStop(struct ClockDevice *device) +{ + struct clk *clk = NULL; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockStop: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + if (device->deviceName) { + clk_put(clk); + } + + device->clk = NULL; + return HDF_SUCCESS; +} + +static int32_t ClockLinuxGetRate(struct ClockDevice *device, uint32_t *rate) +{ + struct clk *clk = NULL; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxGetRate: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + *rate = clk_get_rate(clk); + return HDF_SUCCESS; +} + +static int32_t ClockLinuxDisable(struct ClockDevice *device) +{ + struct clk *clk = NULL; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxDisable: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + clk_disable_unprepare(clk); + return HDF_SUCCESS; +} + +static int32_t ClockLinuxEnable(struct ClockDevice *device) +{ + struct clk *clk = NULL; + int32_t ret; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxDisable: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + ret = clk_prepare_enable(clk); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockLinuxDisable ret = %d \n", ret); + } + + return ret; +} +static struct ClockDevice *ClockLinuxGetParent(struct ClockDevice *device); + + +static int32_t ClockLinuxSetParent(struct ClockDevice *device, struct ClockDevice *parent) +{ + struct clk *clk = NULL; + struct clk *clkParent = NULL; + int32_t ret; + if (device->parent == parent) { + HDF_LOGI("ClockLinuxSetParent:device parent is not change \n"); + return HDF_SUCCESS; + } + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxSetParent: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + clkParent = parent->clk; + if (IS_ERR_OR_NULL(clkParent)) { + HDF_LOGE("ClockLinuxSetParent: clkParent IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + ret = clk_set_parent(clk, clkParent); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockLinuxSetParent: clk_set_parent fail ret = %d\n", ret); + return ret; + } + + if (device->parent && device->parent->deviceName == NULL) { + ClockDeviceRemove(device->parent); + OsalMemFree(device->parent); + } + device->parent = parent; + + return ret; +} + +static const struct ClockMethod g_method = { + .start = ClockStart, + .stop = ClockStop, + .setRate = ClockLinuxSetRate, + .getRate = ClockLinuxGetRate, + .disable = ClockLinuxDisable, + .enable = ClockLinuxEnable, + .getParent = ClockLinuxGetParent, + .setParent = ClockLinuxSetParent, +}; + +static struct ClockDevice *ClockLinuxGetParent(struct ClockDevice *device) +{ + struct clk *clk = NULL; + struct clk *clkParent = NULL; + struct ClockDevice *clockDevice = NULL; + int32_t ret; + + clk = device->clk; + if (IS_ERR_OR_NULL(clk)) { + HDF_LOGE("ClockLinuxGetParent: clk IS_ERR_OR_NULL\n"); + return NULL; + } + + clkParent = clk_get_parent(clk); + if (IS_ERR_OR_NULL(clkParent)) { + HDF_LOGE("ClockLinuxGetParent: can not get clkParent \n"); + return NULL; + } + + if (device->parent != NULL) { + device->parent->clk = clkParent; + return device->parent; + } + + clockDevice = (struct ClockDevice *)OsalMemCalloc(sizeof(*clockDevice)); + if (clockDevice == NULL) { + HDF_LOGE("ClockLinuxGetParent: can not OsalMemCalloc clockDevice \n"); + return NULL; + } + + clockDevice->ops = &g_method; + ret = ClockManagerGetAIdleDeviceId(); + if (ret < 0) { + HDF_LOGE("ClockLinuxGetParent: add clock device:%d device if full fail!", ret); + OsalMemFree(clockDevice); + return NULL; + } + + clockDevice->deviceIndex = ret; + clockDevice->clk = clkParent; + + ret = ClockDeviceAdd(clockDevice); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockLinuxGetParent: add clock device:%u fail!", clockDevice->deviceIndex); + OsalMemFree(clockDevice); + return NULL; + } + device->parent = clockDevice; + + return clockDevice; +} + +static int32_t ClockReadDrs(struct ClockDevice *clockDevice, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { + HDF_LOGE("ClockReadDrs: invalid drs ops!"); + return HDF_ERR_NOT_SUPPORT; + } + ret = drsOps->GetUint32(node, "deviceIndex", &clockDevice->deviceIndex, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockReadDrs: read deviceIndex fail, ret: %d!", ret); + return ret; + } + + drsOps->GetString(node, "clockName", &clockDevice->clockName, 0); + + ret = drsOps->GetString(node, "deviceName", &clockDevice->deviceName, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockReadDrs: read deviceName fail, ret: %d!", ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t ClockParseAndDeviceAdd(struct HdfDeviceObject *device, struct DeviceResourceNode *node) +{ + int32_t ret; + struct ClockDevice *clockDevice = NULL; + + (void)device; + clockDevice = (struct ClockDevice *)OsalMemCalloc(sizeof(*clockDevice)); + if (clockDevice == NULL) { + HDF_LOGE("ClockParseAndDeviceAdd: alloc clockDevice fail!"); + return HDF_ERR_MALLOC_FAIL; + } + ret = ClockReadDrs(clockDevice, node); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockParseAndDeviceAdd: read drs fail, ret: %d!", ret); + OsalMemFree(clockDevice); + return ret; + } + + clockDevice->priv = (void *)node; + clockDevice->ops = &g_method; + + ret = ClockDeviceAdd(clockDevice); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockParseAndDeviceAdd: add clock device:%u fail!", clockDevice->deviceIndex); + OsalMemFree(clockDevice); + return ret; + } + + return HDF_SUCCESS; +} + +static int32_t LinuxClockInit(struct HdfDeviceObject *device) +{ + int32_t ret = HDF_SUCCESS; + struct DeviceResourceNode *childNode = NULL; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("LinuxClockInit: device or property is null"); + return HDF_ERR_INVALID_OBJECT; + } + + DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { + ret = ClockParseAndDeviceAdd(device, childNode); + if (ret != HDF_SUCCESS) { + HDF_LOGE("LinuxClockInit: clock init fail!"); + return ret; + } + } + HDF_LOGE("LinuxClockInit: clock init success!"); + + return HDF_SUCCESS; +} + +static void ClockRemoveByNode(const struct DeviceResourceNode *node) +{ + int32_t ret; + int32_t deviceIndex; + struct ClockDevice *device = NULL; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("ClockRemoveByNode: invalid drs ops!"); + return; + } + + ret = drsOps->GetUint32(node, "deviceIndex", (uint32_t *)&deviceIndex, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockRemoveByNode: read deviceIndex fail, ret: %d!", ret); + return; + } + + device = ClockDeviceGet(deviceIndex); + if (device != NULL && device->priv == node) { + ret = ClockStop(device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockRemoveByNode: close fail, ret: %d!", ret); + } + if (device->parent && device->parent->deviceName == NULL) { + ClockDeviceRemove(device->parent); + OsalMemFree(device->parent); + } + ClockDeviceRemove(device); + OsalMemFree(device); + } +} + +static void LinuxClockRelease(struct HdfDeviceObject *device) +{ + const struct DeviceResourceNode *childNode = NULL; + if (device == NULL || device->property == NULL) { + HDF_LOGE("LinuxClockRelease: device or property is null!"); + return; + } + DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { + ClockRemoveByNode(childNode); + } +} + +struct HdfDriverEntry g_clockLinuxDriverEntry = { + .moduleVersion = 1, + .Bind = NULL, + .Init = LinuxClockInit, + .Release = LinuxClockRelease, + .moduleName = "linux_clock_adapter", +}; +HDF_INIT(g_clockLinuxDriverEntry); diff --git a/adapter/khdf/linux/platform/platform.mk b/adapter/khdf/linux/platform/platform.mk index 133e097d773c9f50738db9bdab5a5398aa403daf..eb52f295f213380629d438faecccb74bf964f597 100644 --- a/adapter/khdf/linux/platform/platform.mk +++ b/adapter/khdf/linux/platform/platform.mk @@ -1,5 +1,5 @@ # -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. +# Copyright (c) 2020-2023 Huawei Device Co., Ltd. # # This software is licensed under the terms of the GNU General Public # License version 2, as published by the Free Software Foundation, and @@ -17,6 +17,7 @@ ccflags-$(CONFIG_DRIVERS_HDF_PLATFORM) +=-I$(srctree)/drivers/hdf/framework/incl -I$(srctree)/drivers/hdf/framework/support/platform/include \ -I$(srctree)/drivers/hdf/framework/support/platform/include/fwk \ -I$(srctree)/drivers/hdf/framework/support/platform/include/adc \ + -I$(srctree)/drivers/hdf/framework/support/platform/include/clock \ -I$(srctree)/drivers/hdf/framework/support/platform/include/dma \ -I$(srctree)/drivers/hdf/framework/support/platform/include/gpio \ -I$(srctree)/drivers/hdf/framework/support/platform/include/hdmi \ diff --git a/adapter/khdf/linux/test/Makefile b/adapter/khdf/linux/test/Makefile index 571b8823101cea7ec2f0f8793b77f94ca011163f..1de758bffbd68ce4bd264a685b31b95bf1926c5f 100644 --- a/adapter/khdf/linux/test/Makefile +++ b/adapter/khdf/linux/test/Makefile @@ -87,6 +87,10 @@ obj-$(CONFIG_DRIVERS_HDF_PLATFORM_ADC) += $(HDF_FRAMWORK_TEST_ROOT)/platform/com $(HDF_FRAMWORK_TEST_ROOT)/platform/common/adc_driver_test.o \ $(HDF_FRAMWORK_TEST_ROOT)/platform/entry/hdf_adc_entry_test.o \ $(HDF_FRAMWORK_TEST_ROOT)/platform/virtual/adc_linux_virtual_iio_driver.o +obj-$(CONFIG_DRIVERS_HDF_PLATFORM_CLOCK) += $(HDF_FRAMWORK_TEST_ROOT)/platform/common/clock_test.o \ + $(HDF_FRAMWORK_TEST_ROOT)/platform/common/clock_driver_test.o \ + $(HDF_FRAMWORK_TEST_ROOT)/platform/entry/hdf_clock_entry_test.o \ + $(HDF_FRAMWORK_TEST_ROOT)/platform/virtual/clock_virtual.o obj-$(CONFIG_DRIVERS_HDF_WIFI) += $(HDF_FRAMWORK_TEST_ROOT)/wifi/hdf_wifi_test.o \ $(HDF_FRAMWORK_TEST_ROOT)/model/network/wifi/unittest/netdevice/net_device_test.o \ diff --git a/adapter/khdf/liteos/model/display/BUILD.gn b/adapter/khdf/liteos/model/display/BUILD.gn index b551df28118071f52a5548e476d8de6fe7d3896e..d7103efcef04dba858666afc5baae28ac414de7c 100644 --- a/adapter/khdf/liteos/model/display/BUILD.gn +++ b/adapter/khdf/liteos/model/display/BUILD.gn @@ -56,6 +56,10 @@ hdf_driver(module_name) { sources += [ "$FRAMEWORKS_DISPLAY_ROOT/panel/mipi_icn9700.c" ] } + if (defined(LOSCFG_DRIVERS_HDF_DUAL_LCD_ICN9700_ST7701SN)) { + sources += [ "$HDF_FRAMEWORKS_PATH/../../../device/board/hisilicon/hispark_taurus/display_drivers/mipi_icn9700_st7701sn.c" ] + } + if (defined(LOSCFG_DRIVERS_HDF_LCD_ST7789)) { sources += [ "$FRAMEWORKS_DISPLAY_ROOT/panel/ssp_st7789.c" ] } diff --git a/adapter/khdf/liteos/model/display/Kconfig b/adapter/khdf/liteos/model/display/Kconfig index ea904842195203e40fa7bbf5c62f6e3287b271ff..28e35b7f9be26344fa66e0d6f50ea000d858fa58 100644 --- a/adapter/khdf/liteos/model/display/Kconfig +++ b/adapter/khdf/liteos/model/display/Kconfig @@ -50,3 +50,9 @@ config DRIVERS_HDF_LCD_ST7789 depends on DRIVERS_HDF_DISP help Answer Y to enable HDF St7789 driver. +config DRIVERS_HDF_DUAL_LCD_ICN9700_ST7701SN + bool "Enable HDF Icn9700&ST7701SN drivers" + default n + depends on DRIVERS_HDF_DISP + help + Answer Y to enable HDF Icn9700&ST7701SN drivers. \ No newline at end of file diff --git a/adapter/khdf/liteos/model/display/Makefile b/adapter/khdf/liteos/model/display/Makefile index 13655b4d88f118ee356b63387ed8886e9c39512d..a2cf1d4fadef52f1733d32793c98d5401e2b691c 100644 --- a/adapter/khdf/liteos/model/display/Makefile +++ b/adapter/khdf/liteos/model/display/Makefile @@ -56,6 +56,10 @@ ifeq ($(LOSCFG_DRIVERS_HDF_LCD_ICN9700), y) LOCAL_SRCS += $(LITEOSTOPDIR)/../../drivers/hdf_core/framework/model/display/driver/panel/mipi_icn9700.c endif +ifeq ($(LOSCFG_DRIVERS_HDF_DUAL_LCD_ICN9700_ST7701SN), y) +LOCAL_SRCS += $(LITEOSTOPDIR)/../../device/board/hisilicon/hispark_taurus/display_drivers/mipi_icn9700_st7701sn.c +endif + ifeq ($(LOSCFG_DRIVERS_HDF_LCD_ST7789), y) LOCAL_SRCS += $(LITEOSTOPDIR)/../../drivers/hdf_core/framework/model/display/driver/panel/ssp_st7789.c endif diff --git a/adapter/khdf/liteos/model/network/wifi/Makefile b/adapter/khdf/liteos/model/network/wifi/Makefile index 436d7d4a3da04795e5b5bcbb6b08ebbb62247839..cce37acb38b73bf0f218af32c4562f7b0cbebb9d 100644 --- a/adapter/khdf/liteos/model/network/wifi/Makefile +++ b/adapter/khdf/liteos/model/network/wifi/Makefile @@ -1,4 +1,4 @@ -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. +# Copyright (c) 2020-2023 Huawei Device Co., Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: @@ -77,6 +77,8 @@ ifeq ($(LOSCFG_DRIVERS_HDF_WLAN_SDIO), y) LOCAL_SRCS += $(IBUS_PATH)/hdf_sdio_intf.c else ifeq ($(LOSCFG_DRIVERS_HDF_WLAN_USB), y) LOCAL_SRCS += $(IBUS_PATH)/hdf_usb_intf.c +else ifeq ($(LOSCFG_DRIVERS_HDF_WLAN_PCIE), y) +LOCAL_SRCS += $(IBUS_PATH)/hdf_pcie_intf.c endif MESSAGE_INCLUDE += -I $(PLATFORM_PATH)/include/message \ diff --git a/adapter/khdf/liteos/model/network/wifi/bus/BUILD.gn b/adapter/khdf/liteos/model/network/wifi/bus/BUILD.gn index ef4fc494d5312469fe29e9877d9b14d5f0dfab89..fef4b42adcbdbf2c19fecdfed5cb9ea7d82398f0 100644 --- a/adapter/khdf/liteos/model/network/wifi/bus/BUILD.gn +++ b/adapter/khdf/liteos/model/network/wifi/bus/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: @@ -37,6 +37,8 @@ hdf_driver(module_name) { sources += [ "$FRAMEWORKS_WIFI_ROOT/bus/hdf_sdio_intf.c" ] } else if (defined(LOSCFG_DRIVERS_HDF_WLAN_USB)) { sources += [ "$FRAMEWORKS_WIFI_ROOT/bus/hdf_usb_intf.c" ] + } else if (defined(LOSCFG_DRIVERS_HDF_WLAN_PCIE)) { + sources += [ "$FRAMEWORKS_WIFI_ROOT/bus/hdf_pcie_intf.c" ] } include_dirs = [ diff --git a/adapter/khdf/liteos/model/network/wifi/bus/Kconfig b/adapter/khdf/liteos/model/network/wifi/bus/Kconfig index c45d54f3dce49542be229fcc3fb19e7546cdd642..53a3057499c7ad54e217ececfd37cf747c82a0ae 100644 --- a/adapter/khdf/liteos/model/network/wifi/bus/Kconfig +++ b/adapter/khdf/liteos/model/network/wifi/bus/Kconfig @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: @@ -34,7 +34,7 @@ config DRIVERS_HDF_WIFI_BUS if DRIVERS_HDF_WIFI_BUS choice - prompt "Select wlan sdio or usb source" + prompt "Select wlan sdio, usb or pcie source" default DRIVERS_HDF_WLAN_SDIO config DRIVERS_HDF_WLAN_SDIO @@ -50,5 +50,12 @@ choice depends on DRIVERS_HDF_USB_PNP_NOTIFY help Answer Y to enable HDF WLAN Usb Host driver. + + config DRIVERS_HDF_WLAN_PCIE + bool "Enable HDF WLAN Pcie Host driver" + default n + depends on DRIVERS_HDF_PLATFORM_PCIE + help + Answer Y to enable HDF WLAN Pcie Host driver. endchoice endif diff --git a/adapter/khdf/liteos/osal/include/hdf_log_adapter.h b/adapter/khdf/liteos/osal/include/hdf_log_adapter.h index 7c64e39cea99dc1505ac08002c1aba6d76b74a96..008b9b4f7796a0833a6a82281cdb1bd38aef8e5c 100644 --- a/adapter/khdf/liteos/osal/include/hdf_log_adapter.h +++ b/adapter/khdf/liteos/osal/include/hdf_log_adapter.h @@ -41,7 +41,7 @@ extern "C" { #ifdef LOSCFG_BASE_CORE_HILOG #undef LOG_DOMAIN -#define LOG_DOMAIN 0xD002500 +#define LOG_DOMAIN 0xD002510 #define HDF_LOGV_WRAPPER(fmt, arg...) HILOG_DEBUG(LOG_DOMAIN, fmt, ##arg) diff --git a/adapter/khdf/liteos/test/BUILD.gn b/adapter/khdf/liteos/test/BUILD.gn index da13cdeb316520f9093c3475282b37b85146dbbb..3e82dfcd17986cb815bdb46c00cbeab91d018c16 100644 --- a/adapter/khdf/liteos/test/BUILD.gn +++ b/adapter/khdf/liteos/test/BUILD.gn @@ -250,6 +250,13 @@ hdf_driver(module_name) { "$HDF_TEST_FRAMWORK_ROOT/platform/virtual/pcie_virtual.c", ] } + if (defined(LOSCFG_DRIVERS_HDF_WLAN_PCIE)) { + sources += [ + "$HDF_TEST_FRAMWORK_ROOT/platform/common/pcie_bus_driver_test.c", + "$HDF_TEST_FRAMWORK_ROOT/platform/common/pcie_bus_test.c", + "$HDF_TEST_FRAMWORK_ROOT/platform/entry/hdf_pcie_bus_entry_test.c", + ] + } if (defined(LOSCFG_DRIVERS_HDF_PLATFORM_PWM)) { sources += [ @@ -318,6 +325,7 @@ config("test_lite") { "$HDF_TEST_FRAMWORK_ROOT/adapter/osal/include", "$HDF_TEST_FRAMWORK_ROOT/utils/hcs_parser/unittest", "$HDF_TEST_FRAMWORK_ROOT", + "$HDF_FRAMEWORKS_PATH/include/wifi", ] if (defined(LOSCFG_DRIVERS_HDF_WIFI)) { diff --git a/adapter/khdf/liteos/test/Makefile b/adapter/khdf/liteos/test/Makefile index 2f70c1614d23baca7a183a146783f262fa045f19..822d4be16b36981239dee9340b2223868ea4698a 100644 --- a/adapter/khdf/liteos/test/Makefile +++ b/adapter/khdf/liteos/test/Makefile @@ -1,4 +1,4 @@ -# Copyright (c) 2020-2022 Huawei Device Co., Ltd. All rights reserved. +# Copyright (c) 2020-2023 Huawei Device Co., Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: @@ -161,6 +161,11 @@ LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/common/pcie_test.c LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/entry/hdf_pcie_entry_test.c LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/virtual/pcie_virtual.c endif +ifeq ($(LOSCFG_DRIVERS_HDF_WLAN_PCIE), y) +LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/common/pcie_bus_driver_test.c +LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/common/pcie_bus_test.c +LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/entry/hdf_pcie_bus_entry_test.c +endif ifeq ($(LOSCFG_DRIVERS_HDF_PLATFORM_EMMC), y) LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/common/emmc_test.c LOCAL_SRCS += $(HDF_TEST_FRAMWORK_ROOT)/platform/entry/hdf_emmc_entry_test.c diff --git a/adapter/khdf/liteos/test/test_lite.mk b/adapter/khdf/liteos/test/test_lite.mk index 731cf5999fae643adcdccf7eaf92f29c6f941197..f78ce60ff54c60bdaaabf7721e3a278e2be65686 100644 --- a/adapter/khdf/liteos/test/test_lite.mk +++ b/adapter/khdf/liteos/test/test_lite.mk @@ -1,4 +1,4 @@ -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. +# Copyright (c) 2020-2023 Huawei Device Co., Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: @@ -65,7 +65,7 @@ HDF_TEST_INCLUDE += -I $(HDF_ROOT_TEST_DIR)/hdf_core/framework/test/unittest/uti HDF_TEST_INCLUDE += -I $(HDF_ROOT_TEST_DIR)/hdf_core/framework/test/unittest HDF_TEST_INCLUDE += -I $(LITEOSTOPDIR)/bsd/compat/linuxkpi/include HDF_TEST_INCLUDE += -I $(LITEOSTOPDIR)/../../base/hiviewdfx/hilog_lite/interfaces/native/innerkits - +HDF_TEST_INCLUDE += -I $(HDF_ROOT_TEST_DIR)/hdf_core/framework/include/wifi ifeq ($(LOSCFG_DRIVERS_HDF_WIFI), y) HDF_TEST_INCLUDE += -I $(HDF_ROOT_TEST_DIR)/hdf_core/framework/test/unittest/model/network/wifi/unittest/netdevice HDF_TEST_INCLUDE += -I $(HDF_ROOT_TEST_DIR)/hdf_core/framework/test/unittest/model/network/wifi/unittest/module diff --git a/adapter/khdf/liteos_m/osal/include/hdf_log_adapter.h b/adapter/khdf/liteos_m/osal/include/hdf_log_adapter.h index 3a91995c3b8a103c60d4cff612d379de1b2dfa4f..b0193eedbcb435f598c4cc744ee95dc27bbd5f93 100644 --- a/adapter/khdf/liteos_m/osal/include/hdf_log_adapter.h +++ b/adapter/khdf/liteos_m/osal/include/hdf_log_adapter.h @@ -41,7 +41,7 @@ extern "C" { #ifdef LOSCFG_BASE_CORE_HILOG #undef LOG_DOMAIN -#define LOG_DOMAIN 0xD002500 +#define LOG_DOMAIN 0xD002510 #define HDF_LOGV_WRAPPER(fmt, arg...) HILOG_DEBUG(LOG_DOMAIN, fmt, ##arg) diff --git a/adapter/khdf/uniproton/osal/include/hdf_log_adapter.h b/adapter/khdf/uniproton/osal/include/hdf_log_adapter.h index 4186ae3431e7b2d1874678f3b9bb8b04ebbad0b4..c734168dbda9c9018208222d86ac0fffdb78015a 100644 --- a/adapter/khdf/uniproton/osal/include/hdf_log_adapter.h +++ b/adapter/khdf/uniproton/osal/include/hdf_log_adapter.h @@ -41,7 +41,7 @@ extern "C" { #ifdef LOSCFG_BASE_CORE_HILOG #undef LOG_DOMAIN -#define LOG_DOMAIN 0xD002500 +#define LOG_DOMAIN 0xD002510 #define HDF_LOGV_WRAPPER(fmt, arg...) HILOG_DEBUG(LOG_DOMAIN, fmt, ##arg) diff --git a/adapter/uhdf/hdi_small.gni b/adapter/uhdf/hdi_small.gni index 9b05b447f080facab11c6e7e4e1a9df490929100..37640791a419a2d0291a962fbf1604776cc404fb 100644 --- a/adapter/uhdf/hdi_small.gni +++ b/adapter/uhdf/hdi_small.gni @@ -126,15 +126,16 @@ template("hdi_small") { if (defined(invoker.sources)) { sources = hdi_build_info.proxy_sources public_configs = [ ":$idl_headers_config" ] - deps = [ - ":hdi_gen", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//third_party/bounds_checking_function:libsec_shared", - ] + deps = [ ":hdi_gen" ] public_deps = hdi_build_info.proxy_deps - external_deps = [ "hdf_core:libhdi" ] + external_deps = [ + "bounds_checking_function:libsec_shared", + "hdf_core:libhdi", + "hilog_lite:hilog_shared", + ] + if (invoker.language == "c") { external_deps += [ "hdf_core:libhdf_utils" ] } @@ -150,6 +151,12 @@ template("hdi_small") { } } + lib_server = "lib" + target_name + "_stub" + "_" + hdi_build_info.version + group(lib_server) { + public_configs = [ ":$idl_headers_config" ] + deps = [ ":hdi_gen" ] + } + # generate code and shared library group("$target_name" + "_idl_target") { deps = [ ":$lib_client" ] diff --git a/adapter/uhdf/platform/BUILD.gn b/adapter/uhdf/platform/BUILD.gn index ce25b50f0ed07b31b883c4e0250fa852e494978c..cee61d4c705ff9e4918acec012f66c0570605f8b 100644 --- a/adapter/uhdf/platform/BUILD.gn +++ b/adapter/uhdf/platform/BUILD.gn @@ -77,7 +77,7 @@ ohos_shared_library("hdf_platform") { external_deps = [ "hdf_core:hdf_posix_osal", - "hilog_featured_lite:hilog_shared", + "hilog_lite:hilog_shared", ] defines = [ "__USER__" ] diff --git a/adapter/uhdf/posix/include/hdf_log_adapter.h b/adapter/uhdf/posix/include/hdf_log_adapter.h index 156d81587115e8cecafccd7c82792c193de4ec2c..62cadbe6a551444071e4c28f79c40c1a40caf876 100644 --- a/adapter/uhdf/posix/include/hdf_log_adapter.h +++ b/adapter/uhdf/posix/include/hdf_log_adapter.h @@ -23,7 +23,7 @@ extern "C" { #endif /* __cplusplus */ #undef LOG_DOMAIN -#define LOG_DOMAIN 0xD002500 +#define LOG_DOMAIN 0xD002510 #define HDF_LOGV_WRAPPER(fmt, arg...) HILOG_DEBUG(LOG_DOMAIN, fmt, ##arg) diff --git a/adapter/uhdf/test/unittest/platform/BUILD.gn b/adapter/uhdf/test/unittest/platform/BUILD.gn index 607f6c8a9f2344336cd0378514b867bc5d3d1539..055ae11f14e4c93ff8af154d29a8a53604544007 100644 --- a/adapter/uhdf/test/unittest/platform/BUILD.gn +++ b/adapter/uhdf/test/unittest/platform/BUILD.gn @@ -30,6 +30,8 @@ if (hdf_core_platform_test_support) { "$hdf_framework_path/uhdf/posix/include", "$hdf_framework_path/include/utils", "$hdf_framework_path/include", + "$hdf_framework_path/include/wifi", + "$hdf_framework_path/model/network/wifi/include", "$hdf_framework_path/test/unittest/include", "$hdf_framework_path/test/unittest/platform/common", "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", @@ -74,6 +76,7 @@ if (hdf_core_platform_test_support) { "$hdf_framework_path/support/platform/test/unittest/common/hdf_i2s_test.cpp", "$hdf_framework_path/support/platform/test/unittest/common/hdf_i3c_test.cpp", "$hdf_framework_path/support/platform/test/unittest/common/hdf_mipi_csi_test.cpp", + "$hdf_framework_path/support/platform/test/unittest/common/hdf_pcie_bus_test.cpp", "$hdf_framework_path/support/platform/test/unittest/common/hdf_pcie_test.cpp", "$hdf_framework_path/support/platform/test/unittest/common/hdf_pin_test.cpp", "$hdf_framework_path/support/platform/test/unittest/common/hdf_timer_test.cpp", diff --git a/adapter/uhdf2/hdi.gni b/adapter/uhdf2/hdi.gni index bfcec6b7ced4c4d21732d7dd6066bdbc81ff5364..ad825e20f47670cadce772e76baf77af8de74d42 100644 --- a/adapter/uhdf2/hdi.gni +++ b/adapter/uhdf2/hdi.gni @@ -179,7 +179,12 @@ template("hdi") { innerapi_tags = invoker.innerapi_tags } shlib_type = "hdi_proxy" - install_images = [ system_base_dir ] + if (defined(invoker.install_images)) { + install_images = invoker.install_images + } else { + install_images = [ system_base_dir ] + } + subsystem_name = invoker.subsystem_name partname_list = string_split(invoker.part_name, "_") if (partname_list[0] == "drivers") { @@ -187,6 +192,14 @@ template("hdi") { } else { part_name = invoker.part_name + "_interface" } + + if (defined(invoker.stack_protector_ret)) { + stack_protector_ret = invoker.stack_protector_ret + } + + if (defined(invoker.sanitize)) { + sanitize = invoker.sanitize + } } } @@ -230,6 +243,14 @@ template("hdi") { install_images = [ chipset_base_dir ] subsystem_name = invoker.subsystem_name part_name = invoker.part_name + + if (defined(invoker.stack_protector_ret)) { + stack_protector_ret = invoker.stack_protector_ret + } + + if (defined(invoker.sanitize)) { + sanitize = invoker.sanitize + } } } } diff --git a/adapter/uhdf2/hdi/BUILD.gn b/adapter/uhdf2/hdi/BUILD.gn index 35551d46bc486ca1ea31d25d5cf896d54e7c28c9..555ec83eea7662a67ee6b589c606d974c79e3afb 100644 --- a/adapter/uhdf2/hdi/BUILD.gn +++ b/adapter/uhdf2/hdi/BUILD.gn @@ -123,7 +123,10 @@ if (defined(ohos_lite)) { "chipsetsdk", "platformsdk_indirect", ] - install_images = [ system_base_dir ] + install_images = [ + system_base_dir, + updater_base_dir, + ] subsystem_name = "hdf" part_name = "hdf_core" } diff --git a/adapter/uhdf2/hdi/test/smq_test/smq_test.cpp b/adapter/uhdf2/hdi/test/smq_test/smq_test.cpp index f062b46d77fce4e845d8c47deeda6b9e451ea2da..1f624f42d5c330a6a1e493c7a05945c514940cb4 100644 --- a/adapter/uhdf2/hdi/test/smq_test/smq_test.cpp +++ b/adapter/uhdf2/hdi/test/smq_test/smq_test.cpp @@ -81,10 +81,10 @@ static bool QueryPidOfHostName(const std::string &hostName, int &hostPid) return false; } - // ps -ef | grep hostName | grep -v "grep" | sed 's/\s\s*/ /g' | cut -d ' ' -f 2 + // ps -ef | grep hostName | grep -v "grep" | sed 's/ */ /g' | cut -d ' ' -f 2 std::ostringstream cmdStr; cmdStr << "ps -ef | grep '" << hostName << "' | grep -v 'grep' | "; - cmdStr << "sed 's/\\s\\s*/ /g' | cut -d ' ' -f 2"; + cmdStr << "sed 's/ */ /g' | cut -d ' ' -f 2"; FILE *res = popen(cmdStr.str().c_str(), "r"); if (res == nullptr) { HDF_LOGE("[%{public}s:%{public}d] failed to popen '%{public}s'", __func__, __LINE__, cmdStr.str().c_str()); diff --git a/adapter/uhdf2/host/test/unittest/devhost_test.cpp b/adapter/uhdf2/host/test/unittest/devhost_test.cpp index bad477e3046f5d8f96af988077a834e93d33785e..69d1286f14a978cf69ae0dd0bc67d97a42f857aa 100644 --- a/adapter/uhdf2/host/test/unittest/devhost_test.cpp +++ b/adapter/uhdf2/host/test/unittest/devhost_test.cpp @@ -18,6 +18,8 @@ #include "devhost_service.h" #include "devhost_service_stub.h" #include "devhost_service_proxy.h" +#include "devhost_dump.h" +#include "devhost_dump_reg.h" #include "device_service_stub.h" #include "devmgr_service_clnt.h" #include "devmgr_service_proxy.h" @@ -28,6 +30,7 @@ #include "hdf_device_node.h" #include "hdf_remote_service.h" #include "hdf_log.h" +#include "hdf_sbuf.h" #include "osal_mem.h" #define HDF_LOG_TAG host_test @@ -410,4 +413,156 @@ HWTEST_F(DevHostTest, DevHostDeviceServiceStubTest, TestSize.Level1) DevHostServiceStubRelease(nullptr); } + +static int32_t DevHostTestDumpHostFunc(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t argv = 0; + + (void)HdfSbufReadUint32(data, &argv); + HDF_LOGI("%{public}d", argv); + + const char *value = HdfSbufReadString(data); + while (value != NULL && argv > 0) { + HDF_LOGI("%{public}s", value); + value = HdfSbufReadString(data); + argv--; + } + + HdfSbufWriteString(reply, "test_host_dump\n"); + + return HDF_SUCCESS; +} + +static int32_t DevHostTestDumpServiceFunc(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t argv = 0; + (void)HdfSbufReadUint32(data, &argv); + HDF_LOGI("%{public}d", argv); + const char *value = HdfSbufReadString(data); + while (value != NULL && argv > 0) { + HDF_LOGI("%{public}s", value); + value = HdfSbufReadString(data); + argv--; + } + + HdfSbufWriteString(reply, "test_service_dump\n"); + + return HDF_SUCCESS; +} + +HWTEST_F(DevHostTest, DevHostDumpTest001, TestSize.Level1) +{ + DevHostDumpInit(); + HdfSBuf * testSBufData = HdfSbufTypedObtain(SBUF_RAW); + HdfSBuf * testSBufReply = HdfSbufTypedObtain(SBUF_RAW); + + // test DevHostDump NULL inpput + HDF_LOGI("test DevHostDump NULL inpput BEGIN"); + DevHostDump(nullptr, nullptr); + ASSERT_TRUE(HdfSbufReadString(testSBufReply) == NULL); + DevHostDump(testSBufData, nullptr); + ASSERT_TRUE(HdfSbufReadString(testSBufReply) == NULL); + DevHostDump(nullptr, testSBufReply); + ASSERT_TRUE(HdfSbufReadString(testSBufReply) == NULL); + HDF_LOGI("test DevHostDump NULL inpput END"); + + // test DevHostDump null option + HDF_LOGI("test DevHostDump null option BEGIN"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(HdfSbufReadString(testSBufReply) == NULL); + HDF_LOGI("test DevHostDump null option END"); + + // test DevHostDump invalid parameter brunch + HDF_LOGI("test DevHostDump invalid parameter brunch BEGIN"); + HdfSbufWriteString(testSBufData, "dumpNothing"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(HdfSbufReadString(testSBufReply) == NULL); + HDF_LOGI("test DevHostDump invalid parameter brunch END"); + + DevHostDumpDeInit(); +} + +HWTEST_F(DevHostTest, DevHostDumpTest002, TestSize.Level1) +{ + DevHostDumpInit(); + HdfSBuf * testSBufData = HdfSbufTypedObtain(SBUF_RAW); + HdfSBuf * testSBufReply = HdfSbufTypedObtain(SBUF_RAW); + + // test DevHostDump option dumpHost without dumpHostFunc + HDF_LOGI("test DevHostDump option dumpHost without dumpHostFunc BEGIN"); + HdfSbufFlush(testSBufData); + HdfSbufFlush(testSBufReply); + HdfSbufWriteString(testSBufData, "dumpHost"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(strcmp(HdfSbufReadString(testSBufReply), "The host does not register dump function\n") == 0); + HdfSbufFlush(testSBufData); + HdfSbufFlush(testSBufReply); + HDF_LOGI("test DevHostDump option dumpHost without dumpHostFunc END"); + + // test DevHostRegisterDumpHost NULL input + HDF_LOGI("test DevHostRegisterDumpHost NULL input BEGIN"); + int32_t ret = DevHostRegisterDumpHost(NULL); + ASSERT_TRUE(HDF_FAILURE == ret); + HDF_LOGI("test DevHostRegisterDumpHost NULL input END"); + + // test DevHostRegisterDumpHost normal brunch + HDF_LOGI("test DevHostRegisterDumpHost normal brunch BEGIN"); + ret = DevHostRegisterDumpHost(DevHostTestDumpHostFunc); + ASSERT_TRUE(HDF_SUCCESS == ret); + HDF_LOGI("test DevHostRegisterDumpHost normal brunch END"); + + // test DevHostDump option dumpHost with dumpHostFunc + HDF_LOGI("test DevHostDump option dumpHost with dumpHostFunc BEGIN"); + HdfSbufWriteString(testSBufData, "dumpHost"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(strcmp(HdfSbufReadString(testSBufReply), "test_host_dump\n") == 0); + HdfSbufFlush(testSBufData); + HdfSbufFlush(testSBufReply); + HDF_LOGI("test DevHostDump option dumpHost with dumpHostFunc END"); +} + +HWTEST_F(DevHostTest, DevHostDumpServiceTest, TestSize.Level1) +{ + HdfSBuf * testSBufData = HdfSbufTypedObtain(SBUF_RAW); + HdfSBuf * testSBufReply = HdfSbufTypedObtain(SBUF_RAW); + DevHostDumpInit(); + // test DevHostRegisterDumpService NULL input + HDF_LOGI("test DevHostRegisterDumpService NULL input BEGIN"); + int32_t ret = DevHostRegisterDumpService(nullptr, DevHostTestDumpServiceFunc); + ASSERT_TRUE(HDF_FAILURE == ret); + HDF_LOGI("test DevHostRegisterDumpService NULL input END"); + + // test DevHostRegisterDumpService with sample_driver_service + HDF_LOGI("test DevHostRegisterDumpService with sample_driver_service BEGIN"); + ret = DevHostRegisterDumpService("sample_driver_service", DevHostTestDumpServiceFunc); + ASSERT_TRUE(HDF_SUCCESS == ret); + HDF_LOGI("test DevHostRegisterDumpService with sample_driver_service END"); + + // test DevHostRegisterDumpService with sample_driver_service Redundantly + HDF_LOGI("test DevHostRegisterDumpService with sample_driver_service Redundantly BEGIN"); + ret = DevHostRegisterDumpService("sample_driver_service", DevHostTestDumpServiceFunc); + ASSERT_TRUE(HDF_FAILURE == ret); + HDF_LOGI("test DevHostRegisterDumpService with sample_driver_service Redundantly END"); + + // test DevDumpHost with option dumpService and wrong service name + HDF_LOGI("test DevDumpHost with option dumpService and wrong service name BEGIN"); + HdfSbufWriteString(testSBufData, "dumpService"); + HdfSbufWriteString(testSBufData, "no_driver_service"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(strcmp(HdfSbufReadString(testSBufReply), "The service does not register dump function\n") == 0); + HdfSbufFlush(testSBufData); + HdfSbufFlush(testSBufReply); + HDF_LOGI("test DevDumpHost with option dumpService and wrong service name END"); + + // test DevDumpHost with option dumpService and correct service name + HDF_LOGI("test DevDumpHost with option dumpService and correct service name BEGIN"); + HdfSbufWriteString(testSBufData, "dumpService"); + HdfSbufWriteString(testSBufData, "sample_driver_service"); + DevHostDump(testSBufData, testSBufReply); + ASSERT_TRUE(strcmp(HdfSbufReadString(testSBufReply), "test_service_dump\n") == 0); + HdfSbufFlush(testSBufData); + HdfSbufFlush(testSBufReply); + DevHostDumpDeInit(); + HDF_LOGI("test DevDumpHost with option dumpService and correct service name END"); +} } // namespace OHOS diff --git a/adapter/uhdf2/ipc/BUILD.gn b/adapter/uhdf2/ipc/BUILD.gn index 1e76c8264bf747c17413c647bceae681f4c6bfea..302894090e5779db7df90df4fca3f2e691795a3e 100644 --- a/adapter/uhdf2/ipc/BUILD.gn +++ b/adapter/uhdf2/ipc/BUILD.gn @@ -66,7 +66,10 @@ if (defined(ohos_lite)) { "chipsetsdk", "platformsdk_indirect", ] - install_images = [ system_base_dir ] + install_images = [ + system_base_dir, + updater_base_dir, + ] subsystem_name = "hdf" part_name = "hdf_core" } diff --git a/adapter/uhdf2/manager/BUILD.gn b/adapter/uhdf2/manager/BUILD.gn index 658b36fa9bfe27b4e66c3418c7d85beecb32e00d..ad65b7d2d22fe43dab28a73a8a8770ec97b8fe22 100644 --- a/adapter/uhdf2/manager/BUILD.gn +++ b/adapter/uhdf2/manager/BUILD.gn @@ -19,6 +19,12 @@ hdf_interfaces_path = "./../../../interfaces" hdf_uhdf_path = "./.." ohos_executable("hdf_devmgr") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } defines = [ "__USER__" ] include_dirs = [ "$hdf_framework_path/core/manager/include", diff --git a/adapter/uhdf2/platform/BUILD.gn b/adapter/uhdf2/platform/BUILD.gn index cd4ec0cff72f9e03392e2e2241aaa129b7ff057b..ba8af2cadab6eff48ead9fe36f9801e07a12bd3d 100644 --- a/adapter/uhdf2/platform/BUILD.gn +++ b/adapter/uhdf2/platform/BUILD.gn @@ -36,6 +36,7 @@ if (is_standard_system) { public_configs = [ ":libhdf_platform_pub_config" ] sources = [ "$HDF_FRAMEWORKS/support/platform/src/adc/adc_if_u.c", + "$HDF_FRAMEWORKS/support/platform/src/clock/clock_if_u.c", "$HDF_FRAMEWORKS/support/platform/src/fwk/platform_listener_u.c", "$HDF_FRAMEWORKS/support/platform/src/gpio/gpio_if_u.c", "$HDF_FRAMEWORKS/support/platform/src/i2c/i2c_if_u.c", diff --git a/framework/core/manager/src/devmgr_service.c b/framework/core/manager/src/devmgr_service.c index 7082b438e26726c22fec5551db720a3acd8721a5..38c7b3bddafdf7a38d96e298c8c6fb0c4472d2b3 100644 --- a/framework/core/manager/src/devmgr_service.c +++ b/framework/core/manager/src/devmgr_service.c @@ -174,6 +174,12 @@ static int DevmgrServiceUnloadDevice(struct IDevmgrService *devMgrSvc, const cha HDF_LOGD("%{public}s host %{public}s devices is not empty", __func__, hostClnt->hostName); return HDF_SUCCESS; } + if (!HdfSListIsEmpty(&hostClnt->unloadDevInfos)) { + OsalMutexUnlock(&hostClnt->hostLock); + HDF_LOGD("%{public}s the hdf_devmgr need not to stop automatically started host %{public}s", __func__, + hostClnt->hostName); + return HDF_SUCCESS; + } hostClnt->hostPid = INVALID_PID; hostClnt->hostService = NULL; // old hostService will be recycled in CleanupDiedHostResources HdfSListFlush(&hostClnt->devices, DeviceTokenClntDelete); diff --git a/framework/include/platform/clock_if.h b/framework/include/platform/clock_if.h new file mode 100644 index 0000000000000000000000000000000000000000..682504b20bd6e62c9098a4482fb1c4bd4b887e88 --- /dev/null +++ b/framework/include/platform/clock_if.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef CLOCK_IF_H +#define CLOCK_IF_H + +#include "platform_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ +#define MAX_PATH_LEN 120 + +DevHandle ClockOpen(uint32_t number); + +int32_t ClockClose(DevHandle handle); + +int32_t ClockEnable(DevHandle handle); + +int32_t ClockDisable(DevHandle handle); + +int32_t ClockSetRate(DevHandle handle, uint32_t rate); + +int32_t ClockGetRate(DevHandle handle, uint32_t *rate); + +int32_t ClockSetParent(DevHandle child, DevHandle parent); + +DevHandle ClockGetParent(DevHandle handle); + +/** + * @brief 枚举 CLOCK I/O 命令. + * + * @since 1.0 + */ +enum ClockIoCmd { + CLOCK_IO_OPEN = 0, + CLOCK_IO_CLOSE, + CLOCK_IO_ENABLE, + CLOCK_IO_DISABLE, + CLOCK_IO_SET_RATE, + CLOCK_IO_GET_RATE, + CLOCK_IO_SET_PARENT, + CLOCK_IO_GET_PARENT, +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* CLOCK_IF_H */ diff --git a/framework/include/wifi/hdf_ibus_intf.h b/framework/include/wifi/hdf_ibus_intf.h index 2afe8df09da984efd750df2662133017d230f161..3aea2a6e9c50b55e2965af685fbbb7d9ea52ed0d 100644 --- a/framework/include/wifi/hdf_ibus_intf.h +++ b/framework/include/wifi/hdf_ibus_intf.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. @@ -19,7 +19,7 @@ extern "C" { struct BusDev; typedef void IrqHandler(void *); - +typedef int32_t MapHandler(void *); struct SdioConfigInfo { uint32_t maxBlockNum; uint32_t maxBlockSize; @@ -65,6 +65,13 @@ struct DevOps { void (*claimHost)(struct BusDev *dev); void (*releaseHost)(struct BusDev *dev); + + // dma map/unmap + int32_t (*dmaMap)(struct BusDev *dev, MapHandler* cb, uintptr_t addr, uint32_t len, uint8_t dir); + int32_t (*dmaUnmap)(struct BusDev *dev, uintptr_t addr, uint32_t len, uint8_t dir); + // io read/write + int32_t (*ioRead)(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf); + int32_t (*ioWrite)(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf); }; struct BusDev { diff --git a/framework/model/audio/common/src/audio_platform_base.c b/framework/model/audio/common/src/audio_platform_base.c index 2b93ecfc3de55e75f0d33d11d381f1a00514853e..1c22199423e64b6f24e20d18e02d2b0374d7ef24 100755 --- a/framework/model/audio/common/src/audio_platform_base.c +++ b/framework/model/audio/common/src/audio_platform_base.c @@ -1101,16 +1101,16 @@ static int32_t AudioPcmTransferBytes(struct PlatformData *data, enum AudioStream } if (streamType == AUDIO_RENDER_STREAM) { - data->renderBufInfo.oneMsBytes = data->renderPcmInfo.rate * data->renderPcmInfo.frameSize - / SECOND_TO_MILLISECOND; + data->renderBufInfo.oneMsBytes = + data->renderPcmInfo.rate * data->renderPcmInfo.frameSize / SECOND_TO_MILLISECOND; if (data->renderBufInfo.oneMsBytes == 0) { AUDIO_DRIVER_LOG_ERR("render pcm info is error."); return HDF_FAILURE; } AUDIO_DRIVER_LOG_DEBUG("render pcm one ms transfer bytes is %d .", data->renderBufInfo.oneMsBytes); } else if (streamType == AUDIO_CAPTURE_STREAM) { - data->captureBufInfo.oneMsBytes = data->capturePcmInfo.rate * data->capturePcmInfo.frameSize - / SECOND_TO_MILLISECOND; + data->captureBufInfo.oneMsBytes = + data->capturePcmInfo.rate * data->capturePcmInfo.frameSize / SECOND_TO_MILLISECOND; if (data->captureBufInfo.oneMsBytes == 0) { AUDIO_DRIVER_LOG_ERR("capture pcm info is error."); return HDF_FAILURE; diff --git a/framework/model/audio/usb/src/audio_usb_dma_ops.c b/framework/model/audio/usb/src/audio_usb_dma_ops.c index a9e8bd832881043133052c72c67219ab89e1420d..8c23fd3264cf02817d15a54486c6ea363096b9ff 100644 --- a/framework/model/audio/usb/src/audio_usb_dma_ops.c +++ b/framework/model/audio/usb/src/audio_usb_dma_ops.c @@ -316,18 +316,13 @@ static int32_t AudioUsbGetEndpoint(struct AudioUsbFormat *audioUsbFormat, struct } epDesc = AudioEndpointDescriptor(alts, USB_ENDPOINT_INDEX_1); - if ((epDesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC) { - epTypeIsoc = true; - } - if (epDesc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE) { - epDescAudioSize = true; - } - + epTypeIsoc = ((epDesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC); + epDescAudioSize = (epDesc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE); if (epTypeIsoc || (epDescAudioSize && epDesc->bSynchAddress != 0)) { AUDIO_DEVICE_LOG_ERR("%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n", audioUsbFormat->iface, audioUsbFormat->altsetting, epDesc->bmAttributes, epDesc->bLength, epDesc->bSynchAddress); - if (isRender && attr == USB_ENDPOINT_SYNC_NONE) { + if (isRender != 0 && attr == USB_ENDPOINT_SYNC_NONE) { return HDF_SUCCESS; } return -EINVAL; @@ -335,19 +330,13 @@ static int32_t AudioUsbGetEndpoint(struct AudioUsbFormat *audioUsbFormat, struct *epNum = epDesc->bEndpointAddress; epDesc = AudioEndpointDescriptor(alts, 0); - epDescAudioSize = false; - - if (epDesc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE && epDesc->bSynchAddress != 0) { - epDescAudioSize = true; - } - if ((isRender != 0 && *epNum != (uint32_t)(epDesc->bSynchAddress | USB_DIR_IN)) || - (isRender != 0 && *epNum != (uint32_t)(epDesc->bSynchAddress & ~USB_DIR_IN))) { - usbDirInva = true; - } - if (epDescAudioSize && usbDirInva) { + epDescAudioSize = (epDesc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE && epDesc->bSynchAddress != 0); + usbDirInva = (*epNum != (uint32_t)(epDesc->bSynchAddress | USB_DIR_IN) || + *epNum != (uint32_t)(epDesc->bSynchAddress & ~USB_DIR_IN)); + if (epDescAudioSize && isRender != 0 && usbDirInva) { AUDIO_DEVICE_LOG_ERR("%d:%d : invalid sync pipe. isRender %d, ep %02x, bSynchAddress %02x\n", audioUsbFormat->iface, audioUsbFormat->altsetting, isRender, *epNum, epDesc->bSynchAddress); - if (isRender && attr == USB_ENDPOINT_SYNC_NONE) { + if (attr == USB_ENDPOINT_SYNC_NONE) { return HDF_SUCCESS; } return -EINVAL; @@ -526,23 +515,11 @@ static bool AudioUsbFindFormatSub(struct PcmInfo *pcmInfo, struct AudioUsbFormat return true; } -static struct AudioUsbFormat *AudioUsbFindFormat(struct AudioUsbDriver *audioUsbDriver, struct PcmInfo *pcmInfo, - int usbPcmFormat, const enum AudioStreamType streamType) +static struct AudioUsbFormat *SeekAudioUsbListFindFormat(struct DListHead *audioUsbFormatList, + struct PcmInfo *pcmInfo, int usbPcmFormat, const enum AudioStreamType streamType) { struct AudioUsbFormat *fp = NULL, *found = NULL; uint32_t curAttr = 0, attr, i; - struct DListHead *audioUsbFormatList = NULL; - - if (streamType == AUDIO_RENDER_STREAM) { - audioUsbFormatList = &audioUsbDriver->renderUsbFormatList; - } else { - audioUsbFormatList = &audioUsbDriver->captureUsbFormatList; - } - - if (DListIsEmpty(audioUsbFormatList)) { - ADM_LOG_ERR("audioUsbFormatList is empty."); - return NULL; - } DLIST_FOR_EACH_ENTRY(fp, audioUsbFormatList, struct AudioUsbFormat, list) { if (!AudioUsbFindFormatSub(pcmInfo, fp, usbPcmFormat)) { continue; @@ -584,10 +561,27 @@ static struct AudioUsbFormat *AudioUsbFindFormat(struct AudioUsbDriver *audioUsb curAttr = attr; } } - return found; } +static struct AudioUsbFormat *AudioUsbFindFormat(struct AudioUsbDriver *audioUsbDriver, struct PcmInfo *pcmInfo, + int usbPcmFormat, const enum AudioStreamType streamType) +{ + struct DListHead *audioUsbFormatList = NULL; + + if (streamType == AUDIO_RENDER_STREAM) { + audioUsbFormatList = &audioUsbDriver->renderUsbFormatList; + } else { + audioUsbFormatList = &audioUsbDriver->captureUsbFormatList; + } + + if (DListIsEmpty(audioUsbFormatList)) { + ADM_LOG_ERR("audioUsbFormatList is empty."); + return NULL; + } + return SeekAudioUsbListFindFormat(audioUsbFormatList, pcmInfo, usbPcmFormat, streamType); +} + int32_t AudioUsbDmaConfigChannel(const struct PlatformData *data, const enum AudioStreamType streamType) { int32_t ret; diff --git a/framework/model/display/driver/lcdkit/lcdkit_parse_config.c b/framework/model/display/driver/lcdkit/lcdkit_parse_config.c index 64c3d3b8c1e00288901eebe75f99f6eb581f522b..88a0522e1df4872b8082718447a62b6374494b0d 100644 --- a/framework/model/display/driver/lcdkit/lcdkit_parse_config.c +++ b/framework/model/display/driver/lcdkit/lcdkit_parse_config.c @@ -36,6 +36,14 @@ static int32_t GetDsiCmdCount(uint8_t *array, int32_t len, uint32_t *count) return HDF_SUCCESS; } +static void FreeDsiPayload(struct DsiCmdDesc *dsiCmd, int32_t num) +{ + int32_t i; + for (i = 0; i < num; i++) { + OsalMemFree(dsiCmd[i]->payload); + } +} + static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, int32_t len) { struct DsiCmdDesc *dsiCmd = (struct DsiCmdDesc *)OsalMemCalloc(count * sizeof(struct DsiCmdDesc)); @@ -45,7 +53,6 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, return HDF_FAILURE; } int32_t ret; - int32_t i; int32_t num = 0; cmd->count = count; cmd->dsiCmd = dsiCmd; @@ -58,9 +65,7 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, tmpCmd->payload = (uint8_t *)OsalMemCalloc(tmpCmd->dataLen * sizeof(uint8_t)); if (tmpCmd->payload == NULL) { HDF_LOGE("%s: OsalMemCalloc failed", __func__); - for (i = 0; i < num; i++) { - OsalMemFree(dsiCmd[i]->payload); - } + FreeDsiPayload(dsiCmd, num); OsalMemFree(array); OsalMemFree(dsiCmd); cmd->dsiCmd = NULL; @@ -71,9 +76,7 @@ static int32_t ParseDsiCmd(struct PanelCmd *cmd, int32_t count, uint8_t *array, ret = memcpy_s(tmpCmd->payload, tmpCmd->dataLen, &tmpArray[DSI_CMD_HEAD], DSI_CMD_HEAD); if (ret != EOK) { HDF_LOGE("%s: memcpy_s failed, ret %d", __func__, ret); - for (i = 0; i < num; i++) { - OsalMemFree(dsiCmd[i]->payload); - } + FreeDsiPayload(dsiCmd, num); OsalMemFree(array); OsalMemFree(dsiCmd); cmd->dsiCmd = NULL; diff --git a/framework/model/display/driver/panel/ili9881_st_5p5.c b/framework/model/display/driver/panel/ili9881_st_5p5.c index 9dd6864bd202663212a154083c3ffa5a895b417a..6ca69a7faec9e5d53da8a492b2cc9681d1200a44 100755 --- a/framework/model/display/driver/panel/ili9881_st_5p5.c +++ b/framework/model/display/driver/panel/ili9881_st_5p5.c @@ -604,6 +604,27 @@ static void PanelResInit(struct panel_ili9881_dev *panel_dev) panel_dev->hw_delay.unprepare_delay = 20; /* 20:unprepare_delay */ } +static int32_t PanelRequestGpio(struct panel_ili9881_dev *panel_dev) +{ + struct panel_ili9881_dev *pdev = panel_dev; + pdev->enable_gpio = devm_gpiod_get_optional(&pdev->dsiDev->dev, "enable", GPIOD_ASIS); + if (IS_ERR(pdev->enable_gpio)) { + HDF_LOGE("get enable_gpio fail"); + return HDF_FAILURE; + } + pdev->hpd_gpio = devm_gpiod_get_optional(&pdev->dsiDev->dev, "hpd", GPIOD_IN); + if (IS_ERR(pdev->hpd_gpio)) { + HDF_LOGE("get hpd_gpio fail"); + return HDF_FAILURE; + } + pdev->reset_gpio = devm_gpiod_get_optional(&pdev->dsiDev->dev, "reset", GPIOD_ASIS); + if (IS_ERR(pdev->reset_gpio)) { + HDF_LOGE("get reset_gpio fail"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + static int32_t PanelEntryInit(struct HdfDeviceObject *object) { struct device_node *panelNode = NULL; @@ -631,19 +652,7 @@ static int32_t PanelEntryInit(struct HdfDeviceObject *object) goto FAIL; } - panel_dev->enable_gpio = devm_gpiod_get_optional(&panel_dev->dsiDev->dev, "enable", GPIOD_ASIS); - if (IS_ERR(panel_dev->enable_gpio)) { - HDF_LOGE("get enable_gpio fail"); - goto FAIL; - } - panel_dev->hpd_gpio = devm_gpiod_get_optional(&panel_dev->dsiDev->dev, "hpd", GPIOD_IN); - if (IS_ERR(panel_dev->hpd_gpio)) { - HDF_LOGE("get hpd_gpio fail"); - goto FAIL; - } - panel_dev->reset_gpio = devm_gpiod_get_optional(&panel_dev->dsiDev->dev, "reset", GPIOD_ASIS); - if (IS_ERR(panel_dev->reset_gpio)) { - HDF_LOGE("get reset_gpio fail"); + if (PanelRequestGpio(panel_dev) != HDF_SUCCESS) { goto FAIL; } diff --git a/framework/model/input/driver/hdf_hid_adapter.c b/framework/model/input/driver/hdf_hid_adapter.c index a5f714c6205a8e5642505fdc0df354b4a7987717..35f80e173e0c9ce72a345c0edad402c79c739872 100644 --- a/framework/model/input/driver/hdf_hid_adapter.c +++ b/framework/model/input/driver/hdf_hid_adapter.c @@ -219,7 +219,7 @@ static void DoRegisterInputDev(InputDevice* inputDev) } } -static void CacheHid(InputDevice* inputDev) +void CacheHid(InputDevice* inputDev) { int32_t i = 0; while ((i < MAX_INPUT_DEV_NUM) && (cachedHid[i] != NULL)) { diff --git a/framework/model/input/driver/hdf_hid_adapter.h b/framework/model/input/driver/hdf_hid_adapter.h index 83efe6140afc619894f529c24ee6ec20b34551ff..2b4a5af2cfc55cafb831ed6b33b6ca9cf33b815a 100644 --- a/framework/model/input/driver/hdf_hid_adapter.h +++ b/framework/model/input/driver/hdf_hid_adapter.h @@ -96,5 +96,5 @@ void SendInfoToHdf(HidInfo *info); void* HidRegisterHdfInputDev(HidInfo *info); void HidUnregisterHdfInputDev(const void *inputDev); void HidReportEvent(const void *inputDev, uint32_t type, uint32_t code, int32_t value); - +void CacheHid(InputDevice* inputDev); #endif diff --git a/framework/model/input/driver/hdf_input_device_manager.c b/framework/model/input/driver/hdf_input_device_manager.c index 175a74d78ac3bc392241c0b822e9683dd10633ae..ab23841107d7ecc610e5c69d5511656c48777449 100644 --- a/framework/model/input/driver/hdf_input_device_manager.c +++ b/framework/model/input/driver/hdf_input_device_manager.c @@ -13,6 +13,7 @@ #include "hdf_device_object.h" #include "hdf_log.h" #include "osal_mem.h" +#include "hdf_hid_adapter.h" #define NODE_MODE 0660 #define SERVICE_NAME_LEN 24 @@ -107,13 +108,21 @@ static void HotPlugNotify(const InputDevice *inputDev, uint32_t status) static int32_t CreateDeviceNode(InputDevice *inputDev) { + static bool existNonHid = false ; if (IsHidDevice(inputDev)) { + if (!existNonHid) { + CacheHid(inputDev); + HDF_LOGI("%s: is first hid dev add cache, devId is %d ", __func__, inputDev->devId); + return HDF_SUCCESS; + } HDF_LOGI("%s: prepare to register hdf device", __func__); inputDev->hdfDevObj = HidRegisterHdfDevice(inputDev); if (inputDev->hdfDevObj == NULL) { return HDF_DEV_ERR_NO_DEVICE; } inputDev->hdfDevObj->priv = (void *)inputDev; + } else { + existNonHid = true ; } HDF_LOGI("%s: create node succ, devId is %d ", __func__, inputDev->devId); diff --git a/framework/model/input/driver/hdf_touch.c b/framework/model/input/driver/hdf_touch.c index 8838ad5c3e53b07b495c36043db3d51d178bb299..52aec409c9d1e2ed0171c07cd927327df624d05c 100644 --- a/framework/model/input/driver/hdf_touch.c +++ b/framework/model/input/driver/hdf_touch.c @@ -41,6 +41,7 @@ static int32_t ChipCheckResetRetry(ChipDevice *chipDev); static TouchDriver *g_touchDriverList[MAX_TOUCH_DEVICE]; static void InputFrameReport(TouchDriver *driver); +static int SuspendFlag = 0; static int32_t SetGpioDirAndLevel(int gpio, int dir, int level) { @@ -236,7 +237,7 @@ static int32_t Gt1xRequestIo(ChipDevice *chipDev) } #endif -static int32_t SetPowerOnTiming(ChipDevice *chipDev, bool enableRst) +static int32_t SetTiming(ChipDevice *chipDev, bool enable) { #if defined(CONFIG_ARCH_MESON) return HDF_SUCCESS; @@ -248,6 +249,7 @@ static int32_t SetPowerOnTiming(ChipDevice *chipDev, bool enableRst) uint32_t intPinAddr; uint32_t intPinValue; SeqArray pwrOnTiming = {0}; + SeqArray pwroffTiming = {0}; TouchDriver *driver = chipDev->driver; rstPinAddr = driver->boardCfg->pins.rstPinReg[0]; @@ -265,26 +267,39 @@ static int32_t SetPowerOnTiming(ChipDevice *chipDev, bool enableRst) HDF_LOGD("%s: rstPinAddr = 0x%x, rstPinValue = 0x%x, intPinAddr = 0x%x, intPinValue = 0x%x", __func__, rstPinAddr, rstPinValue, intPinAddr, intPinValue); - ret = memcpy_s(&pwrOnTiming, sizeof(SeqArray), &chipDev->chipCfg->pwrSeq.pwrOn, sizeof(SeqArray)); - if (ret != EOK) { - HDF_LOGE("%s: memcpy_s failed", __func__); - return HDF_FAILURE; - } - - if ((pwrOnTiming.buf == NULL) || (pwrOnTiming.count == 0)) { - HDF_LOGE("%s: pwrOnTiming config is invalid", __func__); - return HDF_FAILURE; - } - - for (i = 0; i < pwrOnTiming.count / PWR_CELL_LEN; i++) { - if (enableRst) { + HDF_LOGE("%s: enable = %d", __func__, enable); + if (enable) { + ret = memcpy_s(&pwrOnTiming, sizeof(SeqArray), &chipDev->chipCfg->pwrSeq.pwrOn, sizeof(SeqArray)); + if (ret != EOK) { + HDF_LOGE("%s: memcpy_s failed", __func__); + return HDF_FAILURE; + } + if ((pwrOnTiming.buf == NULL) || (pwrOnTiming.count == 0)) { + HDF_LOGE("%s: pwrOnTiming config is invalid", __func__); + return HDF_FAILURE; + } + for (i = 0; i < pwrOnTiming.count / PWR_CELL_LEN; i++) { ret = HandleResetEvent(chipDev, pwrOnTiming.buf, PWR_CELL_LEN); - } else { - ret = HandlePowerEvent(chipDev, pwrOnTiming.buf, PWR_CELL_LEN); + CHECK_RETURN_VALUE(ret); + pwrOnTiming.buf = pwrOnTiming.buf + PWR_CELL_LEN; + } + } else { + ret = memcpy_s(&pwroffTiming, sizeof(SeqArray), &chipDev->chipCfg->pwrSeq.pwrOff, sizeof(SeqArray)); + if (ret != EOK) { + HDF_LOGE("%s: memcpy_s failed", __func__); + return HDF_FAILURE; + } + if ((pwroffTiming.buf == NULL) || (pwroffTiming.count == 0)) { + HDF_LOGE("%s: pwroffTiming config is invalid", __func__); + return HDF_FAILURE; + } + for (i = 0; i < pwroffTiming.count / PWR_CELL_LEN; i++) { + ret = HandlePowerEvent(chipDev, pwroffTiming.buf, PWR_CELL_LEN); + CHECK_RETURN_VALUE(ret); + pwroffTiming.buf = pwroffTiming.buf + PWR_CELL_LEN; } - CHECK_RETURN_VALUE(ret); - pwrOnTiming.buf = pwrOnTiming.buf + PWR_CELL_LEN; } + #if defined(CONFIG_ARCH_ROCKCHIP) ret = SetResetStatus(driver); if (ret != HDF_SUCCESS) { @@ -386,7 +401,11 @@ static void ChipReset(ChipDevice *chipDev) HDF_LOGE("%s: invalid param", __func__); return; } - (void)SetPowerOnTiming(chipDev, true); + if (!SuspendFlag) { + (void)SetTiming(chipDev, true); + } else { + (void)SetTiming(chipDev, false); + } } #if GTP_ESD_PROTECT @@ -564,11 +583,13 @@ static int32_t ChipDriverInit(ChipDevice *chipDev) int32_t count = 20; // 20: reset time int32_t ret; #if defined(CONFIG_ARCH_ROCKCHIP) +#if GTP_ESD_PROTECT g_touchDriver = chipDev->driver; +#endif ret = Gt1xRequestIo(chipDev); CHECK_RETURN_VALUE(ret); #endif - ret = SetPowerOnTiming(chipDev, false); + ret = SetTiming(chipDev, false); CHECK_RETURN_VALUE(ret); if ((chipDev->ops == NULL) || (chipDev->ops->Detect == NULL)) { @@ -1053,7 +1074,12 @@ static int HdfTouchDriverDozeResume(struct HdfDeviceObject *device) return HDF_ERR_INVALID_PARAM; } HDF_LOGI("%s:called", __func__); - +#if GTP_ESD_PROTECT + if (gt1x_workqueue) { + Gt1xEsdSwitch(1); + } +#endif + SuspendFlag = 0; static int32_t isFirstResume = 1; if (isFirstResume == 1) { isFirstResume = 0; @@ -1072,7 +1098,12 @@ static int HdfTouchDriverDozeSuspend(struct HdfDeviceObject *device) return HDF_ERR_INVALID_PARAM; } HDF_LOGI("%s:called", __func__); - +#if GTP_ESD_PROTECT + if (gt1x_workqueue) { + Gt1xDeinitEsdProtect(); + } +#endif + SuspendFlag = 1; int32_t ret = -1; uint8_t writeBuf[3]; // 3: buffer size uint16_t intGpioNum; @@ -1208,4 +1239,4 @@ struct HdfDriverEntry g_hdfTouchEntry = { .Release = HdfTouchDriverRelease, }; -HDF_INIT(g_hdfTouchEntry); \ No newline at end of file +HDF_INIT(g_hdfTouchEntry); diff --git a/framework/model/input/driver/touchscreen/touch_ft5x06.c b/framework/model/input/driver/touchscreen/touch_ft5x06.c index c5c5df0293d3fbe9ecf60eaad992e3794efd8465..0db90576efefa3a7dcdcda2b29167604c8699e1b 100644 --- a/framework/model/input/driver/touchscreen/touch_ft5x06.c +++ b/framework/model/input/driver/touchscreen/touch_ft5x06.c @@ -86,17 +86,12 @@ static int Ft5x06_EP01(ChipDevice *device, u8 *rdbuf) static int Ft5x06_Identify(ChipDevice *device, const InputI2cClient *i2cClient) { u8 rdbuf[EDT_NAME_LEN]; - char *p; - int error; - (void)memset_s(rdbuf, sizeof(rdbuf), NUM_0, sizeof(rdbuf)); (void)memset_s(touch_fw_version, sizeof(touch_fw_version), NUM_0, sizeof(touch_fw_version)); - - error = InputI2cRead(i2cClient, "\xbb", NUM_1, rdbuf, EDT_NAME_LEN - NUM_1); + int error = InputI2cRead(i2cClient, "\xbb", NUM_1, rdbuf, EDT_NAME_LEN - NUM_1); if (error != HDF_SUCCESS) { return error; } - /* Probe content for something consistent. * M06 starts with a response byte. * M09/Generic does not provide model number information. @@ -108,18 +103,15 @@ static int Ft5x06_Identify(ChipDevice *device, const InputI2cClient *i2cClient) } else { device->chipCfg->chipVersion = GENERIC_FT; HDF_LOGI("%s: version = GENERIC_FT;", __func__); - error = InputI2cRead(i2cClient, "\xA6", NUM_1, rdbuf, NUM_2); if (error != HDF_SUCCESS) { return error; } strlcpy(touch_fw_version, rdbuf, NUM_2); - error = InputI2cRead(i2cClient, "\xA8", NUM_1, rdbuf, NUM_1); if (error != HDF_SUCCESS) { return error; } - switch (rdbuf[0]) { case EP0350M09:fallthrough; case EP0430M09:fallthrough; @@ -133,7 +125,6 @@ static int Ft5x06_Identify(ChipDevice *device, const InputI2cClient *i2cClient) case EPDISPLAY: device->chipCfg->chipVersion = EV_FT; HDF_LOGI("%s: version = EV_FT;", __func__); - error = InputI2cRead(i2cClient, "\x53", NUM_1, rdbuf, NUM_1); if (error) return error; @@ -143,7 +134,6 @@ static int Ft5x06_Identify(ChipDevice *device, const InputI2cClient *i2cClient) break; } } - HDF_LOGI("%s: touch_fw_version = %s", __func__, touch_fw_version); return NUM_0; } diff --git a/framework/model/input/driver/touchscreen/touch_gt911.c b/framework/model/input/driver/touchscreen/touch_gt911.c index f2ab20be2b79ef4a90dd7492d28da984e9f6d10e..074c40d9839751889c9c97493258e4e626f6a7ec 100644 --- a/framework/model/input/driver/touchscreen/touch_gt911.c +++ b/framework/model/input/driver/touchscreen/touch_gt911.c @@ -15,6 +15,13 @@ #include "touch_gt911.h" #define MAX_POINT 5 +#if defined(CONFIG_ARCH_ROCKCHIP) +#define GT5688_FIRMWARE_VERSION 256 +#define GT911_FIRMWARE_VERSION 4192 +#endif + +#define FOUR_BYTES 4 +#define FOUR_BYTES_BIT 32 static int32_t ChipInit(ChipDevice *device) { @@ -53,13 +60,19 @@ static int32_t ChipDetect(ChipDevice *device) xSolution = (buf[GT_SOLU_X_HIGH] << ONE_BYTE_OFFSET) | buf[GT_SOLU_X_LOW]; ySolution = (buf[GT_SOLU_Y_HIGH] << ONE_BYTE_OFFSET) | buf[GT_SOLU_Y_LOW]; #if defined(CONFIG_ARCH_ROCKCHIP) - if (buf[GT_PROD_ID_1ST] != '5' || buf[GT_PROD_ID_2ND] != '6' || \ - buf[GT_PROD_ID_3RD] != '8' || buf[GT_PROD_ID_4TH] != '8') { - HDF_LOGE("%s: ID wrong,IC FW version is 0x%x", __func__, version); - return HDF_FAILURE; + HDF_LOGI("%s:IC FW version is %d", __func__, version); + switch (version) { + case GT5688_FIRMWARE_VERSION: + HDF_LOGI("%s:TOUCH IC is GT5688", __func__); + break; + case GT911_FIRMWARE_VERSION: + HDF_LOGI("%s:TOUCH IC is GT911", __func__); + break; + default: + HDF_LOGE("%s: ID wrong,IC FW version is %d", __func__, version); + return HDF_FAILURE; } #endif - HDF_LOGI("%s: IC FW version is 0x%x", __func__, version); if (buf[GT_FW_VER_HIGH] == 0x0) { HDF_LOGI("Product ID : %c%c%c_%02x%02x, xSol = %d, ySol = %d", buf[GT_PROD_ID_1ST], buf[GT_PROD_ID_2ND], buf[GT_PROD_ID_3RD], buf[GT_FW_VER_HIGH], buf[GT_FW_VER_LOW], xSolution, ySolution); @@ -90,57 +103,89 @@ static int ChipCleanBuffer(InputI2cClient *i2cClient) #define X_OFFSET 1 -static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum) +static void ChipVersionDefault(ChipDevice *device, FrameData *frame, const uint8_t *buf, uint8_t pointNum) { - int32_t chipVer = device->chipCfg->chipVersion; - int32_t resX = device->driver->boardCfg->attr.resolutionX; - int32_t resY = device->driver->boardCfg->attr.resolutionY; - int32_t i; - - for (i = 0; i < pointNum; i++) { - if (chipVer == 0) { // chipversion A:gt911_zsj5p5 - frame->fingers[i].trackId = buf[GT_POINT_SIZE * i + GT_TRACK_ID]; + for (uint8_t i = 0; i < pointNum; i++) { // chipversion A:gt911_zsj5p5 + frame->fingers[i].trackId = buf[GT_POINT_SIZE * i + GT_TRACK_ID]; #if defined(CONFIG_ARCH_SPRD) - frame->fingers[i].y = (resX - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << - ONE_BYTE_OFFSET))) * resY / resX; - frame->fingers[i].x = ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << - ONE_BYTE_OFFSET)) * resX / resY; + int32_t resX = device->driver->boardCfg->attr.resolutionX; + int32_t resY = device->driver->boardCfg->attr.resolutionY; + frame->fingers[i].y = (resX - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << + ONE_BYTE_OFFSET))) * resY / resX; + frame->fingers[i].x = ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << + ONE_BYTE_OFFSET)) * resX / resY; #elif defined(CONFIG_ARCH_ROCKCHIP) - frame->fingers[i].x = resX - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); - frame->fingers[i].y = resY - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + int32_t resX = device->driver->boardCfg->attr.resolutionX; + int32_t resY = device->driver->boardCfg->attr.resolutionY; + frame->fingers[i].x = resX - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + frame->fingers[i].y = resY - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + if (frame->fingers[i].y < GT_Y_OFFSET_A) { + frame->fingers[i].y += CORRECTION_VALUE_A; + } else if (frame->fingers[i].y < GT_Y_OFFSET_B) { + frame->fingers[i].y += CORRECTION_VALUE_B; + } else if (frame->fingers[i].y < GT_Y_OFFSET_C) { + frame->fingers[i].y += CORRECTION_VALUE_C; + } #elif defined(LOSCFG_PLATFORM_STM32MP157) - frame->fingers[i].x = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); - frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); + frame->fingers[i].x = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); + frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); #else - frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); - frame->fingers[i].x = (buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); + frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); + frame->fingers[i].x = (buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); #endif - if (frame->fingers[i].x == 0) { - frame->fingers[i].x = X_OFFSET; - } - } else if (chipVer == 1) { // chipversion B:gt911_zsj4p0 - frame->fingers[i].x = resX - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); - frame->fingers[i].y = resY - 1 - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); - } else { // chipversion C:gt911_tg7p0 - frame->fingers[i].x = resX - 1 - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); - frame->fingers[i].y = resY - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | - ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + if (frame->fingers[i].x == 0) { + frame->fingers[i].x = X_OFFSET; } frame->fingers[i].valid = true; } } +static void ChipVersionIsOne(ChipDevice *device, FrameData *frame, const uint8_t *buf, uint8_t pointNum) +{ + int32_t resX = device->driver->boardCfg->attr.resolutionX; + int32_t resY = device->driver->boardCfg->attr.resolutionY; + for (uint8_t i = 0; i < pointNum; i++) { + frame->fingers[i].x = resX - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + frame->fingers[i].y = resY - 1 - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + frame->fingers[i].valid = true; + } +} + +static void ChipVersionIsExt(ChipDevice *device, FrameData *frame, const uint8_t *buf, uint8_t pointNum) +{ + int32_t resX = device->driver->boardCfg->attr.resolutionX; + int32_t resY = device->driver->boardCfg->attr.resolutionY; + for (uint8_t i = 0; i < pointNum; i++) { + frame->fingers[i].x = resX - 1 - ((buf[GT_POINT_SIZE * i + GT_Y_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + frame->fingers[i].y = resY - 1 - ((buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | + ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET)); + frame->fingers[i].valid = true; + } +} + +static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum) +{ + int32_t chipVer = device->chipCfg->chipVersion; + if (chipVer == 0) { // chipversion A:gt911_zsj5p5 + ChipVersionDefault(device, frame, buf, pointNum); + } else if (chipVer == 1) { // chipversion B:gt911_zsj4p0 + ChipVersionIsOne(device, frame, buf, pointNum); + } else { // chipversion C:gt911_tg7p0 + ChipVersionIsExt(device, frame, buf, pointNum); + } +} + static int32_t ChipDataHandle(ChipDevice *device) { int32_t ret; @@ -223,9 +268,18 @@ static void SetAbility(ChipDevice *device) device->driver->inputDev->abilitySet.devProp[0] = SET_BIT(INPUT_PROP_DIRECT); device->driver->inputDev->abilitySet.eventType[0] = SET_BIT(EV_SYN) | SET_BIT(EV_KEY) | SET_BIT(EV_ABS); - device->driver->inputDev->abilitySet.absCode[0] = SET_BIT(ABS_X) | SET_BIT(ABS_Y); - device->driver->inputDev->abilitySet.absCode[1] = SET_BIT(ABS_MT_POSITION_X) | - SET_BIT(ABS_MT_POSITION_Y) | SET_BIT(ABS_MT_TRACKING_ID); + if (sizeof(unsigned long) > FOUR_BYTES) { + unsigned long highBit = SET_BIT(ABS_MT_POSITION_X) | SET_BIT(ABS_MT_POSITION_Y) | + SET_BIT(ABS_MT_TRACKING_ID); + if (BITS_PER_LONG == FOUR_BYTES_BIT) { + highBit <<= FOUR_BYTES_BIT; + } + device->driver->inputDev->abilitySet.absCode[0] = SET_BIT(ABS_X) | SET_BIT(ABS_Y) | highBit; + } else { + device->driver->inputDev->abilitySet.absCode[0] = SET_BIT(ABS_X) | SET_BIT(ABS_Y); + device->driver->inputDev->abilitySet.absCode[1] = SET_BIT(ABS_MT_POSITION_X) | + SET_BIT(ABS_MT_POSITION_Y) | SET_BIT(ABS_MT_TRACKING_ID); + } device->driver->inputDev->abilitySet.keyCode[KEY_CODE_4TH] = SET_BIT(KEY_UP) | SET_BIT(KEY_DOWN); device->driver->inputDev->attrSet.axisInfo[ABS_X].min = 0; device->driver->inputDev->attrSet.axisInfo[ABS_X].max = device->boardCfg->attr.resolutionX - 1; diff --git a/framework/model/input/driver/touchscreen/touch_gt911.h b/framework/model/input/driver/touchscreen/touch_gt911.h index 79246b73f3545baa3be7850598c723af1c4fb8f4..24beb6ba17211d387e9a9c68d32e2f8232ddefb3 100644 --- a/framework/model/input/driver/touchscreen/touch_gt911.h +++ b/framework/model/input/driver/touchscreen/touch_gt911.h @@ -49,6 +49,12 @@ #if defined(CONFIG_ARCH_ROCKCHIP) #define FIRMWARE_LEN 241 #define GTP_REG_CONFIG_DATA 0x8050 +#define GT_Y_OFFSET_A 200 +#define GT_Y_OFFSET_B 700 +#define GT_Y_OFFSET_C 1000 +#define CORRECTION_VALUE_A 30 +#define CORRECTION_VALUE_B 20 +#define CORRECTION_VALUE_C 5 #else #define FIRMWARE_LEN 188 #endif diff --git a/framework/model/misc/light/driver/include/light_driver.h b/framework/model/misc/light/driver/include/light_driver.h index 56bbfac577c3f87441dc3194e0fab5b562d65cbd..77d1a5ed8b38344caa70e351eb3c12e8d5a52b33 100644 --- a/framework/model/misc/light/driver/include/light_driver.h +++ b/framework/model/misc/light/driver/include/light_driver.h @@ -50,6 +50,12 @@ } \ } while (0) +#define CHECK_LIGHT_PARSER_NUM_RETURN_VALUE(ret, num) do { \ + if ((ret) != HDF_SUCCESS) { \ + (num) = LIGHT_INVALID_GPIO; \ + } \ +} while (0) + enum LightIoCmd { LIGHT_IO_CMD_GET_INFO_LIST = 0, LIGHT_IO_CMD_OPS = 1, diff --git a/framework/model/misc/light/driver/src/light_driver.c b/framework/model/misc/light/driver/src/light_driver.c index 57160945dd311fcc88a535bc0d65e47f4b13db46..e6b50a42b02f34476cc1ff3feacfcbcad3370f02 100644 --- a/framework/model/misc/light/driver/src/light_driver.c +++ b/framework/model/misc/light/driver/src/light_driver.c @@ -376,19 +376,13 @@ static int32_t GetLightBaseConfigData(const struct DeviceResourceNode *node, con } ret = parser->GetUint32(node, "busRNum", (uint32_t *)&drvData->info[lightId]->busRNum, 0); - if (ret != HDF_SUCCESS) { - drvData->info[lightId]->busRNum = LIGHT_INVALID_GPIO; - } + CHECK_LIGHT_PARSER_NUM_RETURN_VALUE(ret, drvData->info[lightId]->busRNum); ret = parser->GetUint32(node, "busGNum", (uint32_t *)&drvData->info[lightId]->busGNum, 0); - if (ret != HDF_SUCCESS) { - drvData->info[lightId]->busGNum = LIGHT_INVALID_GPIO; - } + CHECK_LIGHT_PARSER_NUM_RETURN_VALUE(ret, drvData->info[lightId]->busGNum); ret = parser->GetUint32(node, "busBNum", (uint32_t *)&drvData->info[lightId]->busBNum, 0); - if (ret != HDF_SUCCESS) { - drvData->info[lightId]->busBNum = LIGHT_INVALID_GPIO; - } + CHECK_LIGHT_PARSER_NUM_RETURN_VALUE(ret, drvData->info[lightId]->busBNum); ret = parser->GetString(node, "lightName", &name, NULL); if (ret != HDF_SUCCESS) { diff --git a/framework/model/misc/vibrator/driver/src/vibrator_driver.c b/framework/model/misc/vibrator/driver/src/vibrator_driver.c index 2eac1ef8ca9c962bbd214a9d3844f8cbd410e8fd..a84f9997a28797a280ba7d08bb661b0f3f0a74b4 100644 --- a/framework/model/misc/vibrator/driver/src/vibrator_driver.c +++ b/framework/model/misc/vibrator/driver/src/vibrator_driver.c @@ -136,11 +136,6 @@ static int32_t StartOnce(struct HdfSBuf *data, struct HdfSBuf *reply) return HDF_FAILURE; } - if (duration == 0) { - HDF_LOGE("%s: vibrator duration invalid para!", __func__); - return HDF_ERR_INVALID_PARAM; - } - if (drvData->mode != VIBRATOR_MODE_BUTT) { HDF_LOGI("%s: vibrater haptic is busy now, please stop first!", __func__); return HDF_ERR_DEVICE_BUSY; diff --git a/framework/model/network/wifi/bus/hdf_pcie_intf.c b/framework/model/network/wifi/bus/hdf_pcie_intf.c new file mode 100644 index 0000000000000000000000000000000000000000..91131ff5c35edcbc7ace0cea846025e5a464a338 --- /dev/null +++ b/framework/model/network/wifi/bus/hdf_pcie_intf.c @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_base.h" +#include "hdf_dlist.h" +#include "hdf_ibus_intf.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "pcie_if.h" +#include "securec.h" +#include "wifi_inc.h" +#define HDF_LOG_TAG HDF_WIFI_CORE +struct PcieDeviceBase { + DevHandle handle; + IrqHandler *irqHandler; + MapHandler *mapHandler; +}; +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +static struct DevHandle *HdfGetDevHandle(struct BusDev *dev, const struct HdfConfigWlanBus *busCfg) +{ + struct DevHandle *handle = NULL; + struct PcieDeviceBase *pcieDevBase = OsalMemCalloc(sizeof(struct PcieDeviceBase)); + if (pcieDevBase == NULL) { + HDF_LOGE("%s: OsalMemCalloc failed!", __func__); + return NULL; + } + handle = PcieOpen(busCfg->busIdx); + if (handle == NULL) { + HDF_LOGE("%s: pcie card detected!", __func__); + OsalMemFree(pcieDevBase); + return NULL; + } + pcieDevBase->handle = handle; + dev->devBase = pcieDevBase; + dev->priData.driverName = NULL; // check driver name + return handle; +} + +static int32_t HdfGetPcieInfo(struct BusDev *dev, struct BusConfig *busCfg) +{ + (void)dev; + (void)busCfg; + return HDF_SUCCESS; +} + +static int32_t HdfPcieInit(struct BusDev *dev, const struct HdfConfigWlanBus *busCfg) +{ + struct DevHandle *handle = NULL; + if (dev == NULL || busCfg == NULL) { + HDF_LOGE("%s: input parameter error!", __func__); + return HDF_FAILURE; + } + handle = HdfGetDevHandle(dev, busCfg); + if (handle == NULL) { + HDF_LOGE("%s: get handle error!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +static void HdfPcieReleaseDev(struct BusDev *dev) +{ + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return; + } + devBase = dev->devBase; + if (devBase->handle != NULL) { + PcieClose(devBase->handle); + devBase->handle = NULL; + } + if (dev->priData.data != NULL) { + dev->priData.release(dev->priData.data); + dev->priData.data = NULL; + } + OsalMemFree(devBase); + dev->devBase = NULL; +} + +static int32_t HdfPcieDisableFunc(struct BusDev *dev) +{ + (void)dev; + return HDF_SUCCESS; +} + +static int32_t PcieIrqCallBack(DevHandle handle) +{ + struct PcieDeviceBase *devBase = CONTAINER_OF(handle, struct PcieDeviceBase, handle); + if (devBase->handle == NULL || devBase->irqHandler == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_SUCCESS; + } + devBase->irqHandler(NULL); + return HDF_SUCCESS; +} + +static int32_t HdfPcieCliamIrq(struct BusDev *dev, IrqHandler *handler, void *data) +{ + (void)data; + int32_t ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + // save irq handler + if (handler != NULL) { + devBase->irqHandler = handler; + } + + ret = PcieRegisterIrq(devBase->handle, PcieIrqCallBack); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:register irq error!", __func__); + } + return ret; +} + +static int32_t HdfPcieReleaseIrq(struct BusDev *dev) +{ + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + PcieUnregisterIrq(devBase->handle); + devBase->irqHandler = NULL; + return HDF_SUCCESS; +} + +static void HdfPcieClaimHost(struct BusDev *dev) +{ + (void)dev; +} + +static void HdfPcieReleaseHost(struct BusDev *dev) +{ + (void)dev; +} + +static int32_t HdfPcieReset(struct BusDev *dev) +{ + (void)dev; + return HDF_SUCCESS; +} + +static int32_t HdfPcieReadN(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + // read config + int32_t ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = PcieRead(devBase->handle, PCIE_CONFIG, addr, buf, cnt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pcie read err", __func__); + } + return ret; +} + +static int32_t HdfPcieReadFunc0(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + (void)dev; + (void)addr; + (void)cnt; + (void)buf; + return HDF_SUCCESS; +} + +static int32_t HdfPcieReadSpcReg(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf, uint32_t sg_len) +{ + (void)dev; + (void)addr; + (void)cnt; + (void)buf; + (void)sg_len; + return HDF_SUCCESS; +} + +static int32_t HdfPcieWriteN(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + // write config + int32_t ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = PcieWrite(devBase->handle, PCIE_CONFIG, addr, buf, cnt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pcie write err", __func__); + } + return ret; +} + +static int32_t HdfPcieWriteFunc0(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + (void)dev; + (void)addr; + (void)cnt; + (void)buf; + return HDF_SUCCESS; +} + +static int32_t HdfPcieWriteSpcReg(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf, uint32_t sg_len) +{ + (void)dev; + (void)addr; + (void)cnt; + (void)buf; + (void)sg_len; + return HDF_SUCCESS; +} + +static int32_t PcieMapCallbackFunc(DevHandle handle) +{ + struct PcieDeviceBase *devBase = CONTAINER_OF(handle, struct PcieDeviceBase, handle); + if (devBase->handle == NULL || devBase->mapHandler == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_SUCCESS; + } + return devBase->mapHandler(NULL); +} + +static int32_t HdfPcieDmaMap(struct BusDev *dev, MapHandler *cb, uintptr_t addr, uint32_t len, uint8_t dir) +{ + int32_t ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + // save map handler + devBase->mapHandler = cb; + ret = PcieDmaMap(devBase->handle, PcieMapCallbackFunc, addr, len, dir); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pcie dma map err", __func__); + } + return ret; +} +static int32_t HdfPcieDmaUnmap(struct BusDev *dev, uintptr_t addr, uint32_t len, uint8_t dir) +{ + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + PcieDmaUnmap(devBase->handle, addr, len, dir); + devBase->mapHandler = NULL; + return HDF_SUCCESS; +} + +static int32_t HdfPcieIoRead(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + int ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = PcieRead(devBase->handle, PCIE_IO, addr, buf, cnt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pcie io read err", __func__); + } + return ret; +} +static int32_t HdfPcieIoWrite(struct BusDev *dev, uint32_t addr, uint32_t cnt, uint8_t *buf) +{ + int32_t ret; + struct PcieDeviceBase *devBase = NULL; + if (dev == NULL || dev->devBase == NULL) { + HDF_LOGE("%s:input parameter error!", __func__); + return HDF_ERR_INVALID_PARAM; + } + devBase = dev->devBase; + if (devBase->handle == NULL) { + HDF_LOGE("%s:handle is NULL!", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = PcieWrite(devBase->handle, PCIE_IO, addr, buf, cnt); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pcie io write err", __func__); + } + return ret; +} + +static void HdfSetBusOps(struct BusDev *dev) +{ + dev->ops.getBusInfo = HdfGetPcieInfo; + dev->ops.deInit = HdfPcieReleaseDev; + dev->ops.init = HdfPcieInit; + + dev->ops.readData = HdfPcieReadN; + dev->ops.writeData = HdfPcieWriteN; + dev->ops.bulkRead = HdfPcieReadSpcReg; + dev->ops.bulkWrite = HdfPcieWriteSpcReg; + dev->ops.readFunc0 = HdfPcieReadFunc0; + dev->ops.writeFunc0 = HdfPcieWriteFunc0; + + dev->ops.claimIrq = HdfPcieCliamIrq; + dev->ops.releaseIrq = HdfPcieReleaseIrq; + dev->ops.disableBus = HdfPcieDisableFunc; + dev->ops.reset = HdfPcieReset; + + dev->ops.claimHost = HdfPcieClaimHost; + dev->ops.releaseHost = HdfPcieReleaseHost; + + // IO /dma + dev->ops.ioRead = HdfPcieIoRead; + dev->ops.ioWrite = HdfPcieIoWrite; + dev->ops.dmaMap = HdfPcieDmaMap; + dev->ops.dmaUnmap = HdfPcieDmaUnmap; +} +int32_t HdfWlanBusAbsInit(struct BusDev *dev, const struct HdfConfigWlanBus *busConfig) +{ + if (dev == NULL) { + HDF_LOGE("%s:set pcie device ops failed!", __func__); + return HDF_FAILURE; + } + HdfSetBusOps(dev); + return HdfPcieInit(dev, busConfig); +} + +int32_t HdfWlanConfigBusAbs(uint8_t busId) +{ + (void)busId; + return HDF_SUCCESS; +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif diff --git a/framework/model/network/wifi/core/components/softap/ap.c b/framework/model/network/wifi/core/components/softap/ap.c index 0032832c26c8cfa8302400a7ce3383874ab65758..4e8a49bb0cdf0614c0926e7a0bd93c05805efe88 100644 --- a/framework/model/network/wifi/core/components/softap/ap.c +++ b/framework/model/network/wifi/core/components/softap/ap.c @@ -465,13 +465,68 @@ static int32_t WifiCmdSetCountryCode(const RequestContext *context, struct HdfSB return ret; } +static uint32_t OpsGetApBandwidth(const char *ifName, uint8_t *bandwidth) +{ + struct NetDevice *netdev = NULL; + + if (ifName == NULL || bandwidth == NULL) { + HDF_LOGE("%s: Invalid parameter", __func__); + return HDF_FAILURE; + } + netdev = NetDeviceGetInstByName(ifName); + if (netdev == NULL) { + HDF_LOGE("%s:netdev not found!ifName=%s.", __func__, ifName); + return HDF_FAILURE; + } + struct HdfChipDriver *chipDriver = GetChipDriver(netdev); + if (chipDriver == NULL) { + HDF_LOGE("%s:bad net device found!", __func__); + return HDF_FAILURE; + } + if (chipDriver->ops == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return HDF_ERR_NOT_SUPPORT; +} + +static int32_t WifiCmdGetApBandwidth(const RequestContext *context, struct HdfSBuf *reqData, struct HdfSBuf *rspData) +{ + int32_t ret; + const char *ifName = NULL; + uint8_t bandwidth; + (void)context; + + if (reqData == NULL || rspData == NULL) { + return HDF_ERR_INVALID_PARAM; + } + ifName = HdfSbufReadString(reqData); + if (ifName == NULL) { + HDF_LOGE("%s: %s!ParamName=%s", __func__, ERROR_DESC_READ_REQ_FAILED, "ifName"); + return HDF_FAILURE; + } + ret = OpsGetApBandwidth(ifName, &bandwidth); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: fail to get power mode, %d", __func__, ret); + return ret; + } + HDF_LOGI("%s: ap bandwidth: %d", __func__, bandwidth); + if (!HdfSbufWriteUint8(rspData, bandwidth)) { + HDF_LOGE("%s: %s!", __func__, ERROR_DESC_WRITE_RSP_FAILED); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + + static struct MessageDef g_wifiApFeatureCmds[] = { DUEMessage(CMD_AP_START, WifiCmdSetAp, 0), DUEMessage(CMD_AP_STOP, WifiCmdStopAp, 0), DUEMessage(CMD_AP_CHANGE_BEACON, WifiCmdChangeBeacon, 0), DUEMessage(CMD_AP_DEL_STATION, WifiCmdStaRemove, 0), DUEMessage(CMD_AP_GET_ASSOC_STA, WifiCmdGetAssociatedStas, 0), - DUEMessage(CMD_AP_SET_COUNTRY_CODE, WifiCmdSetCountryCode, 0) + DUEMessage(CMD_AP_SET_COUNTRY_CODE, WifiCmdSetCountryCode, 0), + DUEMessage(CMD_AP_GET_BANDWIDTH, WifiCmdGetApBandwidth, 0) }; ServiceDefine(APService, AP_SERVICE_ID, g_wifiApFeatureCmds); diff --git a/framework/model/network/wifi/platform/include/hdf_wlan_services.h b/framework/model/network/wifi/platform/include/hdf_wlan_services.h index 32997568d8875704cc0117c8a303aefa8633d4bb..daff484a355582d601cde7334d325cfd8b7de122 100644 --- a/framework/model/network/wifi/platform/include/hdf_wlan_services.h +++ b/framework/model/network/wifi/platform/include/hdf_wlan_services.h @@ -60,6 +60,7 @@ enum APCommands { CMD_AP_DEL_STATION, CMD_AP_GET_ASSOC_STA, CMD_AP_SET_COUNTRY_CODE, + CMD_AP_GET_BANDWIDTH, }; enum STACommands { diff --git a/framework/model/sensor/driver/common/include/sensor_config_parser.h b/framework/model/sensor/driver/common/include/sensor_config_parser.h index 1ab2b1ff6d30ffe5a35c0aeea88fbee520d0c1ce..3123f701f73824d652301876e4e6aba965636433 100644 --- a/framework/model/sensor/driver/common/include/sensor_config_parser.h +++ b/framework/model/sensor/driver/common/include/sensor_config_parser.h @@ -20,6 +20,13 @@ #define MAX_SENSOR_INDEX_NUM 48 #define MAX_SENSOR_AXIS_NUM 3 +#define CHECK_PARSER_NAME(ptr, str, cname) do { \ + if (strcpy_s(ptr, SENSOR_INFO_VERSION_MAX_LEN, cname) != EOK) { \ + HDF_LOGE("%s:copy %s failed!", __func__, str); \ + return HDF_FAILURE; \ + } \ +} while (0) + enum SensorRegOpsType { SENSOR_INIT_GROUP = 0, SENSOR_ENABLE_GROUP, diff --git a/framework/model/sensor/driver/common/src/sensor_config_parser.c b/framework/model/sensor/driver/common/src/sensor_config_parser.c index 6c3c2f066672ff6cf80e1533af496d0efe315da4..022346de3d0b4da2a171e8c2d6bd61016c483830 100755 --- a/framework/model/sensor/driver/common/src/sensor_config_parser.c +++ b/framework/model/sensor/driver/common/src/sensor_config_parser.c @@ -310,31 +310,19 @@ static int32_t ParseSensorInfo(struct DeviceResourceIface *parser, const struct ret = parser->GetString(infoNode, "sensorName", &name, NULL); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "sensorName"); - if (strcpy_s(config->sensorInfo.sensorName, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { - HDF_LOGE("%s:copy sensorName failed!", __func__); - return HDF_FAILURE; - } + CHECK_PARSER_NAME(config->sensorInfo.sensorName, "sensorName", name); ret = parser->GetString(infoNode, "vendorName", &name, NULL); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "vendorName"); - if (strcpy_s(config->sensorInfo.vendorName, SENSOR_INFO_NAME_MAX_LEN, name) != EOK) { - HDF_LOGE("%s:copy vendorName failed!", __func__); - return HDF_FAILURE; - } + CHECK_PARSER_NAME(config->sensorInfo.vendorName, "vendorName", name); ret = parser->GetString(infoNode, "firmwareVersion", &name, NULL); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "firmwareVersion"); - if (strcpy_s(config->sensorInfo.firmwareVersion, SENSOR_INFO_VERSION_MAX_LEN, name) != EOK) { - HDF_LOGE("%s:copy firmwareVersion failed!", __func__); - return HDF_FAILURE; - } + CHECK_PARSER_NAME(config->sensorInfo.firmwareVersion, "firmwareVersion", name); ret = parser->GetString(infoNode, "hardwareVersion", &name, NULL); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "hardwareVersion"); - if (strcpy_s(config->sensorInfo.hardwareVersion, SENSOR_INFO_VERSION_MAX_LEN, name) != EOK) { - HDF_LOGE("%s:copy hardwareVersion failed!", __func__); - return HDF_FAILURE; - } + CHECK_PARSER_NAME(config->sensorInfo.hardwareVersion, "hardwareVersion", name); ret = parser->GetUint16(infoNode, "sensorTypeId", &id, 0); CHECK_PARSER_RESULT_RETURN_VALUE(ret, "sensorTypeId"); diff --git a/framework/model/sensor/driver/include/sensor_device_type.h b/framework/model/sensor/driver/include/sensor_device_type.h index 8a5fb04be74903fef3698d865ec190ee03f2f649..572bc04c5b84abc3413d161b29bfae07a0b0e06f 100644 --- a/framework/model/sensor/driver/include/sensor_device_type.h +++ b/framework/model/sensor/driver/include/sensor_device_type.h @@ -90,6 +90,8 @@ struct SensorBasicInfo { int32_t power; /**< Sensor power */ int64_t minDelay; /**< Minimum sample period allowed in nanoseconds */ int64_t maxDelay; /**< Maxmum sample period allowed in nanoseconds */ + uint32_t fifoMaxEventCount; /**< Fifo Max Event Count */ + uint32_t reserved; /**< Reserved */ }; struct SensorReportEvent { diff --git a/framework/support/platform/include/clock/clock_core.h b/framework/support/platform/include/clock/clock_core.h new file mode 100644 index 0000000000000000000000000000000000000000..7e21c73d6a2311ef62670ab0d3725434c5c66fcf --- /dev/null +++ b/framework/support/platform/include/clock/clock_core.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef CLOCK_CORE_H +#define CLOCK_CORE_H + +#include "platform_core.h" +#include "osal_spinlock.h" +#include "hdf_base.h" +#include "clock_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define CLOCK_DEVICES_MAX 61 +#define CLOCK_HANDLE_SHIFT 0xFF00U + +struct ClockDevice; +struct ClockMethod; +struct ClockLockMethod; + +struct ClockDevice { + const struct ClockMethod *ops; + OsalSpinlock spin; + const char *deviceName; + const char *clockName; + uint32_t deviceIndex; + const struct ClockLockMethod *lockOps; + void *clk; + void *priv; + struct ClockDevice *parent; +}; + +struct ClockMethod { + int32_t (*start)(struct ClockDevice *device); + int32_t (*stop)(struct ClockDevice *device); + int32_t (*setRate)(struct ClockDevice *device, uint32_t rate); + int32_t (*getRate)(struct ClockDevice *device, uint32_t *rate); + int32_t (*disable)(struct ClockDevice *device); + int32_t (*enable)(struct ClockDevice *device); + struct ClockDevice *(*getParent)(struct ClockDevice *device); + int32_t (*setParent)(struct ClockDevice *device, struct ClockDevice *parent); +}; + +struct ClockLockMethod { + int32_t (*lock)(struct ClockDevice *device); + void (*unlock)(struct ClockDevice *device); +}; + +int32_t ClockDeviceAdd(struct ClockDevice *device); + +int32_t ClockManagerGetAIdleDeviceId(); + +void ClockDeviceRemove(struct ClockDevice *device); + +struct ClockDevice *ClockDeviceGet(uint32_t number); + +struct ClockDevice *ClockDeviceOpen(uint32_t number); + +int32_t ClockDeviceClose(struct ClockDevice *device); + +int32_t ClockDeviceEnable(struct ClockDevice *device); + +int32_t ClockDeviceDisable(struct ClockDevice *device); + +int32_t ClockDeviceSetRate(struct ClockDevice *device, uint32_t rate); + +int32_t ClockDeviceGetRate(struct ClockDevice *device, uint32_t *rate); + +struct ClockDevice *ClockDeviceGetParent(struct ClockDevice *device); + +int32_t ClockDeviceSetParent(struct ClockDevice *device, struct ClockDevice *parent); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* CLOCK_CORE_H */ diff --git a/framework/support/platform/src/clock/clock_core.c b/framework/support/platform/src/clock/clock_core.c new file mode 100644 index 0000000000000000000000000000000000000000..58e4f6dcf01a19d69f69e2cfbed0f2675b563730 --- /dev/null +++ b/framework/support/platform/src/clock/clock_core.c @@ -0,0 +1,864 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "clock_core.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "osal_spinlock.h" +#include "osal_time.h" +#include "platform_core.h" +#include "platform_trace.h" + +#define HDF_LOG_TAG clock_core_c + +struct ClockManager { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct ClockDevice *devices[CLOCK_DEVICES_MAX]; + OsalSpinlock spin; +}; + +static struct ClockManager *g_clockManager = NULL; + +static int32_t ClockDeviceLockDefault(struct ClockDevice *device) +{ + if (device == NULL) { + HDF_LOGE("ClockDeviceLockDefault: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + return OsalSpinLock(&device->spin); +} + +static void ClockDeviceUnlockDefault(struct ClockDevice *device) +{ + if (device == NULL) { + HDF_LOGE("ClockDeviceUnlockDefault: device is null!"); + return; + } + (void)OsalSpinUnlock(&device->spin); +} + +static const struct ClockLockMethod g_clockLockOpsDefault = { + .lock = ClockDeviceLockDefault, + .unlock = ClockDeviceUnlockDefault, +}; + +static inline int32_t ClockDeviceLock(struct ClockDevice *device) +{ + if (device->lockOps == NULL || device->lockOps->lock == NULL) { + HDF_LOGE("ClockDeviceLock: clock device lock is not support!"); + return HDF_ERR_NOT_SUPPORT; + } + return device->lockOps->lock(device); +} + +static inline void ClockDeviceUnlock(struct ClockDevice *device) +{ + if (device->lockOps != NULL && device->lockOps->unlock != NULL) { + device->lockOps->unlock(device); + } +} + +static int32_t ClockManagerAddDevice(struct ClockDevice *device) +{ + int32_t ret; + struct ClockManager *manager = g_clockManager; + + if (device->deviceIndex >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerAddDevice: deviceIndex:%u exceed!", device->deviceIndex); + return HDF_ERR_INVALID_OBJECT; + } + + if (manager == NULL) { + HDF_LOGE("ClockManagerAddDevice: get clock manager fail!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrq(&manager->spin) != HDF_SUCCESS) { + HDF_LOGE("ClockManagerAddDevice: lock clock manager fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + if (manager->devices[device->deviceIndex]) { + HDF_LOGE("ClockManagerAddDevice: clock device num:%u already exits!", device->deviceIndex); + ret = HDF_FAILURE; + } else { + manager->devices[device->deviceIndex] = device; + HDF_LOGE("ClockManagerAddDevice: clock device num:%u add success!", device->deviceIndex); + ret = HDF_SUCCESS; + } + + (void)OsalSpinUnlockIrq(&manager->spin); + return ret; +} + +static void ClockManagerRemoveDevice(struct ClockDevice *device) +{ + struct ClockManager *manager = g_clockManager; + + if (device->deviceIndex < 0 || device->deviceIndex >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerRemoveDevice: invalid devNum:%u!", device->deviceIndex); + return; + } + + if (manager == NULL) { + HDF_LOGE("ClockManagerRemoveDevice: get clock manager fail!"); + return; + } + + if (OsalSpinLockIrq(&manager->spin) != HDF_SUCCESS) { + HDF_LOGE("ClockManagerRemoveDevice: lock clock manager fail!"); + return; + } + + if (manager->devices[device->deviceIndex] != device) { + HDF_LOGE("ClockManagerRemoveDevice: clock device(%u) not in manager!", device->deviceIndex); + } else { + manager->devices[device->deviceIndex] = NULL; + } + + (void)OsalSpinUnlockIrq(&manager->spin); +} + +void ClockDeviceRemove(struct ClockDevice *device) +{ + if (device == NULL) { + HDF_LOGE("ClockDeviceRemove: device is null!"); + return; + } + ClockManagerRemoveDevice(device); + (void)OsalSpinDestroy(&device->spin); +} + +static struct ClockDevice *ClockManagerFindDevice(uint32_t number) +{ + struct ClockDevice *device = NULL; + struct ClockManager *manager = g_clockManager; + + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerFindDevice: invalid devNum:%u!", number); + return NULL; + } + + if (manager == NULL) { + HDF_LOGE("ClockManagerFindDevice: get clock manager fail!"); + return NULL; + } + + if (OsalSpinLockIrq(&manager->spin) != HDF_SUCCESS) { + HDF_LOGE("ClockManagerFindDevice: lock clock manager fail!"); + return NULL; + } + + device = manager->devices[number]; + (void)OsalSpinUnlockIrq(&manager->spin); + + return device; +} + +int32_t ClockDeviceAdd(struct ClockDevice *device) +{ + int32_t ret; + if (device == NULL) { + HDF_LOGE("ClockDeviceAdd: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL) { + HDF_LOGE("ClockDeviceAdd: no ops supplied!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->lockOps == NULL) { + HDF_LOGI("ClockDeviceAdd: use default lockOps!"); + device->lockOps = &g_clockLockOpsDefault; + } + + if (OsalSpinInit(&device->spin) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceAdd: init lock fail!"); + return HDF_FAILURE; + } + + ret = ClockManagerAddDevice(device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceAdd: clock manager add device fail!"); + (void)OsalSpinDestroy(&device->spin); + } + return ret; +} + +int32_t ClockManagerGetAIdleDeviceId() +{ + int32_t ret = -1; + int32_t id; + struct ClockManager *manager = g_clockManager; + + if (manager == NULL) { + HDF_LOGE("ClockManagerAddDevice: get clock manager fail!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (OsalSpinLockIrq(&manager->spin) != HDF_SUCCESS) { + HDF_LOGE("ClockManagerAddDevice: lock clock manager fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + for (id = 0; id < CLOCK_DEVICES_MAX; id++) { + if (manager->devices[id] == NULL) { + ret = id; + break; + } + } + + (void)OsalSpinUnlockIrq(&manager->spin); + return ret; +} + +struct ClockDevice *ClockDeviceGet(uint32_t number) +{ + return ClockManagerFindDevice(number); +} + +int32_t ClockDeviceStart(struct ClockDevice *device) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceStart: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->start == NULL) { + HDF_LOGE("ClockDeviceStart: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceStart: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->start(device); + + ClockDeviceUnlock(device); + return ret; +} + +int32_t ClockDeviceStop(struct ClockDevice *device) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceStart: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->stop == NULL) { + HDF_LOGE("ClockDeviceStart: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceStart: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->stop(device); + + ClockDeviceUnlock(device); + return ret; +} + +struct ClockDevice *ClockDeviceOpen(uint32_t number) +{ + int32_t ret; + struct ClockDevice *device = NULL; + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockDeviceOpen: get clock device fail!"); + return NULL; + } + + ret = ClockDeviceStart(device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceOpen: start clock device fail!"); + return NULL; + } + + return device; +} + +int32_t ClockDeviceClose(struct ClockDevice *device) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceClose: get clock device fail!"); + return NULL; + } + ret = ClockDeviceStop(device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceClose: start clock device fail!"); + return NULL; + } + + return HDF_SUCCESS; +} + +int32_t ClockDeviceSetRate(struct ClockDevice *device, uint32_t rate) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceSetRate: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->setRate == NULL) { + HDF_LOGE("ClockDeviceSetRate: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceSetRate: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->setRate(device, rate); + + ClockDeviceUnlock(device); + return ret; +} + +int32_t ClockDeviceGetRate(struct ClockDevice *device, uint32_t *rate) +{ + int32_t ret; + if (device == NULL) { + HDF_LOGE("ClockDeviceGetRate: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->getRate == NULL) { + HDF_LOGE("ClockDeviceGetRate: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceGetRate: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->getRate(device, rate); + ClockDeviceUnlock(device); + return ret; +} + +struct ClockDevice *ClockDeviceGetParent(struct ClockDevice *device) +{ + struct ClockDevice *parent = NULL; + + if (device == NULL) { + HDF_LOGE("ClockDeviceGetParent: device is null!"); + return NULL; + } + + if (device->ops == NULL || device->ops->getParent == NULL) { + HDF_LOGE("ClockDeviceGetParent: ops or getParent is null!"); + return NULL; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceGetParent: lock clock device fail!"); + return NULL; + } + + parent = device->ops->getParent(device); + + ClockDeviceUnlock(device); + return parent; +} + +int32_t ClockDeviceSetParent(struct ClockDevice *device, struct ClockDevice *parent) +{ + int32_t ret; + + if (device == NULL || parent == NULL) { + HDF_LOGE("ClockDeviceSetParent: device or is parent null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->setParent == NULL) { + HDF_LOGE("ClockDeviceSetParent: ops or setParent is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceSetParent: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + if (ClockDeviceLock(parent) != HDF_SUCCESS) { + ClockDeviceUnlock(device); + HDF_LOGE("ClockDeviceGetParent: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + ret = device->ops->setParent(device, parent); + + ClockDeviceUnlock(device); + ClockDeviceUnlock(parent); + return ret; +} + +int32_t ClockDeviceDisable(struct ClockDevice *device) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceDisable: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->disable == NULL) { + HDF_LOGE("ClockDeviceDisable: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceDisable: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->disable(device); + + ClockDeviceUnlock(device); + return ret; +} + +int32_t ClockDeviceEnable(struct ClockDevice *device) +{ + int32_t ret; + + if (device == NULL) { + HDF_LOGE("ClockDeviceEnable: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + if (device->ops == NULL || device->ops->enable == NULL) { + HDF_LOGE("ClockDeviceEnable: ops or start is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + if (ClockDeviceLock(device) != HDF_SUCCESS) { + HDF_LOGE("ClockDeviceEnable: lock clock device fail!"); + return HDF_ERR_DEVICE_BUSY; + } + + ret = device->ops->enable(device); + + ClockDeviceUnlock(device); + return ret; +} + +static int32_t ClockManagerOpen(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + int32_t ret = HDF_SUCCESS; + + if (data == NULL || reply == NULL) { + HDF_LOGE("ClockManagerOpen: invalid data or reply!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerOpen: fail to read number!\n"); + return HDF_ERR_INVALID_PARAM; + } + + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerOpen: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + if (ClockDeviceOpen(number) == NULL) { + HDF_LOGE("ClockManagerOpen: get device %u fail!", number); + return HDF_ERR_NOT_SUPPORT; + } + + if (!HdfSbufWriteUint32(reply, number + CLOCK_HANDLE_SHIFT)) { + HDF_LOGE("ClockManagerOpen: fail to write number!\n"); + return HDF_ERR_INVALID_PARAM; + } + + return ret; +} + +static int32_t ClockManagerClose(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + int32_t ret; + struct ClockDevice *device = NULL; + + if (data == NULL || reply == NULL) { + HDF_LOGE("ClockManagerClose: invalid data or reply!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerClose: fail to read handle!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerClose: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerEnable: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceClose(device); + return ret; +} + +static int32_t ClockManagerEnable(struct HdfSBuf *data) +{ + uint32_t number = 0; + int32_t ret; + struct ClockDevice *device = NULL; + + if (data == NULL) { + HDF_LOGE("ClockManagerEnable: invalid data!"); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerEnable: fail to read number!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerEnable: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerEnable: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceEnable(device); + return ret; +} + +static int32_t ClockManagerDisable(struct HdfSBuf *data) +{ + uint32_t number = 0; + int32_t ret; + struct ClockDevice *device = NULL; + + if (data == NULL) { + HDF_LOGE("ClockManagerDisable: invalid data!"); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerDisable: fail to read number!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerDisable: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerDisable: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + ret = ClockDeviceDisable(device); + return ret; +} + +static int32_t ClockManagerSetRate(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + uint32_t rate = 0; + int32_t ret; + struct ClockDevice *device = NULL; + HDF_LOGE("func = %s line = %d", __FUNCTION__, __LINE__); + if (data == NULL || reply == NULL) { + HDF_LOGE("ClockManagerSetRate: invalid data or reply!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerSetRate: fail to read handle!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerSetRate: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &rate)) { + HDF_LOGE("ClockManagerSetRate: fail to read rate!\n"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerSetRate: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceSetRate(device, rate); + return ret; +} + +static int32_t ClockManagerGetRate(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + uint32_t rate = 0; + struct ClockDevice *device = NULL; + + if (data == NULL || reply == NULL) { + HDF_LOGE("ClockManagerSetRate: invalid data or reply!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerGetRate: fail to read handle!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerGetRate: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerSetRate: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + ClockDeviceGetRate(device, &rate); + + if (!HdfSbufWriteUint32(reply, rate)) { + HDF_LOGE("ClockManagerGetRate: fail to write rate!\n"); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGI("ClockManagerGetRate: get rate = %u !", rate); + return HDF_SUCCESS; +} + +static int32_t ClockManagerGetParent(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + struct ClockDevice *device = NULL; + struct ClockDevice *parent = NULL; + + if (reply == NULL) { + HDF_LOGE("ClockManagerGetParent: invalid reply!\n"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerGetParent: fail to read number!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerGetParent: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerGetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + parent = ClockDeviceGetParent(device); + if (parent == NULL) { + HDF_LOGE("ClockManagerGetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufWriteUint32(reply, parent->deviceIndex + CLOCK_HANDLE_SHIFT)) { + HDF_LOGE("ClockManagerGetParent: fail to write parent!\n"); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +static int32_t ClockManagerSetParent(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + uint32_t number = 0; + uint32_t number_p = 0; + struct ClockDevice *device = NULL; + struct ClockDevice *parent = NULL; + int32_t ret; + + if (!HdfSbufReadUint32(data, &number)) { + HDF_LOGE("ClockManagerSetParent: fail to read handle!\n"); + return HDF_ERR_INVALID_PARAM; + } + + number -= CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerSetParent: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint32(data, &number_p)) { + HDF_LOGE("ClockManagerSetParent: fail to read parent!"); + return HDF_ERR_INVALID_PARAM; + } + + number_p -= CLOCK_HANDLE_SHIFT; + if (number_p >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockManagerSetParent: invalid number_p!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockManagerSetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + parent = ClockDeviceGet(number_p); + if (parent == NULL) { + HDF_LOGE("ClockManagerSetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceSetParent(device, parent); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockManagerSetParent: number_p =%u , number =%u ", number_p, number); + } + + return ret; +} + +static int32_t ClockManagerDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, + struct HdfSBuf *reply) +{ + if (data == NULL) { + HDF_LOGE("ClockManagerDispatch: invalid data cmd =%d!", cmd); + return HDF_ERR_INVALID_PARAM; + } + + (void)client; + switch (cmd) { + case CLOCK_IO_OPEN: + return ClockManagerOpen(data, reply); + break; + case CLOCK_IO_CLOSE: + return ClockManagerClose(data, reply); + break; + case CLOCK_IO_ENABLE: + return ClockManagerEnable(data); + break; + case CLOCK_IO_DISABLE: + return ClockManagerDisable(data); + break; + case CLOCK_IO_SET_RATE: + return ClockManagerSetRate(data, reply); + break; + case CLOCK_IO_GET_RATE: + return ClockManagerGetRate(data, reply); + break; + case CLOCK_IO_SET_PARENT: + return ClockManagerSetParent(data, reply); + break; + case CLOCK_IO_GET_PARENT: + return ClockManagerGetParent(data, reply); + break; + default: + HDF_LOGE("ClockManagerDispatch: cmd %d is not support!", cmd); + return HDF_ERR_NOT_SUPPORT; + } + return HDF_SUCCESS; +} + +static int32_t ClockManagerBind(struct HdfDeviceObject *device) +{ + (void)device; + return HDF_SUCCESS; +} + +static int32_t ClockManagerInit(struct HdfDeviceObject *device) +{ + int32_t ret; + struct ClockManager *manager = NULL; + + if (device == NULL) { + HDF_LOGE("ClockManagerInit: device is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + manager = (struct ClockManager *)OsalMemCalloc(sizeof(*manager)); + if (manager == NULL) { + HDF_LOGE("ClockManagerInit: memcalloc for manager fail!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = OsalSpinInit(&manager->spin); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockManagerInit: spinlock init fail!"); + OsalMemFree(manager); + return HDF_FAILURE; + } + + manager->device = device; + g_clockManager = manager; + device->service = &manager->service; + device->service->Dispatch = ClockManagerDispatch; + return HDF_SUCCESS; +} + +static void ClockManagerRelease(struct HdfDeviceObject *device) +{ + struct ClockManager *manager = NULL; + + if (device == NULL) { + HDF_LOGE("ClockManagerRelease: device is null!"); + return; + } + + manager = (struct ClockManager *)device->service; + if (manager == NULL) { + HDF_LOGE("ClockManagerRelease: no service bind!"); + return; + } + g_clockManager = NULL; + OsalMemFree(manager); +} + +struct HdfDriverEntry g_clockManagerEntry = { + .moduleVersion = 1, + .Bind = ClockManagerBind, + .Init = ClockManagerInit, + .Release = ClockManagerRelease, + .moduleName = "HDF_PLATFORM_CLOCK_MANAGER", +}; +HDF_INIT(g_clockManagerEntry); diff --git a/framework/support/platform/src/clock/clock_if.c b/framework/support/platform/src/clock/clock_if.c new file mode 100644 index 0000000000000000000000000000000000000000..080e8d3cfe9ac60ccc48c84197789000c797a593 --- /dev/null +++ b/framework/support/platform/src/clock/clock_if.c @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "clock_if.h" +#include "clock_core.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#define HDF_LOG_TAG clock_if_c + +DevHandle ClockOpen(uint32_t number) +{ + if (ClockDeviceOpen(number) == NULL) { + HDF_LOGE("ClockOpen: get device %u fail!", number); + return NULL; + } + return (DevHandle)(number + CLOCK_HANDLE_SHIFT); +} + +int32_t ClockClose(DevHandle handle) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockClose: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockClose: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceClose(device); + return ret; +} + +int32_t ClockEnable(DevHandle handle) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockEnable: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockEnable: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceEnable(device); + return ret; +} + +int32_t ClockDisable(DevHandle handle) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockDisable: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockDisable: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceDisable(device); + return ret; +} + +int32_t ClockSetRate(DevHandle handle, uint32_t rate) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockSetRate: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockSetRate: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + return ClockDeviceSetRate(device, rate); +} + +int32_t ClockGetRate(DevHandle handle, uint32_t *rate) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockGetRate: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockGetRate: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceGetRate(device, rate); + return ret; +} + +DevHandle ClockGetParent(DevHandle handle) +{ + int32_t ret; + uint32_t number = 0; + struct ClockDevice *device = NULL; + struct ClockDevice *parent = NULL; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockGetParent: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockGetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + parent = ClockDeviceGetParent(device); + if (parent == NULL) { + HDF_LOGE("ClockGetParent: get clock parent fail!"); + return HDF_ERR_INVALID_PARAM; + } + + return (DevHandle)(parent->deviceIndex + CLOCK_HANDLE_SHIFT); +} + +int32_t ClockSetParent(DevHandle handle, DevHandle parent) +{ + uint32_t number = 0; + uint32_t number_p = 0; + struct ClockDevice *device = NULL; + struct ClockDevice *pdevices = NULL; + int32_t ret; + + number = (uint32_t)handle - CLOCK_HANDLE_SHIFT; + if (number >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockSetParent: invalid number!"); + return HDF_ERR_INVALID_PARAM; + } + + number_p = (uint32_t)parent - CLOCK_HANDLE_SHIFT; + if (number_p >= CLOCK_DEVICES_MAX) { + HDF_LOGE("ClockSetParent: invalid number_p!"); + return HDF_ERR_INVALID_PARAM; + } + + device = ClockDeviceGet(number); + if (device == NULL) { + HDF_LOGE("ClockSetParent: get clock device fail!"); + return HDF_ERR_INVALID_PARAM; + } + + pdevices = ClockDeviceGet(number_p); + if (parent == NULL) { + HDF_LOGE("ClockManagerSetParent: get clock pdevices fail!"); + return HDF_ERR_INVALID_PARAM; + } + + ret = ClockDeviceSetParent(device, pdevices); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockManagerSetParent: number_p =%u , number =%u ", number_p, number); + } + + return ret; +} \ No newline at end of file diff --git a/framework/support/platform/src/clock/clock_if_u.c b/framework/support/platform/src/clock/clock_if_u.c new file mode 100644 index 0000000000000000000000000000000000000000..7c63c792b185f5a673e5bebeaf6cd8a6c225c430 --- /dev/null +++ b/framework/support/platform/src/clock/clock_if_u.c @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "clock_if.h" + +#define HDF_LOG_TAG clock_if_u_c +#define CLOCK_SERVICE_NAME "HDF_PLATFORM_CLOCK_MANAGER" + +static void *ClockManagerGetService(void) +{ + static void *manager = NULL; + + if (manager != NULL) { + return manager; + } + + manager = (void *)HdfIoServiceBind(CLOCK_SERVICE_NAME); + if (manager == NULL) { + HDF_LOGE("ClockManagerGetService: fail to get clock manager!"); + } + return manager; +} + +DevHandle ClockOpen(uint32_t number) +{ + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + uint32_t handle = 0; + int ret = -1; + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockOpen: service is null!"); + return NULL; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockOpen: fail to obtain data!"); + return NULL; + } + + reply = HdfSbufObtainDefaultSize(); + if (reply == NULL) { + HDF_LOGE("ClockOpen: fail to obtain reply!"); + HdfSbufRecycle(data); + return NULL; + } + + if (!HdfSbufWriteUint32(data, number)) { + HDF_LOGE("ClockOpen: fail to write nodepath!"); + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return NULL; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_OPEN, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockOpen: service call CLOCK_IO_OPEN fail, ret: %d!", ret); + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return NULL; + } + + if (!HdfSbufReadUint32(reply, &handle)) { + HDF_LOGE("ClockOpen: read handle fail!"); + ret = HDF_ERR_IO; + } + + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return (DevHandle)(uintptr_t)handle; +} + +int32_t ClockClose(DevHandle handle) +{ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + + if (handle == NULL) { + HDF_LOGE("ClockClose: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockClose: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockClose: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockClose: write handle fail!"); + HdfSbufRecycle(data); + return HDF_FAILURE; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_CLOSE, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockClose: service call CLOCK_IO_CLOSE fail, ret: %d", ret); + } + HdfSbufRecycle(data); + return ret; +} + +int32_t ClockEnable(DevHandle handle) +{ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + + if (handle == NULL) { + HDF_LOGE("ClockEnable: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockEnable: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockEnable: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockEnable: write handle fail!"); + HdfSbufRecycle(data); + return HDF_FAILURE; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_ENABLE, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockEnable: service call CLOCK_IO_ENABLE fail, ret: %d", ret); + } + HdfSbufRecycle(data); + return ret; +} + +int32_t ClockDisable(DevHandle handle) +{ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + + if (handle == NULL) { + HDF_LOGE("ClockDisable: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockDisable: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockDisable: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockDisable: write handle fail!"); + HdfSbufRecycle(data); + return HDF_ERR_IO; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_DISABLE, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockDisable: service call CLOCK_IO_DISABLE fail, ret: %d", ret); + } + HdfSbufRecycle(data); + return ret; +} + +int32_t ClockSetRate(DevHandle handle, uint32_t value) +{ + int32_t ret; + struct HdfIoService *service = NULL; + struct HdfSBuf *data = NULL; + + if (handle == NULL) { + HDF_LOGE("ClockSetRate: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockSetRate: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockSetRate: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockSetRate: write handle fail!"); + HdfSbufRecycle(data); + return HDF_ERR_IO; + } + + if (!HdfSbufWriteUint32(data, value)) { + HDF_LOGE("ClockSetRate: write channel fail!"); + HdfSbufRecycle(data); + return HDF_ERR_IO; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_SET_RATE, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockSetRate: service call CLOCK_IO_SET_RATE fail, ret: %d", ret); + } + HdfSbufRecycle(data); + return ret; +} + +int32_t ClockGetRate(DevHandle handle, uint32_t *rate) +{ + int32_t ret; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + + if (handle == NULL) { + HDF_LOGE("ClockGetRate: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockGetRate: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockGetRate: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + reply = HdfSbufObtainDefaultSize(); + if (reply == NULL) { + HdfSbufRecycle(data); + HDF_LOGE("ClockGetRate: fail to obtain reply!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockGetRate: write handle fail!"); + ret = HDF_ERR_IO; + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_GET_RATE, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockGetRate: service call CLOCK_IO_GET_RATE fail, ret: %d!", ret); + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; + } + + if (!HdfSbufReadUint32(reply, rate)) { + HDF_LOGE("ClockGetRate: read val fail!"); + ret = HDF_ERR_IO; + } + + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; +} + +DevHandle ClockGetParent(DevHandle handle) +{ + int32_t ret; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + uint32_t parent = 0; + + if (handle == NULL) { + HDF_LOGE("ClockGetParent: handle is invalid!"); + return NULL; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockGetParent: service is invalid!"); + return NULL; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockGetParent: fail to obtain data!"); + return NULL; + } + + reply = HdfSbufObtainDefaultSize(); + if (reply == NULL) { + HdfSbufRecycle(data); + HDF_LOGE("ClockGetParent: fail to obtain reply!"); + return NULL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockGetParent: write handle fail!"); + ret = HDF_ERR_IO; + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return NULL; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_GET_PARENT, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockGetParent: service call CLOCK_IO_GET_PARENT fail, ret: %d!", ret); + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return NULL; + } + + if (!HdfSbufReadUint32(reply, &parent)) { + HDF_LOGE("ClockGetParent: read val fail!"); + ret = HDF_ERR_IO; + } + + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return (DevHandle)(uintptr_t)parent; +} + +int32_t ClockSetParent(DevHandle handle, DevHandle parent) +{ + int32_t ret; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + + if (handle == NULL || parent == NULL) { + HDF_LOGE("ClockSetParent: handle is invalid!"); + return HDF_FAILURE; + } + + service = (struct HdfIoService *)ClockManagerGetService(); + if (service == NULL || service->dispatcher == NULL || service->dispatcher->Dispatch == NULL) { + HDF_LOGE("ClockSetParent: service is invalid!"); + return HDF_ERR_INVALID_PARAM; + } + + data = HdfSbufObtainDefaultSize(); + if (data == NULL) { + HDF_LOGE("ClockSetParent: fail to obtain data!"); + return HDF_ERR_MALLOC_FAIL; + } + + reply = HdfSbufObtainDefaultSize(); + if (reply == NULL) { + HdfSbufRecycle(data); + HDF_LOGE("ClockSetParent: fail to obtain reply!"); + return HDF_ERR_MALLOC_FAIL; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)handle)) { + HDF_LOGE("ClockSetParent: write handle fail!"); + ret = HDF_ERR_IO; + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; + } + + if (!HdfSbufWriteUint32(data, (uint32_t)(uintptr_t)parent)) { + HDF_LOGE("ClockSetParent: write handle fail!"); + ret = HDF_ERR_IO; + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; + } + + ret = service->dispatcher->Dispatch(&service->object, CLOCK_IO_SET_PARENT, data, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockSetParent: service call CLOCK_IO_SET_PARENT fail, ret: %d!", ret); + } + + HdfSbufRecycle(data); + HdfSbufRecycle(reply); + return ret; +} \ No newline at end of file diff --git a/framework/support/platform/test/fuzztest/fuzz.gni b/framework/support/platform/test/fuzztest/fuzz.gni index b7603d9ff69649a4c3cce6ae143806c7a0a3c59f..02efb2efdc9c220a37b73d9b0521aeef82fc03f3 100644 --- a/framework/support/platform/test/fuzztest/fuzz.gni +++ b/framework/support/platform/test/fuzztest/fuzz.gni @@ -7,7 +7,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/platform" +module_output_path = "hdf_core/hdf_core" include_dirs = [ "//drivers/hdf_core/framework/include/platform", diff --git a/framework/support/platform/test/unittest/common/hdf_clock_test.cpp b/framework/support/platform/test/unittest/common/hdf_clock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3efa85e705a642d462e42b721f7d51d966b93869 --- /dev/null +++ b/framework/support/platform/test/unittest/common/hdf_clock_test.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "hdf_uhdf_test.h" +#include "clock_test.h" +#include "hdf_io_service_if.h" + +using namespace testing::ext; + +class HdfClockTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfClockTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfClockTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfClockTest::SetUp() +{ +} + +void HdfClockTest::TearDown() +{ +} + +/** + * @tc.name: ClockTestEnable001 + * @tc.desc: clock enable test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestEnable001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_ENABLE, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_ENABLE)); +} + +/** + * @tc.name: ClockTestDisable001 + * @tc.desc: clock disable test + * @tc.type: FUNC + * @tc.require: NA + */ + +HWTEST_F(HdfClockTest, ClockTestDisable001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_DISABLE, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_DISABLE)); +} + +/** + * @tc.name: ClockTestSetrate001 + * @tc.desc: clock setrate test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestSetrate001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_SET_RATE, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_SET_RATE)); +} + +/** + * @tc.name: ClockTestGetRate001 + * @tc.desc: clock getrate test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestGetRate001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_GET_RATE, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_GET_RATE)); +} + +/** + * @tc.name: ClockTestGetparent001 + * @tc.desc: clock getparent test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestGetparent001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_GET_PARENT, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_GET_PARENT)); +} + +/** + * @tc.name: ClockTestSetparent001 + * @tc.desc: clock setparent test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestSetparent001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_SET_PARENT, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_SET_PARENT)); +} + +/** + * @tc.name: ClockTestMultiThread001 + * @tc.desc: clock multi thread test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, ClockTestMultiThread001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_MULTI_THREAD, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_MULTI_THREAD)); +} + +/** + * @tc.name: CLOCKTestReliability001 + * @tc.desc: clock reliability test + * @tc.type: FUNC + * @tc.require: NA + */ +HWTEST_F(HdfClockTest, CLOCKTestReliability001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_TEST_CMD_RELIABILITY, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_TEST_CMD_RELIABILITY)); +} + +/** + * @tc.name: ClockIfPerformanceTest001 + * @tc.desc: clock user if performance test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfClockTest, ClockIfPerformanceTest001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_PAL_CLOCK_TYPE, CLOCK_IF_PERFORMANCE_TEST, -1}; + EXPECT_EQ(0, HdfTestSendMsgToService(&msg)); + EXPECT_EQ(0, ClockTestExecute(CLOCK_IF_PERFORMANCE_TEST)); +} diff --git a/framework/support/platform/test/unittest/common/hdf_pcie_bus_test.cpp b/framework/support/platform/test/unittest/common/hdf_pcie_bus_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..847cb7f02e3f025fe6838c03878811d87907bd3a --- /dev/null +++ b/framework/support/platform/test/unittest/common/hdf_pcie_bus_test.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "hdf_io_service_if.h" +#include "hdf_uhdf_test.h" +#include "pcie_bus_test.h" + +using namespace testing::ext; +namespace OHOS { +class HdfPcieBusTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void HdfPcieBusTest::SetUpTestCase() +{ + HdfTestOpenService(); +} + +void HdfPcieBusTest::TearDownTestCase() +{ + HdfTestCloseService(); +} + +void HdfPcieBusTest::SetUp() +{} + +void HdfPcieBusTest::TearDown() +{} + +/** + * @tc.name: PcieBusGetBusInfo001 + * @tc.desc: test getBusInfo interface. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, PcieBusGetBusInfo001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_GET_INFO, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: PcieBusReadAndWrite001 + * @tc.desc: test readData/WriteData interface. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, PcieBusReadAndWrite001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_READ_WRITE_DATA, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusBulkReadAndWrite001 + * @tc.desc: test bulkRead/bulkWrite interface. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusBulkReadAndWrite001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_READ_WRITE_BULK, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusFunc0ReadAndWrite001 + * @tc.desc: test readFunc0/writeFunc0 interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusFunc0ReadAndWrite001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_READ_WRITE_FUNC0, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusIrqClaimAndRelease001 + * @tc.desc: test claimIrq/releaseIrq interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusIrqClaimAndRelease001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_CLAIM_RELEASE_IRQ, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusDisableAndReset001 + * @tc.desc: test disable/reset interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusDisableAndReset001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_DISABLE_RESET_BUS, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusHostClaimAndRelease001 + * @tc.desc: test claimHost/releaseHost interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusHostClaimAndRelease001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_CLAIM_RELEASE_HOST, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusIoReadAndWrite001 + * @tc.desc: test readIo/writeIo interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusIoReadAndWrite001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_READ_WRITE_IO, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} + +/** + * @tc.name: TestPcieBusDmaMapAndUnMap001 + * @tc.desc: test dmaMap/dmaUnmap interface in kernel status. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(HdfPcieBusTest, TestPcieBusDmaMapAndUnMap001, TestSize.Level1) +{ + struct HdfTestMsg msg = {TEST_WIFI_PCIE_BUS_TYPE, CMD_TEST_PCIE_BUS_MAP_UNMAP_DMA, -1}; + EXPECT_EQ(HDF_SUCCESS, HdfTestSendMsgToService(&msg)); +} +} // namespace OHOS diff --git a/framework/test/fuzztest/devmgr_c_fuzzer/queryusabledeviceInfo_fuzzer/BUILD.gn b/framework/test/fuzztest/devmgr_c_fuzzer/queryusabledeviceInfo_fuzzer/BUILD.gn index 1f0aa6ff346afc9347111ba709f329e64e0f4478..cd348514c421f1f5e3e553eb957c945b655c534a 100644 --- a/framework/test/fuzztest/devmgr_c_fuzzer/queryusabledeviceInfo_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devmgr_c_fuzzer/queryusabledeviceInfo_fuzzer/BUILD.gn @@ -7,7 +7,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf_core/devmgr_c" +module_output_path = "hdf_core/hdf_core/devmgr_c" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/devmgr_c_fuzzer/unloaddevice_fuzzer/BUILD.gn b/framework/test/fuzztest/devmgr_c_fuzzer/unloaddevice_fuzzer/BUILD.gn index d5ecb8a90fcbd05588f21706266ec78a4c1823af..e2be401041ccc0a279dddd4f398c4eff40d7c0d7 100644 --- a/framework/test/fuzztest/devmgr_c_fuzzer/unloaddevice_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devmgr_c_fuzzer/unloaddevice_fuzzer/BUILD.gn @@ -7,7 +7,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf_core/devmgr_c" +module_output_path = "hdf_core/hdf_core/devmgr_c" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/devmgr_cpp_fuzzer/loaddevice_fuzzer/BUILD.gn b/framework/test/fuzztest/devmgr_cpp_fuzzer/loaddevice_fuzzer/BUILD.gn index 4468462b4c6e228ebca8b6ca556b6238cd46ebb6..be553cff9844fa2cca6b5adf0281946b955104a3 100644 --- a/framework/test/fuzztest/devmgr_cpp_fuzzer/loaddevice_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devmgr_cpp_fuzzer/loaddevice_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/devmgr_cpp" +module_output_path = "hdf_core/hdf_core/devmgr_cpp" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/devmgr_cpp_fuzzer/unloaddevice_fuzzer/BUILD.gn b/framework/test/fuzztest/devmgr_cpp_fuzzer/unloaddevice_fuzzer/BUILD.gn index a2212b4c8f98c898cebee1286484bdd3c4789b65..e57cfae64c07ea763e0365cd9125d12ac33c2bca 100644 --- a/framework/test/fuzztest/devmgr_cpp_fuzzer/unloaddevice_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devmgr_cpp_fuzzer/unloaddevice_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/devmgr_cpp" +module_output_path = "hdf_core/hdf_core/devmgr_cpp" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/devmgrservicestub_fuzzer/BUILD.gn b/framework/test/fuzztest/devmgrservicestub_fuzzer/BUILD.gn index d8c411cd2cafa499b0ec3ccfd90835fb24957ffa..95943116f4e3455129e501b10d4aa7500d3aaca5 100644 --- a/framework/test/fuzztest/devmgrservicestub_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devmgrservicestub_fuzzer/BUILD.gn @@ -11,7 +11,7 @@ import("//build/test.gni") hdf_framework_path = "../../../" hdf_adapter_path = "../../../../adapter" hdf_interfaces_path = "../../../../interfaces" -module_output_path = "hdf_core/devmgrservicestub" +module_output_path = "hdf_core/hdf_core" ohos_fuzztest("DevmgrServiceStubFuzzTest") { module_out_path = module_output_path diff --git a/framework/test/fuzztest/devsvcmanagerstub_fuzzer/BUILD.gn b/framework/test/fuzztest/devsvcmanagerstub_fuzzer/BUILD.gn index ee9bd8e5c3e7043a18067186e7f77c9e197ee17e..3be624029010e3b18c59c70e6d6ac9997d13be12 100644 --- a/framework/test/fuzztest/devsvcmanagerstub_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/devsvcmanagerstub_fuzzer/BUILD.gn @@ -11,7 +11,7 @@ import("//build/test.gni") hdf_framework_path = "../../../" hdf_adapter_path = "../../../../adapter" hdf_interfaces_path = "../../../../interfaces" -module_output_path = "hdf_core/devsvcmanagerstub" +module_output_path = "hdf_core/hdf_core" ohos_fuzztest("DevSvcManagerStubFuzzTest") { module_out_path = module_output_path diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioserviceadapterobtain_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioserviceadapterobtain_fuzzer/BUILD.gn index 3aff4ea5c6e540b171332cd6eb83df7ac7e95580..0ed22fd828b9472733f046f86e655e8b438e2942 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioserviceadapterobtain_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioserviceadapterobtain_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioservicebind_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioservicebind_fuzzer/BUILD.gn index 3b6b541736d12252842c4af38ff02b69715f6a5f..b3c9bdb597f66af4a8867939ef40a3333eb3e551 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioservicebind_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioservicebind_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioservicegrouplisten_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioservicegrouplisten_fuzzer/BUILD.gn index 80c29229d8fc2a66434e9d93816787db44f14158..1e741368da5f8c198c928ca98c46d5de54dac1b7 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioservicegrouplisten_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioservicegrouplisten_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioservicelisten_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioservicelisten_fuzzer/BUILD.gn index 9a2b3b72b296a203d9e606173b712e3997cd050d..0ab7cdccc8d488fbfcff3c3d16592a554e8ecff3 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioservicelisten_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioservicelisten_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioservicenamegetbydeviceclass_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioservicenamegetbydeviceclass_fuzzer/BUILD.gn index 736d53b5ff637beb6c3bba71e04d634ba90737bf..fe02ec260ba1837f24734e46fb0968934991e897 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioservicenamegetbydeviceclass_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioservicenamegetbydeviceclass_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioservicepublish_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioservicepublish_fuzzer/BUILD.gn index 1a08bc4979188be214995329d0d845ea70195c97..b5619d8b13c8b99122979961877bcb5b993f7427 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioservicepublish_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioservicepublish_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/ioserviceremove_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/ioserviceremove_fuzzer/BUILD.gn index 217d25cf1608f58444345e48a2172d66b3dd0d5e..6698c9823523cbab79de3a921bd07164f17696f7 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/ioserviceremove_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/ioserviceremove_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/ioservice_fuzzer/loaddriverbyservicename_fuzzer/BUILD.gn b/framework/test/fuzztest/ioservice_fuzzer/loaddriverbyservicename_fuzzer/BUILD.gn index 854bfcb26181aa316451f4d54a166ac67bf2086e..ab5316f214cb1715e7cab9f9d3aa63b85e27f708 100644 --- a/framework/test/fuzztest/ioservice_fuzzer/loaddriverbyservicename_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/ioservice_fuzzer/loaddriverbyservicename_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/ioservice" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" diff --git a/framework/test/fuzztest/servmgr_c_fuzzer/listservicebyinterfacedesc_fuzzer/BUILD.gn b/framework/test/fuzztest/servmgr_c_fuzzer/listservicebyinterfacedesc_fuzzer/BUILD.gn index 769d2b285d79798ea40af60aa7323e28f6372ecc..b6232647341d6db467f8f8e1b8d6d744ece0cb97 100644 --- a/framework/test/fuzztest/servmgr_c_fuzzer/listservicebyinterfacedesc_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/servmgr_c_fuzzer/listservicebyinterfacedesc_fuzzer/BUILD.gn @@ -7,7 +7,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf_core/servmgr_c" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/servmgr_cpp_fuzzer/servstatlistenerstub_fuzzer/BUILD.gn b/framework/test/fuzztest/servmgr_cpp_fuzzer/servstatlistenerstub_fuzzer/BUILD.gn index 1c07fa83066238b8b2a2230a395691697c5d9cc3..2b889afb20c70bf83796385fcdb14c421b8719be 100644 --- a/framework/test/fuzztest/servmgr_cpp_fuzzer/servstatlistenerstub_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/servmgr_cpp_fuzzer/servstatlistenerstub_fuzzer/BUILD.gn @@ -7,7 +7,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf_core/servmgr_cpp" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/fuzztest/servmgr_cpp_fuzzer/unregisterservicestatuslistener_fuzzer/BUILD.gn b/framework/test/fuzztest/servmgr_cpp_fuzzer/unregisterservicestatuslistener_fuzzer/BUILD.gn index ed858e6ade44af752fa8e4246764a8cf63ffe0fa..049d1827631b275e50e17d4a2ac5a6bf27aebfbd 100644 --- a/framework/test/fuzztest/servmgr_cpp_fuzzer/unregisterservicestatuslistener_fuzzer/BUILD.gn +++ b/framework/test/fuzztest/servmgr_cpp_fuzzer/unregisterservicestatuslistener_fuzzer/BUILD.gn @@ -6,7 +6,7 @@ import("//build/config/features.gni") import("//build/test.gni") -module_output_path = "hdf_core/servmgr_cpp" +module_output_path = "hdf_core/hdf_core" hdf_framework_path = "./../../../../../framework" hdf_adapter_path = "./../../../../../adapter" diff --git a/framework/test/unittest/common/hdf_main_test.c b/framework/test/unittest/common/hdf_main_test.c index aa010b177e23e3b6e33b5aacd13e1fc447b895b7..b00936ab365aa7528ffcd06ae40a0a4a31914a2a 100644 --- a/framework/test/unittest/common/hdf_main_test.c +++ b/framework/test/unittest/common/hdf_main_test.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 Huawei Device Co., Ltd. + * Copyright (c) 2020-2023 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. @@ -34,6 +34,9 @@ #if defined(LOSCFG_DRIVERS_HDF_PLATFORM_ADC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_ADC) #include "hdf_adc_entry_test.h" #endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_CLOCK) || defined(CONFIG_DRIVERS_HDF_PLATFORM_CLOCK) +#include "hdf_clock_entry_test.h" +#endif #if defined(LOSCFG_DRIVERS_HDF_PLATFORM_DAC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_DAC) #include "hdf_dac_entry_test.h" #endif @@ -87,7 +90,9 @@ #if defined(LOSCFG_DRIVERS_HDF_USB_DDK_HOST) || defined(CONFIG_DRIVERS_HDF_USB_DDK_HOST) #include "hdf_usb_entry_test.h" #endif - +#if defined(LOSCFG_DRIVERS_HDF_WLAN_PCIE) || defined(CONFIG_DRIVERS_HDF_WLAN_PCIE) +#include "hdf_pcie_bus_entry_test.h" +#endif #define HDF_LOG_TAG hdf_test // add submodule entry @@ -120,6 +125,9 @@ HdfTestFuncList g_hdfTestFuncList[] = { #if defined(LOSCFG_DRIVERS_HDF_PLATFORM_ADC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_ADC) { TEST_PAL_ADC_TYPE, HdfAdcTestEntry }, #endif +#if defined(LOSCFG_DRIVERS_HDF_PLATFORM_CLOCK) || defined(CONFIG_DRIVERS_HDF_PLATFORM_CLOCK) + { TEST_PAL_CLOCK_TYPE, HdfClockTestEntry }, +#endif #if defined(LOSCFG_DRIVERS_HDF_PLATFORM_DAC) || defined(CONFIG_DRIVERS_HDF_PLATFORM_DAC) { TEST_PAL_DAC_TYPE, HdfDacTestEntry }, #endif @@ -166,6 +174,9 @@ HdfTestFuncList g_hdfTestFuncList[] = { #if defined(LOSCFG_DRIVERS_HDF_WIFI) || defined(CONFIG_DRIVERS_HDF_WIFI) {TEST_WIFI_TYPE, HdfWifiEntry}, #endif +#if defined(LOSCFG_DRIVERS_HDF_WLAN_PCIE) || defined(CONFIG_DRIVERS_HDF_WLAN_PCIE) + {TEST_WIFI_PCIE_BUS_TYPE, HdfPcieBusUnitTestEntry}, +#endif #if defined(LOSCFG_DRIVERS_HDF_AUDIO_TEST) || defined(CONFIG_DRIVERS_HDF_AUDIO_TEST) {TEST_AUDIO_TYPE, HdfAudioEntry}, #endif diff --git a/framework/test/unittest/common/hdf_main_test.h b/framework/test/unittest/common/hdf_main_test.h index ac4a8304037eb2818c82af71896622ed9fbb063e..74630a5fd0d515ebfdaea5f62f902d651cd60c8d 100644 --- a/framework/test/unittest/common/hdf_main_test.h +++ b/framework/test/unittest/common/hdf_main_test.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 Huawei Device Co., Ltd. + * Copyright (c) 2020-2023 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. @@ -75,6 +75,7 @@ typedef enum { TEST_OSAL_END = 400, TEST_WIFI_BEGIN = TEST_OSAL_END, TEST_WIFI_TYPE = TEST_WIFI_BEGIN + 1, + TEST_WIFI_PCIE_BUS_TYPE, TEST_WIFI_END = 600, TEST_CONFIG_TYPE = 601, TEST_AUDIO_TYPE = 701, diff --git a/framework/test/unittest/include/hdf_uhdf_test.h b/framework/test/unittest/include/hdf_uhdf_test.h index ee65bf32dbda86ba214a2825d19804a87a628b68..3296fa15a1654c36168bfcccb51b40576e51f136 100644 --- a/framework/test/unittest/include/hdf_uhdf_test.h +++ b/framework/test/unittest/include/hdf_uhdf_test.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 Huawei Device Co., Ltd. + * Copyright (c) 2020-2023 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. @@ -72,6 +72,7 @@ enum HdfTestSubModuleCmd { TEST_OSAL_END = 400, TEST_WIFI_BEGIN = TEST_OSAL_END, TEST_WIFI_TYPE = TEST_WIFI_BEGIN + 1, + TEST_WIFI_PCIE_BUS_TYPE, TEST_WIFI_END = 600, TEST_CONFIG_TYPE = 601, TEST_HDF_FRAME_END = 800, diff --git a/framework/test/unittest/platform/common/clock_driver_test.c b/framework/test/unittest/platform/common/clock_driver_test.c new file mode 100644 index 0000000000000000000000000000000000000000..ad58a6835a6057696802936d40cdb5052f40345b --- /dev/null +++ b/framework/test/unittest/platform/common/clock_driver_test.c @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "clock_test.h" +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG clock_test_driver_c + +static struct ClockTestConfig g_config; + +static int32_t ClockTestDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + (void)data; + (void)client; + + if (cmd == 0) { + if (reply == NULL) { + HDF_LOGE("ClockTestDispatch: reply is null!"); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufWriteBuffer(reply, &g_config, sizeof(g_config))) { + HDF_LOGE("ClockTestDispatch: write reply fail!"); + return HDF_ERR_IO; + } + } else { + HDF_LOGE("ClockTestDispatch: cmd %d is not support!", cmd); + return HDF_ERR_NOT_SUPPORT; + } + + return HDF_SUCCESS; +} + +static int32_t ClockTestReadConfig(struct ClockTestConfig *config, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("ClockTestReadConfig: invalid drs ops!"); + return HDF_FAILURE; + } + + ret = drsOps->GetUint32(node, "deviceIndex", &config->deviceIndex, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestReadConfig: read deviceIndex fail!"); + return ret; + } + + return HDF_SUCCESS; +} + +static int32_t ClockTestBind(struct HdfDeviceObject *device) +{ + int32_t ret; + static struct IDeviceIoService service; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("ClockTestBind: device or config is null!"); + return HDF_ERR_IO; + } + + ret = ClockTestReadConfig(&g_config, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestBind: read config fail!"); + return ret; + } + + service.Dispatch = ClockTestDispatch; + device->service = &service; + HDF_LOGI("ClockTestBind: done!"); + return HDF_SUCCESS; +} + +static int32_t ClockTestInit(struct HdfDeviceObject *device) +{ + (void)device; + HDF_LOGI("ClockTestInit: done!"); + return HDF_SUCCESS; +} + +static void ClockTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + HDF_LOGI("ClockTestRelease: done!"); + return; +} + +struct HdfDriverEntry g_clockTestEntry = { + .moduleVersion = 1, + .Bind = ClockTestBind, + .Init = ClockTestInit, + .Release = ClockTestRelease, + .moduleName = "PLATFORM_CLOCK_TEST", +}; +HDF_INIT(g_clockTestEntry); diff --git a/framework/test/unittest/platform/common/clock_test.c b/framework/test/unittest/platform/common/clock_test.c new file mode 100644 index 0000000000000000000000000000000000000000..74e9c8d0e28a544b81da2dcaa2014e8a97293589 --- /dev/null +++ b/framework/test/unittest/platform/common/clock_test.c @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "clock_test.h" +#include "clock_if.h" +#include "hdf_base.h" +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#include "osal_thread.h" +#include "osal_time.h" + +#define DEFAULT_RATE 10000 +#define CLOCK_TEST_STACK_SIZE (1024 * 64) +#define CLOCK_TEST_SLEEP_TIME 100 +#define CLOCK_TEST_WAIT_TIMEOUT 20 +#define HDF_LOG_TAG clock_test_c +DevHandle parent = NULL; + +static int32_t ClockTestGetConfig(struct ClockTestConfig *config) +{ + int32_t ret; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + const void *buf = NULL; + uint32_t len; + + HDF_LOGD("ClockTestGetConfig: enter!"); + service = HdfIoServiceBind("CLOCK_TEST"); + if (service == NULL) { + HDF_LOGE("ClockTestGetConfig: service is null!"); + return HDF_ERR_NOT_SUPPORT; + } + + do { + reply = HdfSbufObtain(sizeof(*config) + sizeof(uint64_t)); + if (reply == NULL) { + HDF_LOGE("ClockTestGetConfig: fail to obtain reply!"); + ret = HDF_ERR_MALLOC_FAIL; + break; + } + + ret = service->dispatcher->Dispatch(&service->object, 0, NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestGetConfig: remote dispatch fail!"); + break; + } + + if (!HdfSbufReadBuffer(reply, &buf, &len)) { + HDF_LOGE("ClockTestGetConfig: read buf fail!"); + ret = HDF_ERR_IO; + break; + } + + if (len != sizeof(*config)) { + HDF_LOGE("ClockTestGetConfig: config size:%zu, read size:%u!", sizeof(*config), len); + ret = HDF_ERR_IO; + break; + } + + if (memcpy_s(config, sizeof(*config), buf, sizeof(*config)) != EOK) { + HDF_LOGE("ClockTestGetConfig: memcpy buf fail!"); + ret = HDF_ERR_IO; + break; + } + HDF_LOGD("ClockTestGetConfig: exit!"); + ret = HDF_SUCCESS; + } while (0); + HdfSbufRecycle(reply); + HdfIoServiceRecycle(service); + return ret; +} + +static struct ClockTester *ClockTesterGet(void) +{ + int32_t ret; + static struct ClockTester tester; + static bool hasInit = false; + + HDF_LOGE("ClockTesterGet: enter!"); + if (hasInit) { + return &tester; + } + ret = ClockTestGetConfig(&tester.config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTesterGet: read config fail, ret: %d!", ret); + return NULL; + } + tester.handle = ClockOpen(tester.config.deviceIndex); + if (tester.handle == NULL) { + HDF_LOGE("ClockTesterGet: open clock device:%u fail!", tester.config.deviceIndex); + return NULL; + } + hasInit = true; + HDF_LOGI("ClockTesterGet: done!"); + return &tester; +} + +static int32_t ClockTestEnable(void) +{ + struct ClockTester *tester = NULL; + int32_t ret; + + HDF_LOGI("ClockTestEnable: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestEnable: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockEnable(tester->handle); + + HDF_LOGI("ClockTestEnable: clock device num is %u!", tester->config.deviceIndex); + HDF_LOGI("ClockTestEnable: done!"); + return ret; +} + +static int ClockTestThreadFunc(void *param) +{ + struct ClockTester *tester = NULL; + int32_t ret; + + HDF_LOGI("ClockTestThreadFunc: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestThreadFunc: get tester fail!"); + *((int32_t *)param) = 1; + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockEnable(tester->handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestThreadFunc: clock read fail, ret: %d!", ret); + *((int32_t *)param) = 1; + return HDF_ERR_IO; + } + + *((int32_t *)param) = 1; + HDF_LOGI("ClockTestThreadFunc: done!"); + return HDF_SUCCESS; +} + +static int32_t ClockTestStartThread(struct OsalThread *thread1, struct OsalThread *thread2, const int32_t *count1, + const int32_t *count2) +{ + int32_t ret; + uint32_t time = 0; + struct OsalThreadParam cfg1; + struct OsalThreadParam cfg2; + + if (memset_s(&cfg1, sizeof(cfg1), 0, sizeof(cfg1)) != EOK || + memset_s(&cfg2, sizeof(cfg2), 0, sizeof(cfg2)) != EOK) { + HDF_LOGE("ClockTestStartThread: memset_s fail!"); + return HDF_ERR_IO; + } + + cfg1.name = "ClockTestThread-1"; + cfg2.name = "ClockTestThread-2"; + cfg1.priority = cfg2.priority = OSAL_THREAD_PRI_DEFAULT; + cfg1.stackSize = cfg2.stackSize = CLOCK_TEST_STACK_SIZE; + + ret = OsalThreadStart(thread1, &cfg1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestStartThread: start test thread1 fail, ret: %d!", ret); + return ret; + } + + ret = OsalThreadStart(thread2, &cfg2); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestStartThread: start test thread2 fail, ret: %d!", ret); + } + + while (*count1 == 0 || *count2 == 0) { + HDF_LOGD("ClockTestStartThread: waitting testing thread finish..."); + OsalMSleep(CLOCK_TEST_SLEEP_TIME); + time++; + if (time > CLOCK_TEST_WAIT_TIMEOUT) { + break; + } + } + return ret; +} + +static int32_t ClockTestDisable(void) +{ + struct ClockTester *tester = NULL; + int32_t ret; + + HDF_LOGI("ClockTestDisable: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestDisable: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockDisable(tester->handle); + + HDF_LOGI("ClockTestDisable: done!"); + return ret; +} + +static int32_t ClockTestSetrate(void) +{ + struct ClockTester *tester = NULL; + int32_t ret; + + HDF_LOGI("ClockTestSetrate: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestSetrate: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockSetRate(tester->handle, DEFAULT_RATE); + + HDF_LOGI("ClockTestSetrate: done!"); + return ret; +} + +static int32_t ClockTestGetrate(void) +{ + struct ClockTester *tester = NULL; + int32_t ret; + uint32_t rate; + + HDF_LOGI("ClockTestGetrate: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestGetrate: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockGetRate(tester->handle, &rate); + + HDF_LOGI("ClockTestGetrate: done!"); + return ret; +} + +static int32_t ClockTestGetparent(void) +{ + struct ClockTester *tester = NULL; + + HDF_LOGI("ClockTestGetparent: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestGetparent: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + parent = ClockGetParent(tester->handle); + + HDF_LOGI("ClockTestGetparent: done!"); + return HDF_SUCCESS; +} + +static int32_t ClockTestSetparent(void) +{ + struct ClockTester *tester = NULL; + int32_t ret; + + HDF_LOGI("ClockTestSetparent: enter!"); + tester = ClockTesterGet(); + if (tester == NULL) { + HDF_LOGE("ClockTestSetparent: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + ret = ClockSetParent(tester->handle, parent); + + HDF_LOGI("ClockTestSetparent: done!"); + return ret; +} + +static int32_t ClockTestMultiThread(void) +{ + int32_t ret; + struct OsalThread thread1; + struct OsalThread thread2; + int32_t count1 = 0; + int32_t count2 = 0; + + ret = OsalThreadCreate(&thread1, (OsalThreadEntry)ClockTestThreadFunc, (void *)&count1); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestMultiThread: create test thread1 fail, ret: %d!", ret); + return ret; + } + + ret = OsalThreadCreate(&thread2, (OsalThreadEntry)ClockTestThreadFunc, (void *)&count2); + if (ret != HDF_SUCCESS) { + (void)OsalThreadDestroy(&thread1); + HDF_LOGE("ClockTestMultiThread: create test thread2 fail, ret: %d!", ret); + return ret; + } + + ret = ClockTestStartThread(&thread1, &thread2, &count1, &count2); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockTestStartThread: test start thread fail, ret: %d!", ret); + } + + (void)OsalThreadDestroy(&thread1); + (void)OsalThreadDestroy(&thread2); + return HDF_SUCCESS; +} + +static int32_t ClockTestReliability(void) +{ + uint32_t rate; + HDF_LOGI("ClockTestReliability: enter!"); + // invalid handle + ClockEnable(NULL); + // invalid handle + ClockDisable(NULL); + // invalid handle + ClockSetRate(NULL, DEFAULT_RATE); + // invalid handle + ClockGetRate(NULL, &rate); + // invalid handle + ClockGetParent(NULL); + // invalid handle + ClockSetParent(NULL, NULL); + HDF_LOGI("ClockTestReliability: done!"); + return HDF_SUCCESS; +} + +static int32_t ClockIfPerformanceTest(void) +{ +#ifdef __LITEOS__ + // liteos the accuracy of the obtained time is too large and inaccurate. + return HDF_SUCCESS; +#endif + struct ClockTester *tester = NULL; + uint64_t startMs; + uint64_t endMs; + uint64_t useTime; // ms + int32_t ret; + + tester = ClockTesterGet(); + if (tester == NULL || tester->handle == NULL) { + HDF_LOGE("ClockIfPerformanceTest: get tester fail!"); + return HDF_ERR_INVALID_OBJECT; + } + + startMs = OsalGetSysTimeMs(); + ret = ClockEnable(tester->handle); + if (ret == HDF_SUCCESS) { + endMs = OsalGetSysTimeMs(); + useTime = endMs - startMs; + HDF_LOGI("ClockIfPerformanceTest: ----->interface performance test:[start - end] < 1ms[%s]\r\n", + useTime < 1 ? "yes" : "no"); + return HDF_SUCCESS; + } + return HDF_SUCCESS; +} + +struct ClockTestEntry { + int cmd; + int32_t (*func)(void); + const char *name; +}; + +static struct ClockTestEntry g_entry[] = { + {CLOCK_TEST_CMD_ENABLE, ClockTestEnable, "ClockTestEnable"}, + {CLOCK_TEST_CMD_DISABLE, ClockTestDisable, "ClockTestDisable"}, + {CLOCK_TEST_CMD_SET_RATE, ClockTestSetrate, "ClockTestSetrate"}, + {CLOCK_TEST_CMD_GET_RATE, ClockTestGetrate, "ClockTestGetrate"}, + {CLOCK_TEST_CMD_GET_PARENT, ClockTestGetparent, "ClockTestGetparent"}, + {CLOCK_TEST_CMD_SET_PARENT, ClockTestSetparent, "ClockTestSetparent"}, + {CLOCK_TEST_CMD_MULTI_THREAD, ClockTestMultiThread, "ClockTestMultiThread"}, + {CLOCK_TEST_CMD_RELIABILITY, ClockTestReliability, "ClockTestReliability"}, + {CLOCK_IF_PERFORMANCE_TEST, ClockIfPerformanceTest, "ClockIfPerformanceTest"}, +}; + +int32_t ClockTestExecute(int cmd) +{ + uint32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + + if (cmd > CLOCK_TEST_CMD_MAX) { + HDF_LOGE("ClockTestExecute: invalid cmd:%d!", cmd); + ret = HDF_ERR_NOT_SUPPORT; + HDF_LOGE("[ClockTestExecute][======cmd:%d====ret:%d======]", cmd, ret); + return ret; + } + + for (i = 0; i < sizeof(g_entry) / sizeof(g_entry[0]); i++) { + if (g_entry[i].cmd != cmd || g_entry[i].func == NULL) { + continue; + } + ret = g_entry[i].func(); + break; + } + + HDF_LOGE("[ClockTestExecute][======cmd:%d====ret:%d======]", cmd, ret); + return ret; +} diff --git a/framework/test/unittest/platform/common/clock_test.h b/framework/test/unittest/platform/common/clock_test.h new file mode 100644 index 0000000000000000000000000000000000000000..b836a8088e0cb308d51e4072bd3908625b0a4112 --- /dev/null +++ b/framework/test/unittest/platform/common/clock_test.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef CLOCK_TEST_H +#define CLOCK_TEST_H + +#include "clock_if.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +struct ClockTestConfig { + uint32_t deviceIndex; +}; + +struct ClockTester { + struct ClockTestConfig config; + DevHandle handle; +}; + +enum ClockTestCmd { + CLOCK_TEST_CMD_ENABLE = 0, + CLOCK_TEST_CMD_DISABLE, + CLOCK_TEST_CMD_SET_RATE, + CLOCK_TEST_CMD_GET_RATE, + CLOCK_TEST_CMD_GET_PARENT, + CLOCK_TEST_CMD_SET_PARENT, + CLOCK_TEST_CMD_MULTI_THREAD, + CLOCK_TEST_CMD_RELIABILITY, + CLOCK_IF_PERFORMANCE_TEST, + CLOCK_TEST_CMD_MAX, +}; + +int32_t ClockTestExecute(int cmd); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* CLOCK_TEST_H */ diff --git a/framework/test/unittest/platform/common/pcie_bus_driver_test.c b/framework/test/unittest/platform/common/pcie_bus_driver_test.c new file mode 100644 index 0000000000000000000000000000000000000000..5c08a8816b658984447030e209ed016d73dfc166 --- /dev/null +++ b/framework/test/unittest/platform/common/pcie_bus_driver_test.c @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "device_resource_if.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "hdf_ibus_intf.h" +#include "hdf_log.h" +#include "pcie_bus_test.h" + +static struct PcieBusTestConfig g_config; + +static int32_t PcieBusTestDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, + struct HdfSBuf *reply) +{ + HDF_LOGD("%s: enter!", __func__); + + (void)client; + (void)data; + if (cmd == 0) { + if (reply == NULL) { + HDF_LOGE("%s: reply is null!", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufWriteBuffer(reply, &g_config, sizeof(g_config))) { + HDF_LOGE("%s: write config failed", __func__); + return HDF_ERR_IO; + } + return HDF_SUCCESS; + } else { + return HDF_ERR_NOT_SUPPORT; + } +} + +static int32_t PcieBusTestReadConfig(const struct DeviceResourceNode *node) +{ + HDF_LOGI("PcieBusTestReadConfig enter."); + int32_t ret; + uint32_t busNum = 0; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("PcieBusTestReadConfig: invalid drs ops"); + return HDF_FAILURE; + } + ret = drsOps->GetUint32(node, "busNum", &busNum, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("PcieBusTestReadConfig: read bus num failed"); + return ret; + } + g_config.busNum = (uint8_t)busNum; + return HDF_SUCCESS; +} + +static int32_t PcieBusTestBind(struct HdfDeviceObject *device) +{ + HDF_LOGI("%{public}s enter.", __func__); + static struct IDeviceIoService service; + + if (device == NULL) { + HDF_LOGE("%s: device or config is null!", __func__); + return HDF_ERR_IO; + } + service.Dispatch = PcieBusTestDispatch; + device->service = &service; + + return HDF_SUCCESS; +} + +static int32_t PcieBusTestInit(struct HdfDeviceObject *device) +{ + int32_t ret; + if (device->property == NULL) { + HDF_LOGW("PcieBusTestInit property is NULL."); + return HDF_SUCCESS; + } + + ret = PcieBusTestReadConfig(device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config failed", __func__); + } + return ret; +} + +static void PcieBusTestRelease(struct HdfDeviceObject *device) +{ + if (device != NULL) { + device->service = NULL; + } + return; +} + +struct HdfDriverEntry g_pcieBusTestEntry = { + .moduleVersion = 1, + .Bind = PcieBusTestBind, + .Init = PcieBusTestInit, + .Release = PcieBusTestRelease, + .moduleName = "PLATFORM_PCIE_BUS_TEST", +}; +HDF_INIT(g_pcieBusTestEntry); diff --git a/framework/test/unittest/platform/common/pcie_bus_test.c b/framework/test/unittest/platform/common/pcie_bus_test.c new file mode 100644 index 0000000000000000000000000000000000000000..8c293164f126aa0a6ff60b14d03fa23df769d2a9 --- /dev/null +++ b/framework/test/unittest/platform/common/pcie_bus_test.c @@ -0,0 +1,384 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "pcie_bus_test.h" +#include +#include "hdf_base.h" +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "pcie_if.h" +#define USER_LEM_MAX 8192 +#define DMA_ALIGN_SIZE 256 +#define DMA_TEST_LEN 256 +#define PCIE_TEST_DISABLE_ADDR 0xB7 +#define PCIE_TEST_UPPER_ADDR 0x28 +#define PCIE_TEST_CMD_ADDR 0x04 + +struct PcieBusTestFunc { + int32_t cmd; + int32_t (*func)(struct PcieBusTester *tester); +}; + +static int32_t TestPcieBusGetInfo(struct PcieBusTester *tester) +{ + int32_t ret; + struct BusConfig config; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.getBusInfo(&tester->busDev, &config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: getBusInfo failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t TestPcieBusDataReadWrite(struct PcieBusTester *tester) +{ + uint8_t disable; + uint32_t upper; + uint16_t cmd; + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + ret = tester->busDev.ops.readData(&tester->busDev, PCIE_TEST_DISABLE_ADDR, sizeof(disable), &disable); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: disable read failed ret = %d.", __func__, ret); + return ret; + } + HDF_LOGD("%s: disable is %d", __func__, disable); + + ret = tester->busDev.ops.writeData(&tester->busDev, PCIE_TEST_DISABLE_ADDR, sizeof(disable), &disable); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: disable write failed ret = %d.", __func__, ret); + return ret; + } + + ret = tester->busDev.ops.readData(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(upper), (uint8_t *)&upper); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: upper read failed ret = %d.", __func__, ret); + return ret; + } + HDF_LOGD("%s: upper is %d", __func__, upper); + + ret = tester->busDev.ops.writeData(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(upper), (uint8_t *)&upper); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: upper write failed ret = %d.", __func__, ret); + return ret; + } + + ret = tester->busDev.ops.readData(&tester->busDev, PCIE_TEST_CMD_ADDR, sizeof(cmd), (uint8_t *)&cmd); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: cmd read failed ret = %d.", __func__, ret); + return ret; + } + HDF_LOGD("%s: cmd is %d", __func__, disable); + + ret = tester->busDev.ops.writeData(&tester->busDev, PCIE_TEST_CMD_ADDR, sizeof(cmd), (uint8_t *)&cmd); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: cmd write failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t TestPcieBusBulkReadWrite(struct PcieBusTester *tester) +{ + uint32_t data; + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.bulkRead(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(data), (uint8_t *)&data, + sizeof(data)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: readFunc0 failed ret = %d.", __func__, ret); + return ret; + } + ret = tester->busDev.ops.bulkWrite(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(data), (uint8_t *)&data, + sizeof(data)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: writeFunc0 failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t TestPcieBusFunc0ReadWrite(struct PcieBusTester *tester) +{ + uint32_t data; + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.readFunc0(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(data), (uint8_t *)&data); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: readFunc0 failed ret = %d.", __func__, ret); + return ret; + } + ret = tester->busDev.ops.writeFunc0(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(data), (uint8_t *)&data); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: writeFunc0 failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static void PcieBusIrqHandler(void *arg) +{ + HDF_LOGD("%s: data is %{public}p", __func__, arg); +} + +static int32_t TestPcieBusIrqClaimRelease(struct PcieBusTester *tester) +{ + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.claimIrq(&tester->busDev, PcieBusIrqHandler, NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: claimIrq failed ret = %d.", __func__, ret); + return ret; + } + + ret = tester->busDev.ops.releaseIrq(&tester->busDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: releaseIrq failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t TestPcieBusDisalbeReset(struct PcieBusTester *tester) +{ + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.disableBus(&tester->busDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: disableBus failed ret = %d.", __func__, ret); + return ret; + } + ret = tester->busDev.ops.reset(&tester->busDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: disableBus failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t TestPcieBusHostClaimRelease(struct PcieBusTester *tester) +{ + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + tester->busDev.ops.claimHost(&tester->busDev); + tester->busDev.ops.releaseHost(&tester->busDev); + return HDF_SUCCESS; +} + +static int32_t TestPcieBusIoReadWrite(struct PcieBusTester *tester) +{ + uint32_t upper; + int32_t ret; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + ret = tester->busDev.ops.ioRead(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(upper), (uint8_t *)&upper); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: upper read failed ret = %d.", __func__, ret); + return ret; + } + HDF_LOGD("%s: upper is %d", __func__, upper); + + ret = tester->busDev.ops.ioWrite(&tester->busDev, PCIE_TEST_UPPER_ADDR, sizeof(upper), (uint8_t *)&upper); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: upper write failed ret = %d.", __func__, ret); + return ret; + } + return HDF_SUCCESS; +} + +static int32_t PcieBusMapHandler(void *arg) +{ + HDF_LOGD("%s: data is %{public}p", __func__, arg); + return HDF_SUCCESS; +} + +static int32_t TestPcieBusDmaMapUnMap(struct PcieBusTester *tester) +{ + int32_t ret; + uintptr_t buf = 0; + if (tester == NULL) { + HDF_LOGE("%s: tester is null.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + buf = (uintptr_t)OsalMemAllocAlign(DMA_ALIGN_SIZE, DMA_TEST_LEN); + if (buf == 0) { + HDF_LOGE("%s: malloc fail", __func__); + return HDF_ERR_MALLOC_FAIL; + } + // dma to device + ret = tester->busDev.ops.dmaMap(&tester->busDev, PcieBusMapHandler, buf, DMA_TEST_LEN, PCIE_DMA_TO_DEVICE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed ret = %d", __func__, ret); + OsalMemFree((void *)buf); + return ret; + } + + ret = tester->busDev.ops.dmaUnmap(&tester->busDev, buf, DMA_TEST_LEN, PCIE_DMA_TO_DEVICE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed ret = %d", __func__, ret); + OsalMemFree((void *)buf); + return ret; + } + + /* device to dma */ + ret = tester->busDev.ops.dmaMap(&tester->busDev, PcieBusMapHandler, buf, DMA_TEST_LEN, PCIE_DMA_FROM_DEVICE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed ret = %d", __func__, ret); + OsalMemFree((void *)buf); + return ret; + } + ret = tester->busDev.ops.dmaUnmap(&tester->busDev, buf, DMA_TEST_LEN, PCIE_DMA_FROM_DEVICE); + OsalMemFree((void *)buf); + return HDF_SUCCESS; +} + +static struct PcieBusTestFunc g_entry[] = { + {CMD_TEST_PCIE_BUS_GET_INFO, TestPcieBusGetInfo}, + {CMD_TEST_PCIE_BUS_READ_WRITE_DATA, TestPcieBusDataReadWrite}, + {CMD_TEST_PCIE_BUS_READ_WRITE_BULK, TestPcieBusBulkReadWrite}, + {CMD_TEST_PCIE_BUS_READ_WRITE_FUNC0, TestPcieBusFunc0ReadWrite}, + {CMD_TEST_PCIE_BUS_CLAIM_RELEASE_IRQ, TestPcieBusIrqClaimRelease}, + {CMD_TEST_PCIE_BUS_DISABLE_RESET_BUS, TestPcieBusDisalbeReset}, + {CMD_TEST_PCIE_BUS_CLAIM_RELEASE_HOST, TestPcieBusHostClaimRelease}, + {CMD_TEST_PCIE_BUS_READ_WRITE_IO, TestPcieBusIoReadWrite}, + {CMD_TEST_PCIE_BUS_MAP_UNMAP_DMA, TestPcieBusDmaMapUnMap}, +}; + +static int32_t PcieBusTesterGetConfig(struct PcieBusTestConfig *config) +{ + int32_t ret; + struct HdfSBuf *reply = NULL; + struct HdfIoService *service = NULL; + const void *buf = NULL; + uint32_t len; + + service = HdfIoServiceBind("PCIE_BUS_TEST"); + if ((service == NULL) || (service->dispatcher == NULL) || (service->dispatcher->Dispatch == NULL)) { + HDF_LOGE("%s: HdfIoServiceBind failed\n", __func__); + return HDF_ERR_NOT_SUPPORT; + } + + reply = HdfSbufObtain(sizeof(*config) + sizeof(uint32_t)); + if (reply == NULL) { + HDF_LOGE("%s: failed to obtain reply", __func__); + HdfIoServiceRecycle(service); + return HDF_ERR_MALLOC_FAIL; + } + + ret = service->dispatcher->Dispatch(&service->object, 0, NULL, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: remote dispatch failed", __func__); + HdfIoServiceRecycle(service); + HdfSbufRecycle(reply); + return ret; + } + + if (!HdfSbufReadBuffer(reply, &buf, &len)) { + HDF_LOGE("%s: read buf failed", __func__); + HdfIoServiceRecycle(service); + HdfSbufRecycle(reply); + return HDF_ERR_IO; + } + + if (len != sizeof(*config)) { + HDF_LOGE("%s: config size:%zu, read size:%u", __func__, sizeof(*config), len); + HdfIoServiceRecycle(service); + HdfSbufRecycle(reply); + return HDF_ERR_IO; + } + + if (memcpy_s(config, sizeof(*config), buf, sizeof(*config)) != EOK) { + HDF_LOGE("%s: memcpy buf failed", __func__); + HdfIoServiceRecycle(service); + HdfSbufRecycle(reply); + return HDF_ERR_IO; + } + + HdfIoServiceRecycle(service); + HdfSbufRecycle(reply); + return HDF_SUCCESS; +} + +static struct PcieBusTester *PcieBusTesterGet(void) +{ + static struct PcieBusTester tester = {0}; + struct HdfConfigWlanBus busConfig = {0}; + int32_t ret = PcieBusTesterGetConfig(&tester.config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read config failed:%d", __func__, ret); + return NULL; + } + HdfWlanConfigBusAbs(tester.config.busNum); + busConfig.busIdx = tester.config.busNum; + // busConfig.blockSize + HdfWlanBusAbsInit(&tester.busDev, &busConfig); + return &tester; +} + +static void PcieBusTesterPut(struct PcieBusTester *tester) +{ + if (tester == NULL) { + HDF_LOGE("%s:tester or service is null", __func__); + return; + } + tester->busDev.ops.deInit(&tester->busDev); +} + +int32_t PcieBusTestExecute(int32_t cmd) +{ + uint32_t i; + int32_t ret = HDF_ERR_NOT_SUPPORT; + struct PcieBusTester *tester = NULL; + + if (cmd > CMD_TEST_PCIE_MAX) { + HDF_LOGE("%s: invalid cmd:%d", __func__, cmd); + return ret; + } + + tester = PcieBusTesterGet(); + if (tester == NULL) { + HDF_LOGE("%s: get tester failed", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + for (i = 0; i < sizeof(g_entry) / sizeof(g_entry[0]); i++) { + if (g_entry[i].cmd == cmd && g_entry[i].func != NULL) { + ret = g_entry[i].func(tester); + break; + } + } + PcieBusTesterPut(tester); + HDF_LOGI("[%s][======cmd:%d====ret:%d======]", __func__, cmd, ret); + return ret; +} \ No newline at end of file diff --git a/framework/test/unittest/platform/common/pcie_bus_test.h b/framework/test/unittest/platform/common/pcie_bus_test.h new file mode 100644 index 0000000000000000000000000000000000000000..4e9ca57d63de32fef7aa6ac65941af84ca1eb4ab --- /dev/null +++ b/framework/test/unittest/platform/common/pcie_bus_test.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ +#ifndef PCIE_BUS_TEST_H +#define PCIE_BUS_TEST_H +#include +#include "hdf_ibus_intf.h" +#include "hdf_io_service_if.h" + +enum PcieBusCmd { + CMD_TEST_PCIE_BUS_GET_INFO, + CMD_TEST_PCIE_BUS_READ_WRITE_DATA, + CMD_TEST_PCIE_BUS_READ_WRITE_BULK, + CMD_TEST_PCIE_BUS_READ_WRITE_FUNC0, + CMD_TEST_PCIE_BUS_CLAIM_RELEASE_IRQ, + CMD_TEST_PCIE_BUS_DISABLE_RESET_BUS, + CMD_TEST_PCIE_BUS_CLAIM_RELEASE_HOST, + CMD_TEST_PCIE_BUS_READ_WRITE_IO, + CMD_TEST_PCIE_BUS_MAP_UNMAP_DMA, + CMD_TEST_PCIE_MAX, +}; + +struct PcieBusTestConfig { + uint8_t busNum; +}; + +struct PcieBusTester { + struct PcieBusTestConfig config; + struct BusDev busDev; +}; +int32_t PcieBusTestExecute(int32_t cmd); +#endif diff --git a/framework/test/unittest/platform/entry/hdf_clock_entry_test.c b/framework/test/unittest/platform/entry/hdf_clock_entry_test.c new file mode 100644 index 0000000000000000000000000000000000000000..5902e8b0a1a5cc638071044081233b423a3e6c08 --- /dev/null +++ b/framework/test/unittest/platform/entry/hdf_clock_entry_test.c @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_clock_entry_test.h" +#include "clock_test.h" +#include "hdf_log.h" + +#define HDF_LOG_TAG hdf_clock_entry_test + +int32_t HdfClockTestEntry(HdfTestMsg *msg) +{ + if (msg == NULL) { + HDF_LOGE("HdfClockTestEntry: msg is null!"); + return HDF_FAILURE; + } + + msg->result = ClockTestExecute(msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/framework/test/unittest/platform/entry/hdf_clock_entry_test.h b/framework/test/unittest/platform/entry/hdf_clock_entry_test.h new file mode 100644 index 0000000000000000000000000000000000000000..ebb60efe27a0a2a18760f9b24e6ba65d405136fc --- /dev/null +++ b/framework/test/unittest/platform/entry/hdf_clock_entry_test.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_CLOCK_ENTRY_TEST_H +#define HDF_CLOCK_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfClockTestEntry(HdfTestMsg *msg); + +#endif /* HDF_ADC_ENTRY_TEST_H */ \ No newline at end of file diff --git a/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.c b/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.c new file mode 100644 index 0000000000000000000000000000000000000000..2fc5149cebe3d3be617721cb2eac1700c23c71e2 --- /dev/null +++ b/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.c @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "hdf_log.h" +#include "hdf_pcie_entry_test.h" +#include "pcie_bus_test.h" + +#define HDF_LOG_TAG hdf_pcie_bus_entry_test + +int32_t HdfPcieBusUnitTestEntry(HdfTestMsg *msg) +{ + if (msg == NULL) { + return HDF_FAILURE; + } + + msg->result = PcieBusTestExecute(msg->subCmd); + + return HDF_SUCCESS; +} diff --git a/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.h b/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.h new file mode 100644 index 0000000000000000000000000000000000000000..5784bd2e7fd881207b9c70a432010b8c06b251db --- /dev/null +++ b/framework/test/unittest/platform/entry/hdf_pcie_bus_entry_test.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#ifndef HDF_PCIE_BUS_ENTRY_TEST_H +#define HDF_PCIE_BUS_ENTRY_TEST_H + +#include "hdf_main_test.h" + +int32_t HdfPcieBusUnitTestEntry(HdfTestMsg *msg); + +#endif // HDF_PCIE_BUS_ENTRY_TEST_H diff --git a/framework/test/unittest/platform/virtual/clock_virtual.c b/framework/test/unittest/platform/virtual/clock_virtual.c new file mode 100644 index 0000000000000000000000000000000000000000..c4ed400922bb89e0782cd02778589a99b3ca9fc0 --- /dev/null +++ b/framework/test/unittest/platform/virtual/clock_virtual.c @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * + * HDF is dual licensed: you can use it either under the terms of + * the GPL, or the BSD license, at your option. + * See the LICENSE file in the root of this repository for complete details. + */ + +#include "clock/clock_core.h" +#include "device_resource_if.h" +#include "hdf_device_desc.h" +#include "hdf_log.h" +#include "osal_mem.h" +#include "securec.h" +#include "hdf_base.h" + +#define HDF_LOG_TAG clock_Virtual_driver + +int32_t VirtualClockStart(struct ClockDevice *device) +{ + if (device->clk != NULL) { + HDF_LOGI("device->clk already start\n"); + return HDF_SUCCESS; + } + + device->clk = (void *)&device->deviceIndex; + return HDF_SUCCESS; +} + +int32_t VirtualClockSetRate(struct ClockDevice *device, uint32_t rate) +{ + if (device->clk == NULL) { + HDF_LOGE("VirtualClockSetRate: clk IS_ERR_OR_NULL\n"); + return HDF_FAILURE; + } + + return HDF_SUCCESS; +} + +int32_t VirtualClockStop(struct ClockDevice *device) +{ + if (device->clk == NULL) { + HDF_LOGE("VirtualClockStop: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + device->clk = NULL; + return HDF_SUCCESS; +} + +int32_t VirtualClockGetRate(struct ClockDevice *device, uint32_t *rate) +{ + if (device->clk == NULL) { + HDF_LOGE("VirtualClockGetRate: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +int32_t VirtualClockDisable(struct ClockDevice *device) +{ + if (device->clk == NULL) { + HDF_LOGE("VirtualClockDisable: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +int32_t VirtualClockEnable(struct ClockDevice *device) +{ + if (device->clk == NULL) { + HDF_LOGE("VirtualClockEnable: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +struct ClockDevice *VirtualClockGetParent(struct ClockDevice *device); + +int32_t VirtualClockSetParent(struct ClockDevice *device, struct ClockDevice *parent) +{ + if (device->parent == parent) { + HDF_LOGI("ClockSetParent:device parent is not change \n"); + return HDF_SUCCESS; + } + + if (device->clk == NULL) { + HDF_LOGE("ClockSetParent: clk IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + if (parent->clk == NULL) { + HDF_LOGE("ClockSetParent: clk_parent IS_ERR_OR_NULL\n"); + return HDF_ERR_INVALID_PARAM; + } + + if (device->parent && device->parent->deviceName == NULL) { + ClockDeviceRemove(device->parent); + OsalMemFree(device->parent); + } + device->parent = parent; + + return HDF_SUCCESS; +} + +static const struct ClockMethod g_method = { + .start = VirtualClockStart, + .stop = VirtualClockStop, + .setRate = VirtualClockSetRate, + .getRate = VirtualClockGetRate, + .disable = VirtualClockDisable, + .enable = VirtualClockEnable, + .getParent = VirtualClockGetParent, + .setParent = VirtualClockSetParent, +}; + +struct ClockDevice *VirtualClockGetParent(struct ClockDevice *device) +{ + int32_t ret; + struct ClockDevice *clockDevice = NULL; + if (device->clk == NULL) { + HDF_LOGE("ClockGetParent: clk IS_ERR_OR_NULL\n"); + return NULL; + } + + if (device->parent != NULL) { + device->parent->clk = device->clk; + return device->parent; + } + + clockDevice = (struct ClockDevice *)OsalMemCalloc(sizeof(*clockDevice)); + if (clockDevice == NULL) { + HDF_LOGE("ClockGetParent: can not OsalMemCalloc clockDevice \n"); + return NULL; + } + + clockDevice->ops = &g_method; + ret = ClockManagerGetAIdleDeviceId(); + if (ret < 0) { + HDF_LOGE("ClockGetParent: add clock device:%d device if full fail!", ret); + OsalMemFree(clockDevice); + return NULL; + } + + clockDevice->deviceIndex = ret; + clockDevice->clk = device->clk; + + ret = ClockDeviceAdd(clockDevice); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockGetParent: add clock device:%u fail!", clockDevice->deviceIndex); + OsalMemFree(clockDevice); + return NULL; + } + device->parent = clockDevice; + + return clockDevice; +} + +struct VirtualClockDevice { + struct ClockDevice device; + uint32_t deviceIndex; + const char *clockName; + const char *deviceName; +}; + +static int32_t VirtualClockReadDrs(struct VirtualClockDevice *virtual, const struct DeviceResourceNode *node) +{ + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { + HDF_LOGE("VirtualClockReadDrs: invalid drs ops!"); + return HDF_ERR_NOT_SUPPORT; + } + ret = drsOps->GetUint32(node, "deviceIndex", &virtual->deviceIndex, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("VirtualClockReadDrs: read deviceIndex fail, ret: %d!", ret); + return ret; + } + + return HDF_SUCCESS; +} + +static int32_t VirtualClockInit(struct HdfDeviceObject *device) +{ + int32_t ret; + struct VirtualClockDevice *virtual = NULL; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("VirtualClockInit: device or property is null!"); + return HDF_ERR_INVALID_OBJECT; + } + + virtual = (struct VirtualClockDevice *)OsalMemCalloc(sizeof(*virtual)); + if (virtual == NULL) { + HDF_LOGE("VirtualClockInit: alloc virtual fail!"); + return HDF_ERR_MALLOC_FAIL; + } + + ret = VirtualClockReadDrs(virtual, device->property); + if (ret != HDF_SUCCESS) { + HDF_LOGE("VirtualClockInit: read drs fail, ret: %d!", ret); + OsalMemFree(virtual); + return ret; + } + + virtual->device.priv = (void *)device->property; + virtual->device.deviceIndex = virtual->deviceIndex; + virtual->device.ops = &g_method; + ret = ClockDeviceAdd(&virtual->device); + if (ret != HDF_SUCCESS) { + HDF_LOGE("VirtualClockInit: clock clock virtual device:%u fail, ret: %d!", virtual->deviceIndex, ret); + OsalMemFree(virtual); + return ret; + } + + HDF_LOGI("VirtualClockInit: clock virtual driver init success!"); + return ret; +} + +static void VirtualClockRelease(struct HdfDeviceObject *device) +{ + int32_t ret; + uint32_t deviceIndex; + struct ClockDevice *dev = NULL; + struct DeviceResourceIface *drsOps = NULL; + + HDF_LOGI("VirtualClockRelease: enter!"); + if (device == NULL || device->property == NULL) { + HDF_LOGE("VirtualClockRelease: device or property is null!"); + return; + } + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("VirtualClockRelease: invalid drs ops!"); + return; + } + + ret = drsOps->GetUint32(device->property, "deviceIndex", (uint32_t *)&deviceIndex, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("VirtualClockRelease: read devNum fail, ret: %d!", ret); + return; + } + + dev = ClockDeviceGet(deviceIndex); + if (dev != NULL && dev->priv == device->property) { + ret = VirtualClockStop(dev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("ClockRemoveByNode: close fail, ret: %d!", ret); + } + ClockDeviceRemove(dev); + OsalMemFree(dev); + } +} + +static struct HdfDriverEntry g_VirtualClockDriverEntry = { + .moduleVersion = 1, + .Init = VirtualClockInit, + .Release = VirtualClockRelease, + .moduleName = "virtual_clock_driver", +}; +HDF_INIT(g_VirtualClockDriverEntry); diff --git a/framework/tools/hc-gen/src/startup_cfg_gen.cpp b/framework/tools/hc-gen/src/startup_cfg_gen.cpp index dfc4ef64be1f0599401500c86dfb40424b0d1e77..5926c3ee83c16d517c1aaf692b8df633c23e64c4 100644 --- a/framework/tools/hc-gen/src/startup_cfg_gen.cpp +++ b/framework/tools/hc-gen/src/startup_cfg_gen.cpp @@ -39,6 +39,8 @@ static constexpr const char *DYNAMIC_INFO = " \"ondemand\" : true,\n static constexpr const char *SECON_INFO = " \"secon\" : \"u:r:"; static constexpr const char *CRITICAL_INFO = " \"critical\" : ["; static constexpr uint32_t INVALID_PRIORITY = 0xffffffff; +static constexpr const char *SAND_BOX_INFO = " \"sandbox\" : "; +static constexpr uint32_t INVALID_SAND_BOX = 0xffffffff; StartupCfgGen::StartupCfgGen(const std::shared_ptr &ast) : Generator(ast) { } @@ -125,6 +127,10 @@ void StartupCfgGen::HostInfoOutput(const std::string &name, bool end) ofs_ << CRITICAL_INFO << hostInfoMap_[name].hostCritical << "],\n"; } + if (hostInfoMap_[name].sandBox != INVALID_SAND_BOX) { + ofs_ << SAND_BOX_INFO << hostInfoMap_[name].sandBox << ",\n"; + } + ofs_ << SECON_INFO << name << ":s0\"\n"; ofs_ << TAB TAB << "}"; @@ -146,6 +152,7 @@ void StartupCfgGen::InitHostInfo(HostInfo &hostData) hostData.hostCritical = ""; hostData.processPriority = INVALID_PRIORITY; hostData.threadPriority = INVALID_PRIORITY; + hostData.sandBox = INVALID_SAND_BOX; } bool StartupCfgGen::TemplateNodeSeparate() @@ -348,6 +355,11 @@ bool StartupCfgGen::GetHostInfo() GetConfigIntArray(object, hostData.hostCritical); GetProcessPriority(hostInfo, hostData); + object = hostInfo->Lookup("sandbox", PARSEROP_CONFTERM); + if (object != nullptr) { + hostData.sandBox = object->Child()->IntegerValue(); + } + hostData.hostId = hostId; hostInfoMap_.insert(make_pair(serviceName, hostData)); hostId++; diff --git a/framework/tools/hc-gen/src/startup_cfg_gen.h b/framework/tools/hc-gen/src/startup_cfg_gen.h index 355518794d431dec51d8138cfd8e48be5d273c5f..ee469d055df28e8d72238cc39c5c10eb7b1a638c 100644 --- a/framework/tools/hc-gen/src/startup_cfg_gen.h +++ b/framework/tools/hc-gen/src/startup_cfg_gen.h @@ -24,6 +24,7 @@ struct HostInfo { int32_t processPriority; int32_t threadPriority; uint32_t hostId; + uint32_t sandBox; bool dynamicLoad; }; diff --git a/framework/tools/hcs-view/hcsWebView/src/AttrEditor.js b/framework/tools/hcs-view/hcsWebView/src/AttrEditor.js index ce7e42fd57387e1d7815b1472b07f8c3ba56f795..ca1cf6b0e9c46647ce88f0725ba91942dc97ba98 100644 --- a/framework/tools/hcs-view/hcsWebView/src/AttrEditor.js +++ b/framework/tools/hcs-view/hcsWebView/src/AttrEditor.js @@ -19,6 +19,12 @@ const { DataType, NodeType } = require('./hcs/NodeTools'); const { NodeTools } = require('./hcs/NodeTools'); const INT64_MAX = 9223372036854775807n; const INT64_MIN = -9223372036854775808n; +const CASE_DELETE = 5; +const CASE_QUOTE = 4; +const CASE_BOOL = 3; +const CASE_ARRAY = 2; +const CASE_CHARACTER_STR = 1; +const CASE_INTEGER = 0; class AttrEditor { constructor() { @@ -37,30 +43,30 @@ class AttrEditor { } AttributeArea.gi().clear(); - if (this.node_ != null) { + if (this.node_ !== null && this.node_ !== undefined) { AttributeArea.gi().addTitle(this.node_.name_); switch (this.node_.type_) { - case 6: + case DataType.NODE: switch (this.node_.nodeType_) { - case 0: + case NodeType.DATA: this.freshDataNodeNotInheritEditor(this.node_); break; - case 1: - case 2: - case 5: + case NodeType.COPY: + case NodeType.REFERENCE: + case NodeType.INHERIT: this.freshcopyNodeEditor(this.node_); break; - case 3: + case NodeType.DELETE: this.freshdeleteNodeEditor(this.node_); break; - case 4: + case NodeType.TEMPLETE: this.freshTempletNodeEditor(this.node_); break; default: break; } break; - case 7: + case DataType.ATTR: this.freshDefineAttributeEditor(this.node_); break; } @@ -88,19 +94,19 @@ class AttrEditor { ); } changeDataNodeNotInherit(searchId, type, value) { - if (searchId == 'node_type') { + if (searchId === 'node_type') { AttrEditor.gi().changeNodeType(value); - } else if (searchId == 'name' && this.node_.name_ != value) { + } else if (searchId === 'name' && this.node_.name_ !== value) { ModifyNode.modifyName(this.files_, this.root_, this.node_, value); - } else if (searchId == 'add_child_node') { + } else if (searchId === 'add_child_node') { this.node_.isOpen_ = true; let newNode = ModifyNode.addChildNode(this.root_, this.node_); this.callCallback('change_current_select', newNode); - } else if (searchId == 'add_child_attr') { + } else if (searchId === 'add_child_attr') { this.node_.isOpen_ = true; let newNode = ModifyNode.addChildAttr(this.root_, this.node_); this.callCallback('change_current_select', newNode); - } else if (searchId == 'delete') { + } else if (searchId === 'delete') { ModifyNode.deleteNode(this.node_); this.freshEditor(); } @@ -116,7 +122,7 @@ class AttrEditor { this.root_ == this.node_ ); let btnName = node.ref_; - if (btnName == 'unknow') { + if (btnName === 'unknow') { switch (node.nodeType_) { case NodeType.COPY: btnName = '取消复制'; @@ -137,23 +143,23 @@ class AttrEditor { } changecopyNode(searchId, type, value) { - if (searchId == 'name' && this.node_.name_ != value) { + if (searchId === 'name' && this.node_.name_ !== value) { ModifyNode.modifyName(this.files_, this.root_, this.node_, value); - } else if (searchId == 'change_target') { - if (this.node_.ref_ == 'unknow') { + } else if (searchId === 'change_target') { + if (this.node_.ref_ === 'unknow') { ModifyNode.modifyNodeType(this.files_, this.root_, this.node_, 0); this.freshEditor(this.filePoint_, this.node_); this.callCallback('cancel_change_target', this.node_); } else { this.callCallback('change_target', this.node_); } - } else if (searchId == 'node_type') { + } else if (searchId === 'node_type') { AttrEditor.gi().changeNodeType(value); - } else if (searchId == 'add_child_node') { + } else if (searchId === 'add_child_node') { ModifyNode.addChildNode(this.root_, this.node_); - } else if (searchId == 'add_child_attr') { + } else if (searchId === 'add_child_attr') { ModifyNode.addChildAttr(this.root_, this.node_); - } else if (searchId == 'delete') { + } else if (searchId === 'delete') { ModifyNode.deleteNode(this.node_); this.freshEditor(); } @@ -179,20 +185,20 @@ class AttrEditor { ); this.freshEditor(this.filePoint_, this.node_); if ( - this.node_.nodeType_ == NodeType.COPY || - this.node_.nodeType_ == NodeType.INHERIT || - this.node_.nodeType_ == NodeType.REFERENCE + this.node_.nodeType_ === NodeType.COPY || + this.node_.nodeType_ === NodeType.INHERIT || + this.node_.nodeType_ === NodeType.REFERENCE ) { this.callCallback('change_target', this.node_); } } changedeleteNode(searchId, type, value) { - if (searchId == 'name' && this.node_.name_ != value) { + if (searchId === 'name' && this.node_.name_ !== value) { ModifyNode.modifyName(this.files_, this.root_, this.node_, value); - } else if (searchId == 'delete') { + } else if (searchId === 'delete') { ModifyNode.deleteNode(this.node_); this.freshEditor(); - } else if (searchId == 'node_type') { + } else if (searchId === 'node_type') { AttrEditor.gi().changeNodeType(value); } } @@ -208,16 +214,16 @@ class AttrEditor { ); } changeTempletNode(searchId, type, value) { - if (searchId == 'name') { + if (searchId === 'name') { ModifyNode.modifyName(this.files_, this.root_, this.node_, value); - } else if (searchId == 'add_child_node') { + } else if (searchId === 'add_child_node') { ModifyNode.addChildNode(this.root_, this.node_); - } else if (searchId == 'add_child_attr') { + } else if (searchId === 'add_child_attr') { ModifyNode.addChildAttr(this.root_, this.node_); - } else if (searchId == 'delete') { + } else if (searchId === 'delete') { ModifyNode.deleteNode(this.node_); this.freshEditor(); - } else if (searchId == 'node_type') { + } else if (searchId === 'node_type') { AttrEditor.gi().changeNodeType(value); } } @@ -227,54 +233,54 @@ class AttrEditor { AttributeArea.gi().addTopInput('name', 'Name', node.name_); if ( - v.type_ == DataType.INT8 || - v.type_ == DataType.INT16 || - v.type_ == DataType.INT32 || - v.type_ == DataType.INT64) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[0]); + v.type_ === DataType.INT8 || + v.type_ === DataType.INT16 || + v.type_ === DataType.INT32 || + v.type_ === DataType.INT64) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_INTEGER]); AttributeArea.gi().addValidatorInput( 'value', 'Attribute Value', NodeTools.jinZhi10ToX(v.value_, v.jinzhi_), false, '请输入整数'); - } else if (v.type_ == DataType.STRING) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[1]); + } else if (v.type_ === DataType.STRING) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_CHARACTER_STR]); AttributeArea.gi().addInput('value', 'Attribute Value', v.value_); - } else if (v.type_ == DataType.ARRAY) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[2]); + } else if (v.type_ === DataType.ARRAY) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_ARRAY]); AttributeArea.gi().addTextArea('value', 'Attribute Value', NodeTools.arrayToString(v, 20)); - } else if (v.type_ == DataType.BOOL) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[3]); + } else if (v.type_ === DataType.BOOL) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_BOOL]); AttributeArea.gi().addSelect('value', 'Attribute Value', [true, false], v.value_ == 1); - } else if (v.type_ == DataType.REFERENCE) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[4]); + } else if (v.type_ === DataType.REFERENCE) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_QUOTE]); AttributeArea.gi().addLabelButton('change_target', v.value_, 'Original Node'); - } else if (v.type_ == DataType.DELETE) { - AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[5]); + } else if (v.type_ === DataType.DELETE) { + AttributeArea.gi().addSelect('value_type', 'Type', AttrEditor.ATTR_TYPE_STR, AttrEditor.ATTR_TYPE_STR[CASE_DELETE]); } } getNodeValue(v, value) { switch (AttrEditor.ATTR_TYPE_STR.indexOf(value)) { - case 0: + case CASE_INTEGER: v.type_ = DataType.INT8; v.value_ = 0; v.jinzhi_ = 10; break; - case 1: + case CASE_CHARACTER_STR: v.type_ = DataType.STRING; v.value_ = ''; break; - case 2: + case CASE_ARRAY: v.type_ = DataType.ARRAY; v.value_ = []; break; - case 3: + case CASE_BOOL: v.type_ = DataType.BOOL; v.value_ = 1; break; - case 4: + case CASE_QUOTE: v.type_ = DataType.REFERENCE; v.value_ = 'unknow'; break; - case 5: + case CASE_DELETE: v.type_ = DataType.DELETE; break; } @@ -285,7 +291,7 @@ class AttrEditor { let validRes = {}; validRes.errMsg = ''; let ret = NodeTools.jinZhiXTo10(value); - if (ret[0] == undefined) { + if (ret[0] === undefined) { validRes.errMsg = '请输入整数'; } @@ -299,25 +305,25 @@ class AttrEditor { changeDefineAttribute(searchId, type, value) { let v = this.node_.value_; - if (searchId == 'name' && value != this.node_.name_) { + if (searchId === 'name' && value !== this.node_.name_) { ModifyNode.modifyName(this.files_, this.root_, this.node_, value); } - if (searchId == 'value_type') { + if (searchId === 'value_type') { this.getNodeValue(v, value); } - if (searchId == 'change_target') { + if (searchId === 'change_target') { this.callCallback('change_target', v); } - if (searchId == 'value') { + if (searchId === 'value') { if ( - v.type_ == DataType.INT8 || - v.type_ == DataType.INT16 || - v.type_ == DataType.INT32 || - v.type_ == DataType.INT64 + v.type_ === DataType.INT8 || + v.type_ === DataType.INT16 || + v.type_ === DataType.INT32 || + v.type_ === DataType.INT64 ) { let validRes = this.validateNumber(value); let validatorLabel = document.getElementById('valid_' + searchId); - if (validRes.errMsg == '') { + if (validRes.errMsg === '') { validatorLabel.style.display = 'none'; v.value_ = validRes.value; v.jinzhi_ = validRes.base; @@ -325,46 +331,45 @@ class AttrEditor { validatorLabel.innerText = validRes.errMsg; validatorLabel.style.display = ''; } - } else if (v.type_ == DataType.STRING) { + } else if (v.type_ === DataType.STRING) { v.value_ = value; - } else if (v.type_ == DataType.ARRAY) { + } else if (v.type_ === DataType.ARRAY) { v.value_ = NodeTools.stringToArray(value); - } else if (v.type_ == DataType.BOOL) { - v.value_ = value == 'true' ? 1 : 0; + } else if (v.type_ === DataType.BOOL) { + v.value_ = value === 'true' ? 1 : 0; } } - if (searchId == 'delete') { + if (searchId === 'delete') { ModifyNode.deleteNode(this.node_); this.freshEditor(); } } onChange(searchId, type, value) { let pattr = AttrEditor.gi(); - if (pattr.node_ != null) { + if (pattr.node_ !== null) { AttributeArea.gi().addTitle(pattr.node_.name_); - switch (pattr.node_.type_) { - case 6: + case DataType.NODE: switch (pattr.node_.nodeType_) { - case 0: + case NodeType.DATA: pattr.changeDataNodeNotInherit(searchId, type, value); break; - case 1: - case 2: - case 5: + case NodeType.COPY: + case NodeType.REFERENCE: + case NodeType.INHERIT: pattr.changecopyNode(searchId, type, value); break; - case 3: + case NodeType.DELETE: pattr.changedeleteNode(searchId, type, value); break; - case 4: + case NodeType.TEMPLETE: pattr.changeTempletNode(searchId, type, value); break; default: break; } break; - case 7: + case DataType.ATTR: pattr.changeDefineAttribute(searchId, type, value); break; } @@ -373,7 +378,7 @@ class AttrEditor { } callCallback(type, value) { - if (this.callback_ != null) { + if (this.callback_ !== null) { this.callback_(type, value); } } @@ -396,7 +401,7 @@ AttrEditor.ATTR_TYPE_STR = ['整数', '字符串', '数组', '布尔', '引用', AttrEditor.pInstance_ = null; AttrEditor.gi = function () { - if (AttrEditor.pInstance_ == null) { + if (AttrEditor.pInstance_ === null) { AttrEditor.pInstance_ = new AttrEditor(); } return AttrEditor.pInstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/MainEditor.js b/framework/tools/hcs-view/hcsWebView/src/MainEditor.js index 3f387c441fc4d8ec75150e77ee31bde030a19ac7..60a9770d0836c367364161abf17868361efee975 100644 --- a/framework/tools/hcs-view/hcsWebView/src/MainEditor.js +++ b/framework/tools/hcs-view/hcsWebView/src/MainEditor.js @@ -29,27 +29,48 @@ const { XTexture } = require('./engine/graphics/XTexture'); const { XTools } = require('./engine/XTools'); const { ObjectType } = require('./hcs/ast'); -var DISPLAY_TEXT_MAX = 30; -var ELLIPSIS_LEN = 3; -var EQUAL_SIGN_LEN = 3; +const DISPLAY_TEXT_MAX = 30; +const ELLIPSIS_LEN = 3; +const EQUAL_SIGN_LEN = 3; +const MAX_RANDOM = 255; +const CONSTANT_MIDDLE = 2; +const CONSTANT_QUARTER = 4; +const DRAW_HEIGHT = 4; +const COLOR_MAX = 10; +const GRAY_LEVEL = 192; +const INIT_VALUE = -1; +const KEY_VALUE_MAX = 30; +const ONE_KEY_VALUE_MAX = 29; +const TWO_KEY_VALUE_MAX = 28; +const THREE_KEY_VALUE_MAX = 27; +const BGPIC_WIDTH = 156; +const BGPIC_HEIGHT = 112; +const DRAWTEXT_OFFSETX = -3; +const DRAWTEXT_OFFSETY = -3; + +const MouseType = { + DOWN: 1, // 按下 + MOVE: 2, // 移动 + UP: 3, // 抬起 +}; function rgba(colorArr) { return 0xff000000 | (colorArr[0] << 16) | (colorArr[1] << 8) | colorArr[2]; } function getDarker(colorArr) { - for (let i = 0; i < colorArr.length; ++i) { - if (colorArr[i] - 0 > 10) { - colorArr[i] = colorArr[i] - 10; - } - } + colorArr.forEach((item, index) => { + if (item - 0 > COLOR_MAX) { + item = item - COLOR_MAX; + } + }); return rgba(colorArr); } function isDarkColor(colorArr) { let grayLevel = colorArr[0] * 0.299 + colorArr[1] * 0.587 + colorArr[2] * 0.114; - return grayLevel < 192; + return grayLevel < GRAY_LEVEL; } function getVsCodeTheme() { @@ -86,8 +107,8 @@ class MainEditor { this.keyQueue_ = []; this.dropAll_ = { locked: false, - oldx: -1, - oldy: -1, + oldx: INIT_VALUE, + oldy: INIT_VALUE, }; getVsCodeTheme(); this.nodeBtns = []; @@ -103,54 +124,7 @@ class MainEditor { NapiLog.registError(this.onError); this.errorMsg_ = []; this.cutImgDict_ = {}; - this.whiteImg_ = -1; - this.whiteCut_ = -1; - this.cicleImg_ = -1; - this.circleCut_ = -1; - this.cicleOpenImg_ = -1; - this.circleOpenCut_ = -1; - this.rectangleFocusImg_ = -1; - this.rectangleFocusCut_ = -1; - this.nodeIconImg_ = -1; - this.nodeIconCut_ = -1; - this.attrIconImg_ = -1; - this.attrIconCut_ = -1; - this.rootIconImg_ = -1; - this.rootIconCut_ = -1; - this.rootIconFocusImg_ = -1; - this.rootIconFocusCut_ = -1; - RightMenu.backgroundImg_ = -1; - RightMenu.backgroundCut_ = -1; - RightMenu.popItemFocusImg_ = -1; - RightMenu.popItemFocusCut_ = -1; - this.leftRectCicleCut_ = -1; - this.centerRectCut_ = -1; - this.rightRectCicleCut_ = -1; - this.leftRectFocusCicleCut_ = -1; - this.centerFocusCut_ = -1; - this.rightRectFocusCicleCut_ = -1; - this.delay_ = 0; - this.searchBgImg_ = -1; - this.searchBgCut_ = -1; - this.upImg_ = -1; - this.upCut_ = -1; - this.downImg_ = -1; - this.downCut_ = -1; - this.closeImg_ = -1; - this.closeCut_ = -1; - this.searchImg_ = -1; - this.searchCut_ = -1; - this.isSearchResult_ = false; - this.searchRectFocusCicleImg_ = -1; - this.leftSearchFocusCicleCut_ = -1; - this.centerSearchCut_ = -1; - this.rightSearchFocusCicleCut_ = -1; - - this.searchAttrCicleImg_ = -1; - this.leftSearchAttrCicleCut_ = -1; - this.centerSearchAttrCut_ = -1; - this.rightSearchAttrCicleCut_ = -1; - + this.initMainEditorWithInitValue(); this.selectNode_ = { type: null, pnode: null, @@ -176,7 +150,7 @@ class MainEditor { 132, 32 ); - this.cutImgDict_['whiteCut'] = 'rectangle.png'; + this.cutImgDict_.whiteCut = 'rectangle.png'; this.cicleImg_ = XTexture.gi().loadTextureFromImage('../images/circle.png'); this.circleCut_ = XTexture.gi().makeCut( @@ -188,7 +162,7 @@ class MainEditor { 20, 20 ); - this.cutImgDict_['circleCut'] = 'circle.png'; + this.cutImgDict_.circleCut = 'circle.png'; this.cicleOpenImg_ = XTexture.gi().loadTextureFromImage( '../images/circle_open.png' @@ -202,7 +176,7 @@ class MainEditor { 20, 20 ); - this.cutImgDict_['circleOpenCut'] = 'circle_open.png'; + this.cutImgDict_.circleOpenCut = 'circle_open.png'; this.rectangleFocusImg_ = XTexture.gi().loadTextureFromImage( '../images/rectangle_focus.png' @@ -348,19 +322,7 @@ class MainEditor { 32 ); - let bgPic = RightMenu.isDarkBackground_ ? 'pop_background.png' : 'pop_background_light.png'; - let bgPicPath = '../images/' + bgPic; - RightMenu.backgroundImg_ = XTexture.gi().loadTextureFromImage(bgPicPath); - RightMenu.backgroundCut_ = XTexture.gi().makeCut( - RightMenu.backgroundImg_, - 0, - 0, - 156, - 112, - 156, - 112 - ); - this.cutImgDict_['backgroundCut'] = bgPic; + this.reloadBgPic(); RightMenu.popItemFocusImg_ = XTexture.gi().loadTextureFromImage( '../images/pop_item_focus.png' @@ -505,7 +467,64 @@ class MainEditor { this.historyPushed = false; } + initMainEditorWithInitValue() { + this.whiteImg_ = INIT_VALUE; + this.whiteCut_ = INIT_VALUE; + this.cicleImg_ = INIT_VALUE; + this.circleCut_ = INIT_VALUE; + this.cicleOpenImg_ = INIT_VALUE; + this.circleOpenCut_ = INIT_VALUE; + this.rectangleFocusImg_ = INIT_VALUE; + this.rectangleFocusCut_ = INIT_VALUE; + this.nodeIconImg_ = INIT_VALUE; + this.nodeIconCut_ = INIT_VALUE; + this.attrIconImg_ = INIT_VALUE; + this.attrIconCut_ = INIT_VALUE; + this.rootIconImg_ = INIT_VALUE; + this.rootIconCut_ = INIT_VALUE; + this.rootIconFocusImg_ = INIT_VALUE; + this.rootIconFocusCut_ = INIT_VALUE; + RightMenu.backgroundImg_ = INIT_VALUE; + RightMenu.backgroundCut_ = INIT_VALUE; + RightMenu.popItemFocusImg_ = INIT_VALUE; + RightMenu.popItemFocusCut_ = INIT_VALUE; + this.leftRectCicleCut_ = INIT_VALUE; + this.centerRectCut_ = INIT_VALUE; + this.rightRectCicleCut_ = INIT_VALUE; + this.leftRectFocusCicleCut_ = INIT_VALUE; + this.centerFocusCut_ = INIT_VALUE; + this.rightRectFocusCicleCut_ = INIT_VALUE; + this.delay_ = 0; + this.searchBgImg_ = INIT_VALUE; + this.searchBgCut_ = INIT_VALUE; + this.upImg_ = INIT_VALUE; + this.upCut_ = INIT_VALUE; + this.downImg_ = INIT_VALUE; + this.downCut_ = INIT_VALUE; + this.closeImg_ = INIT_VALUE; + this.closeCut_ = INIT_VALUE; + this.searchImg_ = INIT_VALUE; + this.searchCut_ = INIT_VALUE; + this.isSearchResult_ = false; + this.searchRectFocusCicleImg_ = INIT_VALUE; + this.leftSearchFocusCicleCut_ = INIT_VALUE; + this.centerSearchCut_ = INIT_VALUE; + this.rightSearchFocusCicleCut_ = INIT_VALUE; + + this.searchAttrCicleImg_ = INIT_VALUE; + this.leftSearchAttrCicleCut_ = INIT_VALUE; + this.centerSearchAttrCut_ = INIT_VALUE; + this.rightSearchAttrCicleCut_ = INIT_VALUE; + } + reloadMenuBgPic() { + let bgPic = this.reloadBgPic(); + XMessage.gi().send('reloadMenuBg', { + data: bgPic, + }); + } + + reloadBgPic() { let bgPic = RightMenu.isDarkBackground_ ? 'pop_background.png' : 'pop_background_light.png'; let bgPicPath = '../images/' + bgPic; RightMenu.backgroundImg_ = XTexture.gi().loadTextureFromImage(bgPicPath); @@ -513,52 +532,50 @@ class MainEditor { RightMenu.backgroundImg_, 0, 0, - 156, - 112, - 156, - 112 + BGPIC_WIDTH, + BGPIC_HEIGHT, + BGPIC_WIDTH, + BGPIC_HEIGHT ); - this.cutImgDict_['backgroundCut'] = bgPic; - XMessage.gi().send('reloadMenuBg', { - data: bgPic, - }); + this.cutImgDict_.backgroundCut = bgPic; + return bgPic; } calcPostionY(data, y) { data.posY = y; let ty = y; switch (data.type_) { - case 1: - case 2: - case 3: - case 4: + case DataType.INT8: + case DataType.INT16: + case DataType.INT32: + case DataType.INT64: y += MainEditor.LINE_HEIGHT; break; - case 5: + case DataType.STRING: y += MainEditor.LINE_HEIGHT; break; - case 6: + case DataType.NODE: if (!data.isOpen_) { y += MainEditor.LINE_HEIGHT; } else { - for (let i in data.value_) { - y = this.calcPostionY(data.value_[i], y); - } + data.value_.forEach((item, index) => { + y = this.calcPostionY(item, y); + }); } break; - case 7: + case DataType.ATTR: y = this.calcPostionY(data.value_, y); break; - case 8: + case DataType.ARRAY: y += MainEditor.LINE_HEIGHT; break; - case 9: + case DataType.REFERENCE: y += MainEditor.LINE_HEIGHT; break; - case 10: + case DataType.DELETE: y += MainEditor.LINE_HEIGHT; break; - case 11: + case DataType.BOOL: y += MainEditor.LINE_HEIGHT; break; default: @@ -566,31 +583,31 @@ class MainEditor { break; } if (y > ty) { - data.posY = (ty + y - MainEditor.LINE_HEIGHT) / 2; + data.posY = (ty + y - MainEditor.LINE_HEIGHT) / CONSTANT_MIDDLE; } return y > ty + MainEditor.LINE_HEIGHT ? y : ty + MainEditor.LINE_HEIGHT; } getNodeText(data) { switch (data.nodeType_) { - case 0: + case NodeType.DATA: return data.name_; - case 3: + case NodeType.DELETE: return data.name_ + ' : delete'; - case 4: + case NodeType.TEMPLETE: return 'templete ' + data.name_; - case 5: - if (data.ref_ == 'unknow') { + case NodeType.INHERIT: + if (data.ref_ === 'unknow') { return data.name_; } return data.name_ + ' :: ' + data.ref_; - case 1: - if (data.ref_ == 'unknow') { + case NodeType.COPY: + if (data.ref_ === 'unknow') { return data.name_; } return data.name_ + ' : ' + data.ref_; - case 2: - if (data.ref_ == 'unknow') { + case NodeType.REFERENCE: + if (data.ref_ === 'unknow') { return data.name_; } return data.name_ + ' : &' + data.ref_; @@ -600,51 +617,57 @@ class MainEditor { } drawNode(pm2f, s, size, x, y, type, data) { - let w = pm2f.getTextWidth(type == DataType.ATTR ? s + ' = ' : s, size); - if (data.parent_ == undefined) { + const SPACE = 2; + const MAXLEN_DISPLAY_WITH_SPACE = 25; + const MAXLEN_DISPLAY_NO_SPACE = 26; + const DISPLAY_TEXT_MAX_NOPOINT = 27; + let w = pm2f.getTextWidth(type === DataType.ATTR ? s + ' = ' : s, size); + if (data.parent_ === undefined) { return w; } - if (type == DataType.ATTR) { + if (type === DataType.ATTR) { let lenDisplay = DISPLAY_TEXT_MAX - EQUAL_SIGN_LEN; - if (s.length < 25) { - pm2f.drawText(s, size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - pm2f.drawText(' = ', size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2 + pm2f.getTextWidth(s, size), - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 0, 0, 0xffa9a9a9); - } else if (s.length == 25) { - pm2f.drawText(s, size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - pm2f.drawText(' =', size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2 + pm2f.getTextWidth(s, size), - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 0, 0, 0xffa9a9a9); - } else if (s.length == 26) { - pm2f.drawText(s, size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - pm2f.drawText('=', size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2 + pm2f.getTextWidth(s, size), - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 0, 0, 0xffa9a9a9); - } else if (s.length > 26) { + let orangeColor = 0xffa9a9a9; + if (s.length < MAXLEN_DISPLAY_WITH_SPACE) { + pm2f.drawText(s, size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + pm2f.drawText(' = ', size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE + pm2f.getTextWidth(s, size), + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 0, 0, orangeColor); + } else if (s.length === MAXLEN_DISPLAY_WITH_SPACE) { + pm2f.drawText(s, size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + pm2f.drawText(' =', size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE + pm2f.getTextWidth(s, size), + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 0, 0, orangeColor); + } else if (s.length === MAXLEN_DISPLAY_NO_SPACE) { + pm2f.drawText(s, size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + pm2f.drawText('=', size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE + pm2f.getTextWidth(s, size), + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 0, 0, orangeColor); + } else if (s.length > MAXLEN_DISPLAY_NO_SPACE) { s = s.substring(0, lenDisplay) + '...'; - pm2f.drawText(s, size, x - (data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + pm2f.drawText(s, size, x - (data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0) + + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * SPACE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); } } else { - pm2f.drawText( s.length > DISPLAY_TEXT_MAX ? s.substring(0, 27) + '...' : s, size, x - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_) + - MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + let logoSizeTimes = 2; // logosize显示大小是logoSize长度的2倍 + pm2f.drawText( s.length > DISPLAY_TEXT_MAX ? s.substring(0, DISPLAY_TEXT_MAX_NOPOINT) + '...' : s, size, x - + (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_) + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE * logoSizeTimes, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); } return w; } drawBrokenLine(pm2f, data, offy, i) { let dis = - data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0; + data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0; let baseX_ = data.posX + MainEditor.NODE_RECT_WIDTH - @@ -654,27 +677,27 @@ class MainEditor { dis; pm2f.drawLine( baseX_, - offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, baseX_ + MainEditor.LINE_WIDTH, - offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, MainEditor.NODE_LINE_COLOR, 0.5 ); pm2f.drawLine( baseX_ + MainEditor.LINE_WIDTH, - offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, baseX_ + MainEditor.LINE_WIDTH, - offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, MainEditor.NODE_LINE_COLOR, 0.5 ); pm2f.drawLine( baseX_ + MainEditor.LINE_WIDTH, - offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, baseX_ + MainEditor.LINE_WIDTH * 2, - offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / 2, + offy + data.value_[i].posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE, MainEditor.NODE_LINE_COLOR, 0.5 ); @@ -683,53 +706,125 @@ class MainEditor { arrayNodeProc(w, pm2f, data, offx, offy) { let ss = '[' + data.value_.length + ']' + NodeTools.arrayToString(data); let keyAndValue = data.parent_.name_ + ' = '; - if (keyAndValue.length >= 30) { + + if (keyAndValue.length >= KEY_VALUE_MAX) { return; - } else if (keyAndValue.length == 29) { - w = pm2f.drawText('.', 14, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - } else if (keyAndValue.length == 28) { - w = pm2f.drawText('..', 14, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - } else if (keyAndValue.length == 27) { - w = pm2f.drawText('...', 14, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - } else if (keyAndValue.length < 27) { + } else if (keyAndValue.length === ONE_KEY_VALUE_MAX) { + w = pm2f.drawText('.', MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - + MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } else if (keyAndValue.length === TWO_KEY_VALUE_MAX) { + w = pm2f.drawText('..', MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - + MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } else if (keyAndValue.length === THREE_KEY_VALUE_MAX) { + w = pm2f.drawText('...', MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - + MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } else if (keyAndValue.length < THREE_KEY_VALUE_MAX) { let displayValueLen = DISPLAY_TEXT_MAX - keyAndValue.length; if (ss.length > displayValueLen) { ss = ss.substring(0, displayValueLen - 3) + '...'; } - w = pm2f.drawText(ss, 14, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + w = pm2f.drawText(ss, MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - + MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); } } configNodeProc(w, pm2f, data, offx, offy, path) { - let dis = data.parent_ != undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0; + let dis = data.parent_ !== undefined ? MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_ : 0; this.setNodeButton(pm2f, offx, offy + data.posY, w, MainEditor.NODE_TEXT_SIZE, path, data); if (data.value_.length > 0) { this.setNodeMoreButton(pm2f, offx - dis, offy + data.posY, MainEditor.NODE_MORE_CHILD, MainEditor.NODE_MORE_CHILD, data); } let drawNodeX_ = offx + MainEditor.NODE_RECT_WIDTH + MainEditor.NODE_SIZE_BG_OFFX + MainEditor.NODE_MORE_CHILD + MainEditor.LINE_WIDTH * 2 - dis; - if (data.type_ == DataType.NODE) { - for (let i in data.value_) { - if ( - data.value_[i].parent_.type_ == 6 && - data.value_[i].parent_.isOpen_ - ) { - this.drawObj(pm2f, data.value_[i], drawNodeX_, offy, path + '.'); - this.drawBrokenLine(pm2f, data, offy, i); - } else if (data.value_[i].parent_.type_ == DataType.ATTR) { - this.drawObj(pm2f, data.value_[i], drawNodeX_, offy, path + '.'); + if (data.type_ === DataType.NODE) { + data.value_.forEach((item, index) => { + if (item.parent_.type_ === DataType.NODE && item.parent_.isOpen_) { + this.drawObj(pm2f, item, drawNodeX_, offy, path + '.'); + this.drawBrokenLine(pm2f, data, offy, index); + } else if (item.parent_.type_ === DataType.ATTR) { + this.drawObj(pm2f, item, drawNodeX_, offy, path + '.'); pm2f.drawLine(data.posX + w, offy + data.posY + 10, - data.value_[i].posX, offy + data.value_[i].posY + 10, MainEditor.NODE_TEXT_COLOR, 1); + item.posX, offy + item.posY + 10, MainEditor.NODE_TEXT_COLOR, 1); } else { NapiLog.logInfo('Node collapse does not need to draw child node'); } - } + }); } else { - for (let i in data.value_) { - this.drawObj(pm2f, data.value_[i], drawNodeX_, offy, path + '.'); + data.value_.forEach((item, index) => { + this.drawObj(pm2f, item, drawNodeX_, offy, path + '.'); pm2f.drawLine(data.posX + w, offy + data.posY + 10, - data.value_[i].posX, offy + data.value_[i].posY + 10, MainEditor.NODE_TEXT_COLOR, 1); - } + item.posX, offy + item.posY + 10, MainEditor.NODE_TEXT_COLOR, 1); + }); + } + } + + /** + * 绘制Attr对象 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} offx x偏移值 + * @param {} offy y偏移值 + * @param {} path 节点路径 + */ + drawAttrObj(pm2f, data, offx, offy, path) { + let w = this.drawNode(pm2f, data.name_, MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY, data.type_, data); + this.setNodeButton(pm2f, offx, offy + data.posY, w, MainEditor.NODE_TEXT_SIZE, path, data); + this.drawObj(pm2f, data.value_, offx + w, offy, path); + pm2f.drawCut(this.attrIconCut_, offx + MainEditor.LOGO_LEFT_PADDING - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_), + offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.LOGO_SIZE / CONSTANT_MIDDLE); + } + + /** + * 绘制Node对象 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} offx x偏移值 + * @param {} offy y偏移值 + * @param {} path 节点路径 + */ + drawNodeObj(pm2f, data, offx, offy, path) { + let w = this.drawNode(pm2f, this.getNodeText(data), MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY, data.type_, data); + this.configNodeProc(w, pm2f, data, offx, offy, path); + if (data.parent_ !== undefined) { + pm2f.drawCut(this.nodeIconCut_, offx + MainEditor.LOGO_LEFT_PADDING - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_), + offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - MainEditor.LOGO_SIZE / CONSTANT_MIDDLE); + } + } + + /** + * 绘制引用对象 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} drawTextX_ x偏移值 + * @param {} drawTextY_ y偏移值 + */ + drawReferenceObj(pm2f, data, drawTextX_, drawTextY_) { + let content = data.parent_.name_ + ' = '; + if (content.length > DISPLAY_TEXT_MAX) { + content = ''; + } else if ((content + data.value_).length > DISPLAY_TEXT_MAX) { + content = data.value_.substring((data.parent_.name_ + ' = ').length, THREE_KEY_VALUE_MAX) + '...'; + } else { + content = data.value_; + } + pm2f.drawText('&' + content, MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, + 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } + + /** + * 绘制引用对象 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} drawTextX_ x偏移值 + * @param {} drawTextY_ y偏移值 + */ + drawStringObj(pm2f, data, drawTextX_, drawTextY_) { + let value = data.value_; + let keyAndValue = data.parent_.name_ + ' = ' + data.value_; + if (keyAndValue.length > DISPLAY_TEXT_MAX) { + value = keyAndValue.substring((data.parent_.name_ + ' = ').length, THREE_KEY_VALUE_MAX) + '...'; } + let w = pm2f.drawText('"' + value + '"', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, + 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); } drawObj(pm2f, data, offx, offy, path) { @@ -741,73 +836,76 @@ class MainEditor { } let parentTextWidth = pm2f.getTextWidth(' = ', MainEditor.NODE_TEXT_SIZE); let drawTextX_ = offx + MainEditor.LOGO_LEFT_PADDING + MainEditor.LOGO_SIZE + parentTextWidth; - let drawTextY_ = offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.NODE_TEXT_SIZE / 2; + let drawTextY_ = offy + data.posY + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - + MainEditor.NODE_TEXT_SIZE / CONSTANT_MIDDLE; switch (data.type_) { - case 1: - case 2: - case 3: - case 4: + case DataType.INT8: + case DataType.INT16: + case DataType.INT32: + case DataType.INT64: w = pm2f.drawText(NodeTools.jinZhi10ToX(data.value_, data.jinzhi_), MainEditor.NODE_TEXT_SIZE, - drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), + drawTextY_, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); break; - case 5: - let value = data.value_; - let keyAndValue = data.parent_.name_ + ' = ' + data.value_; - if (keyAndValue.length > DISPLAY_TEXT_MAX) { - value = keyAndValue.substring((data.parent_.name_ + ' = ').length, 27) + '...'; - } - w = pm2f.drawText('"' + value + '"', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, - 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + case DataType.STRING: + this.drawStringObj(pm2f, data, drawTextX_, drawTextY_); break; - case 6: - w = this.drawNode(pm2f, this.getNodeText(data), MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY, data.type_, data); - this.configNodeProc(w, pm2f, data, offx, offy, path); - if (data.parent_ != undefined) { - pm2f.drawCut(this.nodeIconCut_, offx + MainEditor.LOGO_LEFT_PADDING - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_), - offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.LOGO_SIZE / 2); - } + case DataType.NODE: + this.drawNodeObj(pm2f, data, offx, offy, path); break; - case 7: - w = this.drawNode(pm2f, data.name_, MainEditor.NODE_TEXT_SIZE, offx, offy + data.posY, data.type_, data); - this.setNodeButton(pm2f, offx, offy + data.posY, w, MainEditor.NODE_TEXT_SIZE, path, data); - this.drawObj(pm2f, data.value_, offx + w, offy, path); - pm2f.drawCut(this.attrIconCut_, offx + MainEditor.LOGO_LEFT_PADDING - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_), - offy + data.posY + MainEditor.NODE_RECT_HEIGHT / 2 - MainEditor.LOGO_SIZE / 2); + case DataType.ATTR: + this.drawAttrObj(pm2f, data, offx, offy, path); break; case 8: this.arrayNodeProc(w, pm2f, data, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), offy); break; - case 9: - let content = data.parent_.name_ + ' = '; - if (content.length > DISPLAY_TEXT_MAX) { - content = ''; - } else if ((content + data.value_).length > DISPLAY_TEXT_MAX) { - content = data.value_.substring((data.parent_.name_ + ' = ').length, 27) + '...'; - } else { - content = data.value_; - } - w = pm2f.drawText('&' + content, MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, - 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + case DataType.REFERENCE: + this.drawReferenceObj(pm2f, data, drawTextX_, drawTextY_); break; - case 10: + case DataType.DELETE: w = pm2f.drawText('delete', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); break; - case 11: - if (data.value_) { - w = pm2f.drawText('true', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, - 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - } else { - w = pm2f.drawText('false', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, - 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); - } + case DataType.BOOL: + this.drawBoolObj(pm2f, data, drawTextX_, drawTextY_); break; default: NapiLog.logError('unknow' + data.type_); break; } - if (data.errMsg_ != null) { - if (parseInt(this.delay_ / 10) % 2 == 0) { + this.drawErrorRect(pm2f, data, offx, offy); + } + + /** + * 绘制Bool对象 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} drawTextX_ x偏移值 + * @param {} drawTextY_ y偏移值 + */ + drawBoolObj(pm2f, data, drawTextX_, drawTextY_) { + let w; + if (data.value_) { + w = pm2f.drawText('true', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, + 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } else { + w = pm2f.drawText('false', MainEditor.NODE_TEXT_SIZE, drawTextX_ - (MainEditor.NODE_RECT_WIDTH - data.parent_.parent_.nodeWidth_), drawTextY_, + 1, 1, 0, 1, 1, MainEditor.NODE_TEXT_COLOR); + } + } + + /** + * 绘制错误显示框 + * @param {} pm2f X2DFast + * @param {} data 节点数据对象 + * @param {} offx x偏移值 + * @param {} offy y偏移值 + */ + drawErrorRect(pm2f, data, offx, offy) { + if (data.errMsg_ !== null && data.errMsg_ !== undefined) { + let displayFreq = 2; // 显示频率 + let frameNo = 10; + if (parseInt(this.delay_ / frameNo) % displayFreq === 0) { pm2f.drawRect(offx - (MainEditor.NODE_RECT_WIDTH - data.parent_.nodeWidth_), offy + data.posY, data.nodeWidth_, MainEditor.NODE_RECT_HEIGHT, 0xffff0000, 1); } @@ -816,86 +914,118 @@ class MainEditor { } } + /** + * 获取绘制框宽度 + * @param {} pm2f X2DFast + * @param {} node 节点数据对象 + * @return {} rectWidth 绘制框宽度 + */ + getRectWidth(pm2f, node) { + let displayValue; + let rectWidth = 0; + if (node.value_.type_ === ObjectType.PARSEROP_ARRAY) { + let arrayValue = NodeTools.arrayToString(node.value_); + displayValue = '[' + node.value_.value_.length + ']' + arrayValue; + } else if ( + node.value_.type_ === ObjectType.PARSEROP_UINT8 || + node.value_.type_ === ObjectType.PARSEROP_UINT16 || + node.value_.type_ === ObjectType.PARSEROP_UINT32 || + node.value_.type_ === ObjectType.PARSEROP_UINT64 + ) { + displayValue = NodeTools.jinZhi10ToX( + node.value_.value_, + node.value_.jinzhi_ + ); + } else if (node.value_.type_ === ObjectType.PARSEROP_DELETE) { + displayValue = 'delete'; + } else if (node.value_.type_ === ObjectType.PARSEROP_BOOL) { + if (node.value_) { + displayValue = 'true'; + } else { + displayValue = 'false'; + } + } else { + displayValue = node.value_.value_; + } + + let keyAndValue; + let lenDisplay = THREE_KEY_VALUE_MAX; + let moreLenDisplayOne = 1; + let moreLenDisplayTwo = 2; + if (node.name_.length <= lenDisplay) { + keyAndValue = node.name_ + ' = ' + displayValue; + } else if (node.name_.length === lenDisplay + moreLenDisplayOne) { + keyAndValue = node.name_ + ' ='; + } else if (node.name_.length === lenDisplay + moreLenDisplayTwo) { + keyAndValue = node.name_ + '='; + } else if (node.name_.length >= DISPLAY_TEXT_MAX) { + keyAndValue = node.name_; + } + + if (keyAndValue.length >= DISPLAY_TEXT_MAX) { + keyAndValue = keyAndValue.substring(0, THREE_KEY_VALUE_MAX) + '...'; + } + rectWidth = pm2f.getTextWidth(keyAndValue, MainEditor.NODE_TEXT_SIZE); + return rectWidth; + } + + /** + * 绘制节点名称 + * @param {} pm2f X2DFast + * @param {} node 节点数据对象 + * @param {} x x坐标值 + * @param {} y y坐标值 + * @param {} w 宽度 + * @param {} h 高度 + */ + drawNodeNameText(pm2f, node, x, y, w, h) { + pm2f.drawText( + node.name_, + MainEditor.NODE_TEXT_SIZE, + x + MainEditor.NODE_RECT_WIDTH / CONSTANT_MIDDLE - w / CONSTANT_MIDDLE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - h / CONSTANT_MIDDLE, + 1, + 1, + 0, + 1, + 1, + MainEditor.NODE_TEXT_COLOR + ); + } + setNodeButton(pm2f, x, y, w, h, path, node) { let rectWidth = MainEditor.NODE_RECT_WIDTH; - if (node.parent_ == undefined) { - if (this.nodePoint_ == node) { + if (node.parent_ === undefined) { + if (this.nodePoint_ === node) { pm2f.drawCut(this.rootIconFocusCut_, x, y); } else { pm2f.drawCut(this.rootIconCut_, x, y); } node.nodeWidth_ = MainEditor.NODE_RECT_WIDTH; - pm2f.drawText( - node.name_, - MainEditor.NODE_TEXT_SIZE, - x + MainEditor.NODE_RECT_WIDTH / 2 - w / 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - h / 2, - 1, - 1, - 0, - 1, - 1, - MainEditor.NODE_TEXT_COLOR - ); + this.drawNodeNameText(pm2f, node, x, y, w, h); } else { - if (node.type_ == DataType.ATTR) { - let displayValue; - if (node.value_.type_ == ObjectType.PARSEROP_ARRAY) { - let arrayValue = NodeTools.arrayToString(node.value_); - displayValue = '[' + node.value_.value_.length + ']' + arrayValue; - } else if ( - node.value_.type_ == ObjectType.PARSEROP_UINT8 || - node.value_.type_ == ObjectType.PARSEROP_UINT16 || - node.value_.type_ == ObjectType.PARSEROP_UINT32 || - node.value_.type_ == ObjectType.PARSEROP_UINT64 - ) { - displayValue = NodeTools.jinZhi10ToX( - node.value_.value_, - node.value_.jinzhi_ - ); - } else if (node.value_.type_ == ObjectType.PARSEROP_DELETE) { - displayValue = 'delete'; - } else if (node.value_.type_ == ObjectType.PARSEROP_BOOL) { - if (node.value_) { - displayValue = 'true'; - } else { - displayValue = 'false'; - } - } else { - displayValue = node.value_.value_; - } - - let keyAndValue; - let lenDisplay = 27; - if (node.name_.length <= lenDisplay) { - keyAndValue = node.name_ + ' = ' + displayValue; - } else if (node.name_.length == lenDisplay + 1) { - keyAndValue = node.name_ + ' ='; - } else if (node.name_.length == lenDisplay + 2) { - keyAndValue = node.name_ + '='; - } else if (node.name_.length >= DISPLAY_TEXT_MAX) { - keyAndValue = node.name_; - } - - if (keyAndValue.length >= DISPLAY_TEXT_MAX) { - keyAndValue = keyAndValue.substring(0, 27) + '...'; - } - rectWidth = pm2f.getTextWidth(keyAndValue, MainEditor.NODE_TEXT_SIZE); + if (node.type_ === DataType.ATTR) { + rectWidth = this.getRectWidth(pm2f, node); } else { rectWidth = pm2f.getTextWidth( - this.getNodeText(node).length > DISPLAY_TEXT_MAX ? this.getNodeText(node).substring(0, 27) + '...' : this.getNodeText(node), + this.getNodeText(node).length > DISPLAY_TEXT_MAX ? this.getNodeText(node).substring(0, THREE_KEY_VALUE_MAX) + '...' : this.getNodeText(node), MainEditor.NODE_TEXT_SIZE ); } this.drawNodeRectButton(pm2f, x, y, rectWidth, node); } + if (this.nodeBtnPoint_ >= this.nodeBtns.length) { this.nodeBtns.push(new XButton()); } let pbtn = this.nodeBtns[this.nodeBtnPoint_]; + let singleOffset = 6; + let numberOffset = 2; + let widthOffset = singleOffset * numberOffset; + let logoSizeOffset = 8; pbtn.move( - x - (node.parent_ == undefined ? 0 : MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), - y, node.parent_ == undefined ? MainEditor.NODE_RECT_WIDTH : rectWidth + 6 * 2 + MainEditor.LOGO_SIZE + 8, MainEditor.NODE_RECT_HEIGHT + x - (node.parent_ === undefined ? 0 : MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), + y, node.parent_ === undefined ? MainEditor.NODE_RECT_WIDTH : rectWidth + widthOffset + MainEditor.LOGO_SIZE + logoSizeOffset, MainEditor.NODE_RECT_HEIGHT ); pbtn.name_ = path; pbtn.node_ = node; @@ -903,14 +1033,18 @@ class MainEditor { } drawNodeRectButton(pm2f, x, y, rectWidth, node) { - let width = rectWidth + 6 * 2 + MainEditor.LOGO_SIZE + 8; - if (node.type_ == DataType.ATTR) { + let singleOffset = 6; + let numberOffset = 2; + let widthOffset = singleOffset * numberOffset; + let logoSizeOffset = 8; + let width = rectWidth + widthOffset + MainEditor.LOGO_SIZE + logoSizeOffset; + if (node.type_ === DataType.ATTR) { switch (node.value_.type_) { - case 1: - case 2: - case 3: - case 4: - case 8: + case ObjectType.PARSEROP_UINT8: + case ObjectType.PARSEROP_UINT16: + case ObjectType.PARSEROP_UINT32: + case ObjectType.PARSEROP_UINT64: + case ObjectType.PARSEROP_ARRAY: width = width; break; default: @@ -918,7 +1052,7 @@ class MainEditor { break; } } - if (this.nodePoint_ == node) { + if (this.nodePoint_ === node) { if (this.isSearchResult_) { pm2f.drawCut(this.leftSearchAttrCicleCut_, x - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y); pm2f.drawCut(this.centerSearchAttrCut_, x + 8 - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y, width / 116); @@ -929,7 +1063,7 @@ class MainEditor { pm2f.drawCut(this.rightRectFocusCicleCut_, x + 8 + width - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y); } } else { - if (this.searchKey != null && node.name_.indexOf(this.searchKey) > -1 && this.isSearchResult_) { + if (this.searchKey !== null && node.name_.indexOf(this.searchKey) > -1 && this.isSearchResult_) { pm2f.drawCut( this.leftSearchFocusCicleCut_, x - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y); pm2f.drawCut(this.centerSearchCut_, x + 8 - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y, width / 116); pm2f.drawCut( this.rightSearchFocusCicleCut_, x + 8 + width - (MainEditor.NODE_RECT_WIDTH - node.parent_.nodeWidth_), y); @@ -959,117 +1093,273 @@ class MainEditor { this.nodeMoreBtns.push(new XButton()); } let pbtn = this.nodeMoreBtns[this.nodeMoreBtnPoint_]; - if (node.parent_ == undefined) { + if (node.parent_ === undefined) { pbtn.move(x + MainEditor.NODE_RECT_WIDTH + MainEditor.NODE_SIZE_BG_OFFX, - y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / 2, w, h); + y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / CONSTANT_MIDDLE, w, h); } else { if (node.isOpen_) { pbtn.move(x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX, - y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / 2, w, h); + y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / CONSTANT_MIDDLE, w, h); } else { pbtn.move(x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX, - y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / 2, w, h); + y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / CONSTANT_MIDDLE, w, h); } } if (node.isOpen_) { pm2f.drawCut(this.circleOpenCut_, x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX, - y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / 2); + y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / CONSTANT_MIDDLE); } else { + let c = 0xffffffff; + let oy = 1; + let ox = 1; + let ra = 0; + let sh = 1; + let sw = 1; + let yOffset = 4; + let textSize = 10; pm2f.drawCut(this.circleCut_, x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX, - y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / 2); + y + (MainEditor.NODE_RECT_HEIGHT - MainEditor.NODE_MORE_CHILD) / CONSTANT_MIDDLE); let textWidth = pm2f.getTextWidth(node.value_.length, 10); - pm2f.drawText(node.value_.length, 10, x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX + MainEditor.NODE_MORE_CHILD / 2 - textWidth / 2, - y + MainEditor.NODE_RECT_HEIGHT / 2 - 4, 1, 1, 0, 1, 1, 0xffffffff); + pm2f.drawText(node.value_.length, textSize, x + node.nodeWidth_ + MainEditor.NODE_SIZE_BG_OFFX + + MainEditor.NODE_MORE_CHILD / CONSTANT_MIDDLE - textWidth / CONSTANT_MIDDLE, + y + MainEditor.NODE_RECT_HEIGHT / CONSTANT_MIDDLE - yOffset, sw, sh, ra, ox, oy, c); } pbtn.node_ = node; this.nodeMoreBtnPoint_ += 1; } - draw(pm2f) { - getVsCodeTheme(); - pm2f.fillRect(0, 0, Scr.logicw, Scr.logich, MainEditor.CANVAS_BG); - if (this.filePoint_ != null && this.filePoint_ in this.files_) { - let data = this.files_[this.filePoint_]; - this.calcPostionY(data, 0); - if (this.modifyPos_) { - this.offX_ -= this.modifyPos_.node.posX - this.modifyPos_.x; - this.offY_ -= this.modifyPos_.node.posY - this.modifyPos_.y; - this.modifyPos_ = null; - } else if (this.isFirstDraw) { - this.offX_ = 0; - this.offY_ = -data.posY + Scr.logich / 2; - this.maxX = 0; - this.drawObj(pm2f, data, this.offX_, this.offY_, ''); - pm2f.fillRect(0, 0, Scr.logicw, Scr.logich, MainEditor.CANVAS_BG); - this.offX_ = (Scr.logicw - this.maxX) / 2; - this.isFirstDraw = false; - } - this.nodeBtnPoint_ = 0; - this.nodeMoreBtnPoint_ = 0; - this.drawObj(pm2f, data, this.offX_, this.offY_, ''); - } - pm2f.fillRect(0, 0, window.innerWidth, 4, MainEditor.CANVAS_LINE); + /** + * 移动绘制 + * @param {} xOffset x偏移值 + */ + moveAndDraw(xOffset) { + let x = 16; + let y = 20; + let w = window.innerWidth - xOffset - DRAW_HEIGHT - x; + let h = 20; + this.sltInclude.move(x, y, w, h).draw(); + } + + /** + * 绘制Rect + * @param {} pm2f X2DFast + * @param {*} xx 起始x坐标 + * @param {*} yy 起始y坐标 + * @param {*} xOffset x偏移值 + */ + fillWholeRect(pm2f, xx, yy, xOffset) { + pm2f.fillRect(xx, yy, window.innerWidth, DRAW_HEIGHT, MainEditor.CANVAS_LINE); pm2f.fillRect( - window.innerWidth - 420 - 4, + window.innerWidth - xOffset - DRAW_HEIGHT, 0, - 4, + DRAW_HEIGHT, window.innerHeight, MainEditor.CANVAS_LINE ); - pm2f.fillRect(0, 4, window.innerWidth - 420 - 4, 48, MainEditor.CANVAS_BG); + yy = 4; + let wSpace = 4; + let h = 48; + pm2f.fillRect(xx, yy, window.innerWidth - xOffset - wSpace, h, MainEditor.CANVAS_BG); + yy = 52; pm2f.fillRect( - 0, - 52, - window.innerWidth - 420 - 4, - 4, + xx, + yy, + window.innerWidth - xOffset - DRAW_HEIGHT, + DRAW_HEIGHT, MainEditor.CANVAS_LINE ); + } + + /** + * 修改节点位置 + */ + subFuncModify() { + this.offX_ -= this.modifyPos_.node.posX - this.modifyPos_.x; + this.offY_ -= this.modifyPos_.node.posY - this.modifyPos_.y; + this.modifyPos_ = null; + } + + /** + * 绘制Rect + * @param {} pm2f X2DFast + * @param {*} x 起始x坐标 + * @param {*} y 起始y坐标 + * @param {*} data 绘制的数据对象 + */ + subFuncFirstDraw(pm2f, x, y, data) { + this.offX_ = 0; + this.offY_ = -data.posY + Scr.logich / CONSTANT_MIDDLE; + this.maxX = 0; + this.drawObj(pm2f, data, this.offX_, this.offY_, ''); + pm2f.fillRect(x, y, Scr.logicw, Scr.logich, MainEditor.CANVAS_BG); + this.offX_ = (Scr.logicw - this.maxX) / CONSTANT_MIDDLE; + this.isFirstDraw = false; + } + + /** + * 绘制接口 + * @param {} pm2f X2DFast + * @param {*} xx 起始x坐标 + * @param {*} yy 起始y坐标 + */ + subFuncDraw(pm2f, xx, yy) { + let data = this.files_[this.filePoint_]; + this.calcPostionY(data, 0); + if (this.modifyPos_) { + this.subFuncModify(); + } else if (this.isFirstDraw) { + this.subFuncFirstDraw(pm2f, xx, yy, data); + } + this.nodeBtnPoint_ = 0; + this.nodeMoreBtnPoint_ = 0; + this.drawObj(pm2f, data, this.offX_, this.offY_, ''); + } + + /** + * 绘制选择文本 + * @param {} pm2f X2DFast + */ + drawSelectText(pm2f) { + let drawTextName = '点击选择目标'; + this.callDrawText(pm2f, drawTextName); + this.btnCancelSelect_.name_ = '取消选择'; + } + + callDrawText(pm2f, drawTextName) { + pm2f.drawText(drawTextName, MainEditor.NODE_TEXT_SIZE, this.mousePos_.x, + this.mousePos_.y, 1, 1, 0, DRAWTEXT_OFFSETX, DRAWTEXT_OFFSETY, MainEditor.NODE_TEXT_COLOR); + } + + /** + * 绘制复制文本 + * @param {} pm2f X2DFast + */ + drawCopyText(pm2f) { + let drawTextName = '已复制' + this.selectNode_.pnode.name_; + this.callDrawText(pm2f, drawTextName); + this.btnCancelSelect_.name_ = '取消复制'; + } + + /** + * 绘制剪切文本 + * @param {} pm2f X2DFast + * @param {*} xx 起始x坐标 + * @param {*} yy 起始y坐标 + */ + drawCutText(pm2f) { + pm2f.drawText( + '已剪切' + this.selectNode_.pnode.name_, + 18, + this.mousePos_.x, + this.mousePos_.y, + 1, + 1, + 0, + -3, + -3, + MainEditor.NODE_TEXT_COLOR + ); + this.btnCancelSelect_.name_ = '取消剪切'; + } + + /** + * 绘制错误信息文本 + * @param {} pm2f X2DFast + * @param {*} xx 起始x坐标 + * @param {*} yy 起始y坐标 + */ + drawErrorText(pm2f, a, y) { + a = a << 24; + pm2f.fillRect(0, y, Scr.logicw, 20, 0xff0000 | a); + pm2f.drawText( + this.errorMsg_[i][1], + MainEditor.NODE_TEXT_SIZE, + Scr.logicw / CONSTANT_MIDDLE, + y, + 1, + 1, + 0, + -2, + -1, + MainEditor.NODE_TEXT_COLOR + ); + } + + /** + * 绘制一组剪切文本 + * @param {} pm2f X2DFast + * @param {*} xx 起始x坐标 + * @param {*} yy 起始y坐标 + */ + drawCuts(pm2f, x, y) { + let xOffset = 28; + let yDoubleOffset = 56; + let ySpace = 8; + pm2f.drawCut(this.searchBgCut_, x, y); + pm2f.drawCut(this.searchCut_, x + xOffset, y + yDoubleOffset / CONSTANT_MIDDLE - ySpace); + x = x + 16 + 290 + 16; + + let searchResultTxt = + this.searchInput.result.length === 0 ? 'No result' : this.searchInput.point + 1 + '/' + this.searchInput.result.length; + let color = 0xffffffff; + let offsetY = -2; + let offsetX = -1; + let ra = 0; + let sh = 1; + let sw = 1; + let yOffsetBase = 56; + let yOffset = 3; + let xStep = 16; + let yRightSpace = 8; + let start = 74; + + x += pm2f.drawText( + searchResultTxt, + MainEditor.NODE_TEXT_SIZE, + x, + y + yOffsetBase / CONSTANT_MIDDLE + yOffset, + sw, + sh, + ra, + offsetX, + offsetY, + color + ); + x += start - pm2f.getTextWidth(searchResultTxt, MainEditor.NODE_TEXT_SIZE); + pm2f.drawCut(this.upCut_, x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace); + this.searchInput.btnUp.move(x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace, xStep, xStep); + x += xStep + xStep; + pm2f.drawCut(this.downCut_, x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace); + this.searchInput.btnDown.move(x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace, xStep, xStep); + x += xStep + xStep; + pm2f.drawCut(this.closeCut_, x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace); + this.searchInput.btnClose.move(x, y + yOffsetBase / CONSTANT_MIDDLE - yRightSpace, xStep, xStep); + } + + /** + * MainEditor绘制 + * @param {} pm2f X2DFast + */ + draw(pm2f) { + let xx = 0; + let yy = 0; + getVsCodeTheme(); + pm2f.fillRect(xx, yy, Scr.logicw, Scr.logich, MainEditor.CANVAS_BG); + if (this.filePoint_ !== null && this.filePoint_ in this.files_) { + this.subFuncDraw(pm2f, xx, yy); + } + let xOffset = 420; + this.fillWholeRect(pm2f, xx, yy, xOffset); this.sltInclude.setColor(MainEditor.CANVAS_BG, MainEditor.NODE_TEXT_COLOR); - this.sltInclude.move(16, 20, window.innerWidth - 420 - 4 - 16, 20).draw(); - - if (this.selectNode_.type != null) { - if (this.selectNode_.type == 'change_target') { - pm2f.drawText( - '点击选择目标', - 14, - this.mousePos_.x, - this.mousePos_.y, - 1, - 1, - 0, - -3, - -3, - MainEditor.NODE_TEXT_COLOR - ); - this.btnCancelSelect_.name_ = '取消选择'; - } else if (this.selectNode_.type == 'copy_node') { - pm2f.drawText( - '已复制' + this.selectNode_.pnode.name_, - 14, - this.mousePos_.x, - this.mousePos_.y, - 1, - 1, - 0, - -3, - -3, - MainEditor.NODE_TEXT_COLOR - ); - this.btnCancelSelect_.name_ = '取消复制'; - } else if (this.selectNode_.type == 'cut_node') { - pm2f.drawText( - '已剪切' + this.selectNode_.pnode.name_, - 18, - this.mousePos_.x, - this.mousePos_.y, - 1, - 1, - 0, - -3, - -3, - MainEditor.NODE_TEXT_COLOR - ); - this.btnCancelSelect_.name_ = '取消剪切'; + this.moveAndDraw(xOffset); + + if (this.selectNode_.type !== null) { + if (this.selectNode_.type === 'change_target') { + this.drawSelectText(pm2f); + } else if (this.selectNode_.type === 'copy_node') { + this.drawCopyText(pm2f); + } else if (this.selectNode_.type === 'cut_node') { + this.drawCutText(pm2f); } this.btnCancelSelect_.move(Scr.logicw - 250, Scr.logich - 30, 100, 20); } @@ -1079,92 +1369,52 @@ class MainEditor { while (this.errorMsg_.length > 0 && this.errorMsg_[0][0] < ts) { this.errorMsg_.shift(); } - for (let i in this.errorMsg_) { - let y = Scr.logich / 2 - this.errorMsg_.length * 20 + i * 20; - let a = parseInt((this.errorMsg_[i][0] - ts) / 2); - if (a > 255) { - a = 255; + + this.errorMsg_.forEach((item, index) => { + let sizeNumber = 20; + let y = Scr.logich / CONSTANT_MIDDLE - this.errorMsg_.length * sizeNumber + i * sizeNumber; + let a = parseInt((item[0] - ts) / CONSTANT_MIDDLE); + if (a > MAX_RANDOM) { + a = MAX_RANDOM; } NapiLog.logError(a); - a = a << 24; - pm2f.fillRect(0, y, Scr.logicw, 20, 0xff0000 | a); - pm2f.drawText( - this.errorMsg_[i][1], - 14, - Scr.logicw / 2, - y, - 1, - 1, - 0, - -2, - -1, - MainEditor.NODE_TEXT_COLOR - ); - } + this.drawErrorText(pm2f, a, y); + }); } + this.delay_ += 1; RightMenu.Draw(); if (this.searchInput) { let x = this.searchInput.pos[0]; let y = this.searchInput.pos[1]; - let w = this.searchInput.pos[2]; - let h = this.searchInput.pos[3]; - pm2f.drawCut(this.searchBgCut_, x, y); - pm2f.drawCut(this.searchCut_, x + 28, y + 56 / 2 - 8); - x = x + 16 + 290 + 16; - - let searchResultTxt = - this.searchInput.result.length == 0 ? 'No result' : this.searchInput.point + 1 + '/' + this.searchInput.result.length; - x += pm2f.drawText( - searchResultTxt, - MainEditor.NODE_TEXT_SIZE, - x, - y + 56 / 2 + 3, - 1, - 1, - 0, - -1, - -2, - 0xffffffff - ); - x += 74 - pm2f.getTextWidth(searchResultTxt, MainEditor.NODE_TEXT_SIZE); - pm2f.drawCut(this.upCut_, x, y + 56 / 2 - 8); - this.searchInput.btnUp.move(x, y + 56 / 2 - 8, 16, 16); - x += 16 + 16; - pm2f.drawCut(this.downCut_, x, y + 56 / 2 - 8); - this.searchInput.btnDown.move(x, y + 56 / 2 - 8, 16, 16); - x += 16 + 16; - pm2f.drawCut(this.closeCut_, x, y + 56 / 2 - 8); - this.searchInput.btnClose.move(x, y + 56 / 2 - 8, 16, 16); + this.drawCuts(pm2f, x, y); } this.procAll(); } - + buttonClickedProc(nodeBtns) { if ( - this.selectNode_.type == null || - this.selectNode_.type == 'copy_node' || - this.selectNode_.type == 'cut_node' - ) { + this.selectNode_.type === null || this.selectNode_.type === 'copy_node' || + this.selectNode_.type === 'cut_node') { this.nodePoint_ = nodeBtns.node_; AttrEditor.gi().freshEditor(this.filePoint_, this.nodePoint_); return true; } - if (this.selectNode_.type == 'change_target') { + if (this.selectNode_.type === 'change_target') { let pn = nodeBtns.node_; - if (pn.type_ == DataType.NODE) { - if (this.selectNode_.pnode.type_ == DataType.NODE) { + if (pn.type_ === DataType.NODE) { + if (this.selectNode_.pnode.type_ === DataType.NODE) { if ( - NodeTools.getPathByNode(this.selectNode_.pnode.parent_) == + NodeTools.getPathByNode(this.selectNode_.pnode.parent_) === NodeTools.getPathByNode(pn.parent_) ) { this.selectNode_.pnode.ref_ = pn.name_; } else { this.selectNode_.pnode.ref_ = NodeTools.getPathByNode(pn); } - } else if (this.selectNode_.pnode.type_ == DataType.REFERENCE) { + } else if (this.selectNode_.pnode.type_ === DataType.REFERENCE) { if ( - NodeTools.getPathByNode(this.selectNode_.pnode.parent_.parent_) == + NodeTools.getPathByNode(this.selectNode_.pnode.parent_.parent_) === NodeTools.getPathByNode(pn.parent_) ) { this.selectNode_.pnode.value_ = pn.name_; @@ -1184,18 +1434,20 @@ class MainEditor { } dropAllLocked(msg, x, y) { - if (msg == 2) { + if (msg === MouseType.MOVE) { this.offX_ += x - this.dropAll_.oldx; this.offY_ += y - this.dropAll_.oldy; this.dropAll_.oldx = x; this.dropAll_.oldy = y; } - if (msg == 3) { + if (msg === MouseType.UP) { this.dropAll_.locked = false; } } procTouch(msg, x, y) { + const ADD = 6; + const DELETE = 7; if (this.searchInput) { if (XTools.InRect(x, y, ...this.searchInput.pos)) { if (this.searchInput.btnUp.procTouch(msg, x, y)) { @@ -1218,7 +1470,7 @@ class MainEditor { } return true; } else { - if (msg == 1) { + if (msg === MouseType.DOWN) { this.searchInput = null; this.isSearchResult_ = false; } @@ -1240,7 +1492,7 @@ class MainEditor { return true; } - if (this.selectNode_.type != null) { + if (this.selectNode_.type !== null) { if (this.btnCancelSelect_.procTouch(msg, x, y)) { if (this.btnCancelSelect_.isClicked()) { this.selectNode_.type = null; @@ -1249,7 +1501,7 @@ class MainEditor { } } - for (let i = 0; i < this.nodeBtnPoint_; i++) { + for (let i = 0; i < this.nodeBtns.length; i++) { if (this.nodeBtns[i].procTouch(msg, x, y)) { let nodeBtns = this.nodeBtns[i]; if (nodeBtns.isClicked()) { @@ -1257,7 +1509,7 @@ class MainEditor { } else if (nodeBtns.isRightClicked()) { this.onAttributeChange('change_current_select', nodeBtns.node_); switch (nodeBtns.node_.type_) { - case 6: + case ADD: RightMenu.Reset( [ RightMenu.Button(null, 'Add Child Node', null, () => { @@ -1277,7 +1529,7 @@ class MainEditor { nodeBtns.posY_ + MainEditor.NODE_RECT_HEIGHT ); break; - case 7: + case DELETE: RightMenu.Reset( [ RightMenu.Button(null, 'Delete', null, () => { @@ -1286,34 +1538,33 @@ class MainEditor { }), ], nodeBtns.posX_, - nodeBtns.posY_ + +MainEditor.NODE_RECT_HEIGHT + nodeBtns.posY_ + MainEditor.NODE_RECT_HEIGHT ); break; } } return true; - } - } + } + } - for (let i = 0; i < this.nodeMoreBtnPoint_; i++) { - if (this.nodeMoreBtns[i].procTouch(msg, x, y)) { - let nodeMoreBtn = this.nodeMoreBtns[i]; + this.nodeMoreBtns.forEach((item, index) => { + if (item.procTouch(msg, x, y)) { + let nodeMoreBtn = item; if (nodeMoreBtn.isClicked()) { this.buttonClickedProc(nodeMoreBtn); - this.nodeMoreBtns[i].node_.isOpen_ = - !this.nodeMoreBtns[i].node_.isOpen_; + item.node_.isOpen_ = !item.node_.isOpen_; this.modifyPos_ = { - node: this.nodeMoreBtns[i].node_, - x: this.nodeMoreBtns[i].node_.posX, - y: this.nodeMoreBtns[i].node_.posY, + node: item.node_, + x: item.node_.posX, + y: item.node_.posY, }; } return true; - } - } + } + }); - if (msg == 1 && !this.dropAll_.locked) { + if (msg === MouseType.DOWN && !this.dropAll_.locked) { this.dropAll_.locked = true; this.dropAll_.oldx = x; this.dropAll_.oldy = y; @@ -1342,12 +1593,12 @@ class MainEditor { out.push(data); } switch (data.type_) { - case 6: - for (let i in data.value_) { - this.searchNodeByName(data.value_[i], name, out); - } + case DataType.NODE: + data.value_.forEach((item, index) => { + this.searchNodeByName(item, name, out); + }); break; - case 7: + case DataType.ATTR: this.searchNodeByName(data.value_, name, out); break; } @@ -1364,99 +1615,126 @@ class MainEditor { } this.expandAllParents(node); this.isSearchResult_ = true; - this.offX_ -= node.posX - Scr.logicw / 2; - this.offY_ -= this.offY_ + node.posY - Scr.logich / 2; + this.offX_ -= node.posX - Scr.logicw / CONSTANT_MIDDLE; + this.offY_ -= this.offY_ + node.posY - Scr.logich / CONSTANT_MIDDLE; this.nodePoint_ = node; AttrEditor.gi().freshEditor(); } - procKey(k) { - if (k == 'ctrl+z') { - if (this.selectNode_.type != null) { - this.selectNode_.type = null; - } - console.log('!!! popHistory ', this.historyZ.length); - let h; - if (this.historyZ.length <= 0) { - h = this.historyBase[this.filePoint_]; - } else { - if (this.historyZ.length > 1 && this.historyPushed) { - this.historyZ.pop(); - this.historyPushed = false; - } - h = this.historyZ.pop(); + /** + * Ctrl+Z 快捷键处理 + */ + procCtrlZ() { + let h; + if (this.historyZ.length <= 0) { + h = this.historyBase[this.filePoint_]; + } else { + if (this.historyZ.length > 1 && this.historyPushed) { + this.historyZ.pop(); + this.historyPushed = false; } + h = this.historyZ.pop(); + } + + this.filePoint_ = h.fn; + this.rootPoint_ = h.fn; + Lexer.FILE_AND_DATA[this.filePoint_] = h.data; + this.parse(this.filePoint_); + if (h.sel) { + this.nodePoint_ = NodeTools.getNodeByPath( + this.files_[this.filePoint_], + h.sel + ); + } else { + this.nodePoint_ = null; + } + AttrEditor.gi().freshEditor(this.filePoint_, this.nodePoint_); + } - this.filePoint_ = h.fn; - this.rootPoint_ = h.fn; - Lexer.FILE_AND_DATA[this.filePoint_] = h.data; - this.parse(this.filePoint_); - if (h.sel) { - this.nodePoint_ = NodeTools.getNodeByPath( + /** + * Ctrl+F 快捷键处理 + */ + procCtrlF() { + let xOffset = 300; + let posWidth = 450; + let posHeight = 40; + this.searchInput = { + pos: [(Scr.logicw - xOffset) / CONSTANT_MIDDLE, Scr.logich / CONSTANT_QUARTER, posWidth, posHeight], + result: [], + point: 0, + btnUp: new XButton(0, 0, 0, 0, '上一个'), + btnDown: new XButton(0, 0, 0, 0, '下一个'), + btnClose: new XButton(0, 0, 0, 0, '关闭'), + }; + let x = this.searchInput.pos[0]; + let y = this.searchInput.pos[1]; + let w = this.searchInput.pos[2]; + let h = this.searchInput.pos[3]; + let width = 258; + let height = 32; + let hOffset = 20; + CanvasInput.Reset(x, y + (h - hOffset) / CONSTANT_MIDDLE, width, height, '', null, (v) => { + this.searchInput.result = []; + if (v.length > 0) { + this.searchNodeByName( this.files_[this.filePoint_], - h.sel + v, + this.searchInput.result ); - } else { - this.nodePoint_ = null; - } - AttrEditor.gi().freshEditor(this.filePoint_, this.nodePoint_); - } else if (k == 'ctrl+f') { - this.searchInput = { - pos: [(Scr.logicw - 300) / 2, Scr.logich / 4, 450, 40], - result: [], - point: 0, - btnUp: new XButton(0, 0, 0, 0, '上一个'), - btnDown: new XButton(0, 0, 0, 0, '下一个'), - btnClose: new XButton(0, 0, 0, 0, '关闭'), - }; - let x = this.searchInput.pos[0]; - let y = this.searchInput.pos[1]; - let w = this.searchInput.pos[2]; - let h = this.searchInput.pos[3]; - CanvasInput.Reset(x, y + (h - 20) / 2, 258, 32, '', null, (v) => { - this.searchInput.result = []; - if (v.length > 0) { - this.searchNodeByName( - this.files_[this.filePoint_], - v, - this.searchInput.result - ); - if (this.searchInput.result.length > 0) { - this.locateNode(this.searchInput.result[0]); - this.searchInput.point = 0; - } + if (this.searchInput.result.length > 0) { + this.locateNode(this.searchInput.result[0]); + this.searchInput.point = 0; } - }); - CanvasInput.SetSafeArea(...this.searchInput.pos); - } else if (k == 'ctrl+c') { - if (this.nodePoint_ != null) { + } + }); + CanvasInput.SetSafeArea(...this.searchInput.pos); + } + + /** + * Ctrl+V 快捷键处理 + */ + procCtrlV() { + if (this.selectNode_.type !== null && this.nodePoint_ !== null) { + let parent = this.nodePoint_; + if (this.nodePoint_.type_ !== DataType.NODE) { + parent = this.nodePoint_.parent_; + } + parent.value_.push(NodeTools.copyNode(this.selectNode_.pnode, parent)); + if (this.selectNode_.type === 'cut_node') { + ModifyNode.deleteNode(this.selectNode_.pnode); + this.selectNode_.type = null; + } + this.checkAllError(); + } + } + + procKey(k) { + if (k === 'ctrl+z') { + if (this.selectNode_.type !== null) { + this.selectNode_.type = null; + } + console.log('!!! popHistory ', this.historyZ.length); + this.procCtrlZ(); + } else if (k === 'ctrl+f') { + this.procCtrlF(); + } else if (k === 'ctrl+c') { + if (this.nodePoint_ !== null) { this.selectNode_ = { type: 'copy_node', pnode: this.nodePoint_, }; } - } else if (k == 'ctrl+x') { - if (this.nodePoint_ != null) { + } else if (k === 'ctrl+x') { + if (this.nodePoint_ !== null) { this.selectNode_ = { type: 'cut_node', pnode: this.nodePoint_, }; } - } else if (k == 'ctrl+v') { - if (this.selectNode_.type != null && this.nodePoint_ != null) { - let parent = this.nodePoint_; - if (this.nodePoint_.type_ != DataType.NODE) { - parent = this.nodePoint_.parent_; - } - parent.value_.push(NodeTools.copyNode(this.selectNode_.pnode, parent)); - if (this.selectNode_.type == 'cut_node') { - ModifyNode.deleteNode(this.selectNode_.pnode); - this.selectNode_.type = null; - } - this.checkAllError(); - } - } else if (k == 'Delete') { - if (this.nodePoint_ != null) { + } else if (k === 'ctrl+v') { + this.procCtrlV(); + } else if (k === 'Delete') { + if (this.nodePoint_ !== null) { ModifyNode.deleteNode(this.nodePoint_); AttrEditor.gi().freshEditor(); } @@ -1466,7 +1744,10 @@ class MainEditor { procAll() { while (this.touchQueue_.length > 0) { let touch = this.touchQueue_.shift(); - this.procTouch(touch[0], touch[1], touch[2]); + let msgIndex = 0; + let xIndex = 1; + let yIndex = 2; + this.procTouch(touch[msgIndex], touch[xIndex], touch[yIndex]); } while (this.keyQueue_.length > 0) { @@ -1490,9 +1771,9 @@ class MainEditor { case 5: break; case 6: - for (let i in data.value_) { - ret += this.nodeCount(data.value_[i]); - } + data.value_.forEach((item, index) => { + ret += this.nodeCount(item); + }); break; case 7: ret += this.nodeCount(data.value_); @@ -1513,7 +1794,7 @@ class MainEditor { this.nodeCount_[fn] = -1; } let newcount = this.nodeCount(this.files_[fn]); - if (this.nodeCount_[fn] != newcount) { + if (this.nodeCount_[fn] !== newcount) { if (bset) { this.nodeCount_[fn] = newcount; } @@ -1540,12 +1821,14 @@ class MainEditor { } onAttributeChange(type, value) { let pme = MainEditor.gi(); - if (type == 'writefile') { + let lenChangeTarget = 13; + if (type === 'writefile') { let data1 = Generator.gi().makeHcs(pme.filePoint_, pme.files_[pme.filePoint_]); let data2 = []; - for (let j in data1) { - data2.push(data1.charCodeAt(j)); - } + let dataCharArr = Array.from(data1); + dataCharArr.forEach((item, index) => { + data2.push(data1.charCodeAt(index)); + }); if (pme.isNodeCountChanged(pme.filePoint_)) { Lexer.FILE_AND_DATA[pme.filePoint_] = data2; pme.parse(pme.filePoint_); @@ -1571,12 +1854,12 @@ class MainEditor { data: data1, }); pme.saveHistory(pme.filePoint_, data2, NodeTools.getPathByNode(pme.nodePoint_), 1); - } else if (type.substring(0, 13) == 'change_target') { + } else if (type.substring(0, lenChangeTarget) === 'change_target') { pme.selectNode_.type = type; pme.selectNode_.pnode = value; } else if (type.startsWith('cancel_change_target')) { pme.selectNode_.type = null; - } else if (type == 'change_current_select') { + } else if (type === 'change_current_select') { pme.nodePoint_ = value; AttrEditor.gi().freshEditor(pme.filePoint_, pme.nodePoint_); } @@ -1592,98 +1875,98 @@ class MainEditor { console.log('onReceive type=' + type); NapiLog.logError(type); let me = MainEditor.gi(); - if (type == 'parse') { + if (type === 'parse') { me.parse(data); - } else if (type == 'filedata') { + } else if (type === 'filedata') { me.saveHistory(data.fn, data.data, null, 2); Lexer.FILE_AND_DATA[data.fn] = data.data; me.parse(data.fn); - } else if (type == 'freshfiledata') { + } else if (type === 'freshfiledata') { me.saveHistory(data.fn, data.data, null, 3); Lexer.FILE_AND_DATA[data.fn] = data.data; - } else if (type == 'whiteCutImg') { + } else if (type === 'whiteCutImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initCutData(wurl); - } else if (type == 'circleImg') { + } else if (type === 'circleImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initCicleImgData(wurl); - } else if (type == 'cicleOpenImg') { + } else if (type === 'cicleOpenImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initcicleOpenImgData(wurl); - } else if (type == 'rectangleFocusImg') { + } else if (type === 'rectangleFocusImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initRectangleFocusImgData(wurl); - } else if (type == 'nodeIconImg') { + } else if (type === 'nodeIconImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initNodeIconImgData(wurl); - } else if (type == 'attrIconImg') { + } else if (type === 'attrIconImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initAttrIconImgData(wurl); - } else if (type == 'rootIconImg') { + } else if (type === 'rootIconImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initRootIconImgData(wurl); - } else if (type == 'rootIconFocusImg') { + } else if (type === 'rootIconFocusImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initRootIconFocusImgData(wurl); - } else if (type == 'backgroundImg') { + } else if (type === 'backgroundImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initBackgroundImgData(wurl); - } else if (type == 'popItemFocusImg') { + } else if (type === 'popItemFocusImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initPopItemFocusImgData(wurl); - } else if (type == 'colorThemeChanged') { + } else if (type === 'colorThemeChanged') { me.reloadMenuBgPic(); - } else if (type == 'searchBgImg') { + } else if (type === 'searchBgImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initSearchBgImgData(wurl); - } else if (type == 'upCutImg') { + } else if (type === 'upCutImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initUpImgData(wurl); - } else if (type == 'downCut') { + } else if (type === 'downCut') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initDownImgData(wurl); - } else if (type == 'closeCutImg') { + } else if (type === 'closeCutImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initCloseImgData(wurl); - } else if (type == 'searchCutImg') { + } else if (type === 'searchCutImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initSearchImgData(wurl); - } else if (type == 'searchNoodRectImg') { + } else if (type === 'searchNoodRectImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); me.initSearchNoodRectImgData(wurl); - } else if (type == 'searchAttrRectImg') { + } else if (type === 'searchAttrRectImg') { let u8arr = new Uint8Array(data.data); let imgobj = new Blob([u8arr], { type: 'image/png' }); let wurl = window.URL.createObjectURL(imgobj); @@ -1694,326 +1977,180 @@ class MainEditor { } initSearchAttrRectImgData(wurl) { + const HEIGHT = 32; + const NEW_WIDTH = 132; + const OLD_WIDTH = 8; + const CS_X_VAL = 8; + const RS_X_VAL = 124; + const CS_OLD_WIDTH = 116; this.searchAttrCicleImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.leftSearchAttrCicleCut_ = XTexture.gi().makeCut( - this.searchAttrCicleImg_, - 0, - 0, - 8, - 32, - 132, - 32 - ); - this.centerSearchAttrCut_ = XTexture.gi().makeCut( - this.searchAttrCicleImg_, - 8, - 0, - 116, - 32, - 132, - 32 - ); - this.rightSearchAttrCicleCut_ = XTexture.gi().makeCut( - this.searchAttrCicleImg_, - 124, - 0, - 8, - 32, - 132, - 32 - ); + this.leftSearchAttrCicleCut_ = XTexture.gi().makeCut(this.searchAttrCicleImg_, 0, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.centerSearchAttrCut_ = XTexture.gi().makeCut(this.searchAttrCicleImg_, CS_X_VAL, 0, CS_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.rightSearchAttrCicleCut_ = XTexture.gi().makeCut(this.searchAttrCicleImg_, RS_X_VAL, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); } initSearchNoodRectImgData(wurl) { + const HEIGHT = 32; + const NEW_WIDTH = 132; + const OLD_WIDTH = 8; + const CS_X_VAL = 8; + const RS_X_VAL = 124; + const CS_OLD_WIDTH = 116; this.searchRectFocusCicleImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.leftSearchFocusCicleCut_ = XTexture.gi().makeCut( - this.searchRectFocusCicleImg_, - 0, - 0, - 8, - 32, - 132, - 32 - ); - this.centerSearchCut_ = XTexture.gi().makeCut( - this.searchRectFocusCicleImg_, - 8, - 0, - 116, - 32, - 132, - 32 - ); - this.rightSearchFocusCicleCut_ = XTexture.gi().makeCut( - this.searchRectFocusCicleImg_, - 124, - 0, - 8, - 32, - 132, - 32 - ); + this.leftSearchFocusCicleCut_ = XTexture.gi().makeCut(this.searchRectFocusCicleImg_, 0, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.centerSearchCut_ = XTexture.gi().makeCut(this.searchRectFocusCicleImg_, CS_X_VAL, 0, CS_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.rightSearchFocusCicleCut_ = XTexture.gi().makeCut(this.searchRectFocusCicleImg_, RS_X_VAL, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); } initSearchImgData(wurl) { + const WIDTH = 16; + const HEIGHT = 16; this.searchImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.searchCut_ = XTexture.gi().makeCut( - this.searchImg_, - 0, - 0, - 16, - 16, - 16, - 16 - ); + this.searchCut_ = XTexture.gi().makeCut(this.searchImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initCloseImgData(wurl) { + const WIDTH = 16; + const HEIGHT = 16; this.closeImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.closeCut_ = XTexture.gi().makeCut( - this.closeImg_, - 0, - 0, - 16, - 16, - 16, - 16 - ); + this.closeCut_ = XTexture.gi().makeCut(this.closeImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initDownImgData(wurl) { + const WIDTH = 16; + const HEIGHT = 16; this.downImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.downCut_ = XTexture.gi().makeCut(this.downImg_, 0, 0, 16, 16, 16, 16); + this.downCut_ = XTexture.gi().makeCut(this.downImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initUpImgData(wurl) { + const WIDTH = 16; + const HEIGHT = 16; this.upImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.upCut_ = XTexture.gi().makeCut(this.upImg_, 0, 0, 16, 16, 16, 16); + this.upCut_ = XTexture.gi().makeCut(this.upImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initSearchBgImgData(wurl) { + const WIDTH = 494; + const HEIGHT = 56; this.searchBgImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.searchBgCut_ = XTexture.gi().makeCut( - this.searchBgImg_, - 0, - 0, - 494, - 56, - 494, - 56 - ); + this.searchBgCut_ = XTexture.gi().makeCut(this.searchBgImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initPopItemFocusImgData(wurl) { + const WIDTH = 148; + const HEIGHT = 32; RightMenu.popItemFocusImg_ = XTexture.gi().loadTextureFromImage(wurl); - RightMenu.popItemFocusCut_ = XTexture.gi().makeCut( - RightMenu.popItemFocusImg_, - 0, - 0, - 148, - 32, - 148, - 32 - ); + RightMenu.popItemFocusCut_ = XTexture.gi().makeCut(RightMenu.popItemFocusImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initBackgroundImgData(wurl) { + const WIDTH = 156; + const HEIGHT = 112; RightMenu.backgroundImg_ = XTexture.gi().loadTextureFromImage(wurl); - RightMenu.backgroundCut_ = XTexture.gi().makeCut( - RightMenu.backgroundImg_, - 0, - 0, - 156, - 112, - 156, - 112 - ); + RightMenu.backgroundCut_ = XTexture.gi().makeCut(RightMenu.backgroundImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initRootIconFocusImgData(wurl) { + const WIDTH = 132; + const HEIGHT = 32; this.rootIconFocusImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.rootIconFocusCut_ = XTexture.gi().makeCut( - this.rootIconFocusImg_, - 0, - 0, - 132, - 32, - 132, - 32 - ); + this.rootIconFocusCut_ = XTexture.gi().makeCut(this.rootIconFocusImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initRootIconImgData(wurl) { + const WIDTH = 132; + const HEIGHT = 32; this.rootIconImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.rootIconCut_ = XTexture.gi().makeCut( - this.rootIconImg_, - 0, - 0, - 132, - 32, - 132, - 32 - ); + this.rootIconCut_ = XTexture.gi().makeCut(this.rootIconImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initAttrIconImgData(wurl) { + const WIDTH = 8; + const HEIGHT = 8; this.attrIconImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.attrIconCut_ = XTexture.gi().makeCut( - this.attrIconImg_, - 0, - 0, - 8, - 8, - 8, - 8 - ); + this.attrIconCut_ = XTexture.gi().makeCut(this.attrIconImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initNodeIconImgData(wurl) { + const WIDTH = 8; + const HEIGHT = 8; this.nodeIconImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.nodeIconCut_ = XTexture.gi().makeCut( - this.nodeIconImg_, - 0, - 0, - 8, - 8, - 8, - 8 - ); + this.nodeIconCut_ = XTexture.gi().makeCut(this.nodeIconImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initcicleOpenImgData(wurl) { + const WIDTH = 20; + const HEIGHT = 20; this.cicleOpenImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.circleOpenCut_ = XTexture.gi().makeCut( - this.cicleOpenImg_, - 0, - 0, - 20, - 20, - 20, - 20 - ); + this.circleOpenCut_ = XTexture.gi().makeCut(this.cicleOpenImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initRectangleFocusImgData(wurl) { + const HEIGHT = 32; + const NEW_WIDTH = 132; + const OLD_WIDTH = 8; + const RF_OLD_WIDTH = 132; + const CF_X_VAL = 8; + const CF_OLD_WIDTH = 116; + const RR_X_VAL = 124; this.rectangleFocusImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.rectangleFocusCut_ = XTexture.gi().makeCut( - this.rectangleFocusImg_, - 0, - 0, - 132, - 32, - 132, - 32 - ); - this.leftRectFocusCicleCut_ = XTexture.gi().makeCut( - this.rectangleFocusImg_, - 0, - 0, - 8, - 32, - 132, - 32 - ); - this.centerFocusCut_ = XTexture.gi().makeCut( - this.rectangleFocusImg_, - 8, - 0, - 116, - 32, - 132, - 32 - ); - this.rightRectFocusCicleCut_ = XTexture.gi().makeCut( - this.rectangleFocusImg_, - 124, - 0, - 8, - 32, - 132, - 32 - ); + this.rectangleFocusCut_ = XTexture.gi().makeCut(this.rectangleFocusImg_, 0, 0, RF_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.leftRectFocusCicleCut_ = XTexture.gi().makeCut(this.rectangleFocusImg_, 0, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.centerFocusCut_ = XTexture.gi().makeCut(this.rectangleFocusImg_, CF_X_VAL, 0, CF_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.rightRectFocusCicleCut_ = XTexture.gi().makeCut(this.rectangleFocusImg_, RR_X_VAL, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); } initCicleImgData(wurl) { + const WIDTH = 20; + const HEIGHT = 20; this.cicleImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.circleCut_ = XTexture.gi().makeCut( - this.cicleImg_, - 0, - 0, - 20, - 20, - 20, - 20 - ); + this.circleCut_ = XTexture.gi().makeCut(this.cicleImg_, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT); } initCutData(wurl) { + const HEIGHT = 32; + const NEW_WIDTH = 132; + const OLD_WIDTH = 8; + const CR_X_VAL = 8; + const RR_X_VAL = 124; + const WC_OLD_WIDTH = 132; + const CR_OLD_WIDTH = 116; this.whiteImg_ = XTexture.gi().loadTextureFromImage(wurl); - this.whiteCut_ = XTexture.gi().makeCut( - this.whiteImg_, - 0, - 0, - 132, - 32, - 132, - 32 - ); - this.leftRectCicleCut_ = XTexture.gi().makeCut( - this.whiteImg_, - 0, - 0, - 8, - 32, - 132, - 32 - ); - this.centerRectCut_ = XTexture.gi().makeCut( - this.whiteImg_, - 8, - 0, - 116, - 32, - 132, - 32 - ); - this.rightRectCicleCut_ = XTexture.gi().makeCut( - this.whiteImg_, - 124, - 0, - 8, - 32, - 132, - 32 - ); + this.whiteCut_ = XTexture.gi().makeCut(this.whiteImg_, 0, 0, WC_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.leftRectCicleCut_ = XTexture.gi().makeCut(this.whiteImg_, 0, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.centerRectCut_ = XTexture.gi().makeCut(this.whiteImg_, CR_X_VAL, 0, CR_OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); + this.rightRectCicleCut_ = XTexture.gi().makeCut(this.whiteImg_, RR_X_VAL, 0, OLD_WIDTH, HEIGHT, NEW_WIDTH, HEIGHT); } syncOpenStatus(newNode, oldParentNode) { let oldNode = null; - for (let i = 0; i < oldParentNode.value_.length; ++i) { - if (newNode.name_ === oldParentNode.value_[i].name_) { - oldNode = oldParentNode.value_[i]; - } - } - if (oldNode == null) { + oldParentNode.value_.forEach((item, index) => { + if (newNode.name_ === item.name_) { + oldNode = item; + } + }); + if (oldNode === null) { return; } newNode.isOpen_ = oldNode.isOpen_; - for (let j = 0; j < newNode.value_.length; ++j) { - this.syncOpenStatus(newNode.value_[j], oldNode); + if (newNode.type_ === DataType.NODE) { + newNode.value_.forEach((j, index) => { + this.syncOpenStatus(j, oldNode); + }); } } syncRootStatus(newRoot, oldRoot) { newRoot.isOpen_ = oldRoot.isOpen_; - for (let i = 0; i < newRoot.value_.length; ++i) { - this.syncOpenStatus(newRoot.value_[i], oldRoot); - } + newRoot.value_.forEach((item, index) => { + this.syncOpenStatus(item, oldRoot); + }); } parse(fn) { - if (this.rootPoint_ == null) { + if (this.rootPoint_ === null) { this.rootPoint_ = fn; } let t = Generator.gi().hcsToAst(fn); @@ -2022,16 +2159,17 @@ class MainEditor { } let fs = []; - for (let i in t) { - let newRoot = Generator.gi().astToObj(t[i].ast.astRoot_); + Object.keys(t).forEach((index) => { + let newRoot = Generator.gi().astToObj(t[index].ast.astRoot_); - if (this.files_[i]) { - this.syncRootStatus(newRoot, this.files_[i]); + if (this.files_[index]) { + this.syncRootStatus(newRoot, this.files_[index]); } - this.files_[i] = newRoot; - fs.push(i); - } + this.files_[index] = newRoot; + fs.push(index); + }); + this.filePoint_ = this.rootPoint_; this.sltInclude.resetList(fs, this.filePoint_); AttrEditor.gi().setFiles(this.files_); @@ -2054,7 +2192,7 @@ class MainEditor { MainEditor.LINE_HEIGHT = 50; MainEditor.NODE_RECT_HEIGHT = 32; MainEditor.NODE_RECT_WIDTH = 132; -MainEditor.NODE_TEXT_COLOR = 0xffffffff; +MainEditor.NODE_TEXT_COLOR = 0xffffffff; // white MainEditor.NODE_TEXT_SIZE = 14; MainEditor.BTN_CONTENT_OFFY = 4; MainEditor.NODE_TEXT_OFFX = 5; @@ -2067,7 +2205,7 @@ MainEditor.LOGO_SIZE = 8; MainEditor.pInstance_ = null; MainEditor.gi = function () { - if (MainEditor.pInstance_ == null) { + if (MainEditor.pInstance_ === null) { MainEditor.pInstance_ = new MainEditor(); } return MainEditor.pInstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/attr/AttributeArea.js b/framework/tools/hcs-view/hcsWebView/src/attr/AttributeArea.js index 0232d774edef0404c511866c43e9a5f1efa64115..fe181646baf90887fcc61a8b44721bb99f76b2e0 100644 --- a/framework/tools/hcs-view/hcsWebView/src/attr/AttributeArea.js +++ b/framework/tools/hcs-view/hcsWebView/src/attr/AttributeArea.js @@ -13,6 +13,8 @@ * limitations under the License. */ +const MAX_LABEL_LENGTH = 40; + class AttributeArea { constructor() { document.attrCallback = this; @@ -47,6 +49,13 @@ class AttributeArea { '
'; ret += '
'; + this.htmlStr += ret; + } + + addInputFunc(default_, ret, searchId, disable) { if (default_.indexOf('"') >= 0) { ret += ' value=""'; this.freshInputValue_.push([searchId, default_]); @@ -56,36 +65,16 @@ class AttributeArea { if (disable) { ret += ' disabled="disabled"'; } - ret += - ' oninput="document.attrCallback.Event(' + - "'input', " + - "'" + - searchId + - "'" + - ')" />
'; - this.htmlStr += ret; + return ret; } addInput(searchId, label, default_, disable) { let ret = '
'; ret += '= 0) { - ret += ' value=""'; - this.freshInputValue_.push([searchId, default_]); - } else { - ret += ' value="' + default_ + '"'; - } - if (disable) { - ret += ' disabled="disabled"'; - } - ret += - ' oninput="document.attrCallback.Event(' + - "'input', " + - "'" + - searchId + - "'" + - ')" />
'; + ret = this.addInputFunc(default_, ret, searchId, disable); + ret += ' oninput="document.attrCallback.Event(' + "'input', " + "'" + + searchId + "'" + ')" />
'; this.htmlStr += ret; } @@ -99,17 +88,8 @@ class AttributeArea { let validatorId = 'valid_' + searchId; let ret = '
'; ret += '= 0) { - ret += ' value=""'; - this.freshInputValue_.push([searchId, default_]); - } else { - ret += ' value="' + default_ + '"'; - } - if (disable) { - ret += ' disabled="disabled"'; - } + ret += ' class="input_text" maxlength="40" placeholder="' + defaultTxt + '"'; + ret = this.addInputFunc(default_, ret, searchId, disable); ret += ' autofocus="autofocus" onFocus="document.attrCallback.Event(' + "'input', " + @@ -147,61 +127,35 @@ class AttributeArea { this.htmlStr += ret; } addButton(searchId, label) { - if (label.length > 40) { - label = label.substring(0, 40) + '...'; + if (label.length > MAX_LABEL_LENGTH) { + label = label.substring(0, MAX_LABEL_LENGTH) + '...'; } let text = '" class="button_click" type="button" onclick="document.attrCallback.Event('; - this.htmlStr += - '
'; + let htmlString = this.getStrText(searchId, text, label); + this.htmlStr += '
'; + } + addLabelButton(searchId, label, title) { - if (label.length > 40) { - label = label.substring(0, 40) + '...'; + if (label.length > MAX_LABEL_LENGTH) { + label = label.substring(0, MAX_LABEL_LENGTH) + '...'; } let text = '" class="label_button_click" type="button" onclick="document.attrCallback.Event('; - this.htmlStr += - '

'; + let htmlString = this.getStrText(searchId, text, label); + this.htmlStr += '

'; + let text = '" class="button_click_delete" type="button" onclick="document.attrCallback.Event('; + this.htmlStr += '
'; } addSelect(searchId, label, selectList, default_, disable) { let ret = '
'; @@ -230,16 +184,18 @@ class AttributeArea { this.htmlStr += ret; } addGap(type) { - if (type == 0) this.htmlStr += '
'; + if (type === 0) { + this.htmlStr += '
'; + } } Event(type, value) { let cbv = ''; - if (type == 'input') { + if (type === 'input') { cbv = document.getElementById(value).value; - } else if (type == 'select') { + } else if (type === 'select') { cbv = document.getElementById(value).value; } - if (this.callbackFunc != null) { + if (this.callbackFunc !== null) { this.callbackFunc(value, type, cbv); } } @@ -249,7 +205,7 @@ class AttributeArea { } AttributeArea.pInstance_ = null; AttributeArea.gi = function () { - if (AttributeArea.pInstance_ == null) { + if (AttributeArea.pInstance_ === null) { AttributeArea.pInstance_ = new AttributeArea(); } return AttributeArea.pInstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/GLFrame.js b/framework/tools/hcs-view/hcsWebView/src/engine/GLFrame.js index 32674761be0c6c1efb813c2ed7aabdbfd5e15f82..adbb12668255053b7b21e92e70ebae922fac1fbb 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/GLFrame.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/GLFrame.js @@ -136,7 +136,7 @@ function keyDown(e) { GLFrame.pinstance_.callbackKey(1, ret); if (!CanvasInput.FOCUS) { } - if (ret == 'ctrl+z') { + if (ret === 'ctrl+z') { e.preventDefault(); } } @@ -176,7 +176,7 @@ export class GLFrame { window.requestAnimationFrame(mainLoop); } callbackKey(type, code) { - if (this.pCallbackKey != null) { + if (this.pCallbackKey !== null) { this.pCallbackKey(type, code); } } @@ -184,17 +184,17 @@ export class GLFrame { gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - if (this.pCallbackDraw != null) { + if (this.pCallbackDraw !== null) { this.pCallbackDraw(); } } callbackProctouch(msg, x, y) { XTools.MOUSE_POS.x = x; XTools.MOUSE_POS.y = y; - if (msg == 1) { + if (msg === 1) { CanvasInput.Hide(x, y); } - if (this.pCallbackTouch != null) { + if (this.pCallbackTouch !== null) { x = (x * Scr.logicw) / Scr.width; y = (y * Scr.logich) / Scr.height; this.pCallbackTouch(msg, x, y); diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/RightMenu.js b/framework/tools/hcs-view/hcsWebView/src/engine/RightMenu.js index 9553088bc337c790ae076514a022d3331521333a..58a66e6e1e9e311eb132b1f6543dd9e627812f1e 100755 --- a/framework/tools/hcs-view/hcsWebView/src/engine/RightMenu.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/RightMenu.js @@ -16,6 +16,21 @@ const { X2DFast } = require('./graphics/X2DFast'); const { Scr } = require('./XDefine'); const { XTools } = require('./XTools'); +const MenuType = { + BUTTON: 0, // 按钮 + CONTENT: 1, // 目录 + DIVIDER: 2, // 分割线 +}; + +const MenuGroupSize = { + DELETE: 1, // 目录 + NODEMENU: 3, // 分割线 +}; + +const MOUSETYPE_MOVE = 2; +const DRAWTEXT_OFFSETX = -3; +const DRAWTEXT_OFFSETY = -2; + class RightMenu { static backgroundImg_ = -1; static backgroundCut_ = -1; @@ -30,8 +45,8 @@ class RightMenu { static isDarkBackground_ = true; static Reset(detail, x, y) { RightMenu.MENU = { - x: x == null ? XTools.MOUSE_POS.x : x, - y: y == null ? XTools.MOUSE_POS.y : y, + x: x === null ? XTools.MOUSE_POS.x : x, + y: y === null ? XTools.MOUSE_POS.y : y, detail: detail, needClose: false, }; @@ -89,13 +104,13 @@ class RightMenu { let w = RightMenu.MENUW; let l = 0; for (let e of grp) { - if (e.type != 2) { + if (e.type !== MenuType.DIVIDER) { l += 1; } } - if (grp.length == 3) { + if (grp.length === MenuGroupSize.NODEMENU) { X2DFast.px2f.drawCut(this.backgroundCut_, x, y, 1, 0.88, 0, -1, -1); - } else if (grp.length == 1) { + } else if (grp.length === MenuGroupSize.DELETE) { X2DFast.px2f.drawCut(this.backgroundCut_, x, y, 1, 0.3, 0, -1, -1); } else { X2DFast.px2f.drawCut(this.backgroundCut_, x, y, 1, 1, 0, -1, -1); @@ -109,7 +124,7 @@ class RightMenu { y ); } - if (e.type == 2) { + if (e.type === MenuType.DIVIDER) { e.rect = [x, y, w, 0]; X2DFast.px2f.drawLine(x, y, x + w, y, 0xff808080, 2); continue; @@ -128,7 +143,7 @@ class RightMenu { 0, textColor ); - if (e.type == 0) { + if (e.type === MenuType.BUTTON) { if (e.hk) { X2DFast.px2f.drawText( e.hk, @@ -143,44 +158,27 @@ class RightMenu { 0xff808080 ); } - } else if (e.type == 1) { + } else if (e.type === MenuType.CONTENT) { if (e.open) { - X2DFast.px2f.drawText( - '<', - RightMenu.TEXT_SIZE, - x + w, - OFFY_, - 1, - 1, - 0, - -3, - -2, - textColor - ); + RightMenu.callDrawText('<', x, w, OFFY_, textColor); RightMenu.DrawGroup(e.group, x + w, y); } else { - X2DFast.px2f.drawText( - '>', - RightMenu.TEXT_SIZE, - x + w, - OFFY_, - 1, - 1, - 0, - -3, - -2, - textColor - ); + RightMenu.callDrawText('>', x, w, OFFY_, textColor); } } y += 32; } } + static callDrawText(symbol, x, w, OFFY_, textColor) { + X2DFast.px2f.drawText(symbol, RightMenu.TEXT_SIZE, x + w, OFFY_, 1, 1, 0, + DRAWTEXT_OFFSETX, DRAWTEXT_OFFSETY, textColor); + } + static Touch(msg, x, y) { if (RightMenu.MENU) { if (RightMenu.TouchGroup(RightMenu.MENU.detail, msg, x, y)) { return true; - } else if (msg != 2) { + } else if (msg !== MOUSETYPE_MOVE) { RightMenu.MENU.needClose = true; } } @@ -204,20 +202,20 @@ class RightMenu { return false; } if (XTools.InRect(x, y, ...e.rect)) { - if (e.type == 1 && msg == 1) { + if (e.type === MenuType.CONTENT && msg === 1) { e.open = !e.open; } - if (e.type == 2) { + if (e.type === MenuType.DIVIDER) { } - if (e.type == 0) { - if (msg == 1) { + if (e.type === MenuType.BUTTON) { + if (msg === 1) { e.cb(); } } e.on = true; return true; } - if (e.type == 1) { + if (e.type === MenuType.CONTENT) { if (e.open && RightMenu.TouchGroup(e.group, msg, x, y)) { return true; } diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/XDefine.js b/framework/tools/hcs-view/hcsWebView/src/engine/XDefine.js index 657bd749dddbc4b216dde814b66d55d17b61c89c..3067149dc26e82837656625b58827c9777e71e54 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/XDefine.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/XDefine.js @@ -19,14 +19,14 @@ export class Scr { static ReSize(w, h) { Scr.width = w; Scr.height = h; - if (Scr.keeplogicworh == 'width') { + if (Scr.keeplogicworh === 'width') { Scr.logich = (Scr.logicw * h) / w; } else { Scr.logicw = (Scr.logich * w) / h; } } static setLogicScreenSize(w, h) { - if (Scr.logicw == w && Scr.width == w && Scr.logich == h && Scr.height == h) { + if (Scr.logicw === w && Scr.width === w && Scr.logich === h && Scr.height === h) { return; } Scr.logicw = w; @@ -34,7 +34,7 @@ export class Scr { Scr.width = w; Scr.height = h; NapiLog.logError('setLogicScreenSize'); - if ('undefined' != typeof wx) { + if ('undefined' !== typeof wx) { var info = wx.getSystemInfoSync(); Scr.width = info.windowWidth; Scr.height = info.windowHeight; diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/XTools.js b/framework/tools/hcs-view/hcsWebView/src/engine/XTools.js index 468b1c3f4d9cb13b975ac80238c7a98023f4308c..d22c706cebff424d47b4e8faf4d1ca65c8e24e4f 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/XTools.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/XTools.js @@ -56,7 +56,7 @@ export function RandInt(min = 0, max = 100) { } export function GetURL() { - if ('undefined' != typeof wx) { + if ('undefined' !== typeof wx) { return 'https://7465-testegg-19e3c9-1301193145.tcb.qcloud.la/'; } else { return ''; diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/control/XButton.js b/framework/tools/hcs-view/hcsWebView/src/engine/control/XButton.js index 085b58cc04f0c4623da49f56fcdb403236f3bfc0..e6c751427ea5bb2ba013ff5ad23333569fe7e29a 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/control/XButton.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/control/XButton.js @@ -37,9 +37,11 @@ class XButton { } draw() { + const COLOR_OFF = 0x00202020; + const SIZE = 14; let coloroff = 0; if (this.touchDown_) { - coloroff = 0x00202020; + coloroff = COLOR_OFF; } this.pm2f_.fillRect( this.posX_, @@ -48,13 +50,21 @@ class XButton { this.posH_, this.backgroundColor_ - coloroff ); - if (this.name_ != undefined && this.name_.length > 0) + if (this.name_ !== undefined && this.name_.length > 0) { - this.pm2f_.drawText(this.name_, 14, this.posX_ + this.posW_ / 2, this.posY_ + this.posH_ / 2 + 2, 1, 1, 0, -2, -2, this.nameColor_ - coloroff); + let middle = 2; + let yOffset = 2; + let sw = 1; + let sh = 1; + let ra = 0; + let ox = -2; + let oy = -2; + this.pm2f_.drawText(this.name_, SIZE, this.posX_ + this.posW_ / middle, this.posY_ + + this.posH_ / middle + yOffset, sw, sh, ra, ox, oy, this.nameColor_ - coloroff); } } - isTouchIn(x, y) { + isTouchInButton(x, y) { if (x < this.posX_) { return false; } @@ -70,7 +80,7 @@ class XButton { return true; } procTouch(msg, x, y) { - let isIn = this.isTouchIn(x, y); + let isIn = this.isTouchInButton(x, y); switch (msg) { case 1: if (isIn) { diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/control/XSelect.js b/framework/tools/hcs-view/hcsWebView/src/engine/control/XSelect.js index f012e2bcb86960d39beb78c2278f661d8485f547..2a56656209413fbd2c170385038eb8dadcdb0bf4 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/control/XSelect.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/control/XSelect.js @@ -14,6 +14,7 @@ */ const { X2DFast } = require('../graphics/X2DFast'); +const HEIGHT = 20; class XSelect { constructor(list, default_) { @@ -49,12 +50,12 @@ class XSelect { this.pm2f_.fillRect(x, y, w, h, this.backgroundColor_); let name = '...'; - if (this.default_.indexOf('\\') != -1) { + if (this.default_.indexOf('\\') !== -1) { let list = this.default_.split('\\'); if (list.length > model) { for (let i = list.length - model; i < list.length; i++) { name += list[i]; - if (i != list.length - 1) { + if (i !== list.length - 1) { name += '\\'; } } @@ -66,21 +67,21 @@ class XSelect { } this.pm2f_.drawText(name, 16, x, y, 1, 1, 0, -1, -1, this.nameColor_); if (this.open_) { - this.pm2f_.fillRect(x, y + h, w, 20 * this.list_.length, this.backgroundColor_); + this.pm2f_.fillRect(x, y + h, w, HEIGHT * this.list_.length, this.backgroundColor_); for (let i in this.list_) { - if (i == this.tmpSelect_) { - this.pm2f_.fillRect(x, y + h + i * 20, w, 20, this.backgroundColor_); + if (i === this.tmpSelect_) { + this.pm2f_.fillRect(x, y + h + i * HEIGHT, w, HEIGHT, this.backgroundColor_); } - if (this.list_[i] == this.default_) { - this.pm2f_.fillRect(x, y + h + i * 20, w, 20, this.backgroundColor_); + if (this.list_[i] === this.default_) { + this.pm2f_.fillRect(x, y + h + i * HEIGHT, w, HEIGHT, this.backgroundColor_); } let name1 = '...'; - if (this.list_[i].indexOf('\\') != -1) { + if (this.list_[i].indexOf('\\') !== -1) { let list = this.list_[i].split('\\'); if (list.length > model) { for (let k = list.length - model; k < list.length; k++) { name1 += list[k]; - if (k != list.length - 1) { + if (k !== list.length - 1) { name1 += '\\'; } } @@ -115,7 +116,7 @@ class XSelect { if (x > this.posX_ + this.posW_) { return false; } - if (y > this.posY_ + this.posH_ + (this.open_ ? 20 * this.list_.length : 0)) { + if (y > this.posY_ + this.posH_ + (this.open_ ? HEIGHT * this.list_.length : 0)) { return false; } return true; @@ -132,9 +133,9 @@ class XSelect { break; } if (this.tmpSelect_ >= 0 && this.tmpSelect_ <= this.list_.length) { - if (this.default_ != this.list_[this.tmpSelect_]) { + if (this.default_ !== this.list_[this.tmpSelect_]) { this.default_ = this.list_[this.tmpSelect_]; - if (this.selectCallback != null) { + if (this.selectCallback !== null) { this.selectCallback(this.default_); } } diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/X2DFast.js b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/X2DFast.js index 4bb14dfdd621c4f314b86bb478e3b463e9fc5acd..33e94ef20de313c8de4d5b8256acb64580f8f09d 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/X2DFast.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/X2DFast.js @@ -21,10 +21,11 @@ import { gl } from '../GLFrame.js'; import { fAngle, iDistance } from '../XTools.js'; const { NapiLog } = require('./../../hcs/NapiLog'); const COLOR = 0xffffffff; +const DRAWTEXT_SIZE = 14; export class X2DFast { static gi() { - if (X2DFast.px2f == null) { + if (X2DFast.px2f === null) { X2DFast.px2f = new X2DFast(); } return X2DFast.px2f; @@ -82,7 +83,7 @@ export class X2DFast { while (i < Math.PI * 2 + 0.00001) { let dx = Math.cos(i) * rw + ox; let dy = Math.sin(i) * rh + oy; - if (lx != -1) { + if (lx !== -1) { this.drawLine(lx, ly, dx, dy, c, lw); } lx = dx; @@ -122,35 +123,36 @@ export class X2DFast { const RIGHT = -3; const UP = -1; const DOWN = -3; + const BY_MIDDLE = 2; X2DFast.tmpMat.unit(); - if (ox == LEFT) { + if (ox === LEFT) { ox = 0; } - if (ox == MIDDLE) { - ox = Math.floor(realw / 2); + if (ox === MIDDLE) { + ox = Math.floor(realw / BY_MIDDLE); } - if (ox == RIGHT) { + if (ox === RIGHT) { ox = realw; } - if (oy == UP) { + if (oy === UP) { oy = 0; } - if (oy == MIDDLE) { - oy = Math.floor(realh / 2); + if (oy === MIDDLE) { + oy = Math.floor(realh / BY_MIDDLE); } - if (oy == DOWN) { + if (oy === DOWN) { oy = realh; } - if (ox != 0 || oy != 0) { + if (ox !== 0 || oy !== 0) { X2DFast.tmpMat.move(-ox, -oy, 0); } - if (sw != 1 || sh != 1) { + if (sw !== 1 || sh !== 1) { X2DFast.tmpMat.scale(sw, sh, 1); } - if (ra != 0) { + if (ra !== 0) { X2DFast.tmpMat.rotate(0, 0, ra); } - if (x != 0 || y != 0) { + if (x !== 0 || y !== 0) { X2DFast.tmpMat.move(x, y, 0); } } @@ -167,7 +169,7 @@ export class X2DFast { return ((a * 64 + r) * 64 + g) * 64 + b; } drawCut_(pcut, m00, m01, m10, m11, m22, m30, m31, c = COLOR) { - if (c == -1) { + if (c === -1) { c = COLOR; } c = this.swapC(c); @@ -194,7 +196,7 @@ export class X2DFast { let intX = parseInt(x); let intY = parseInt(y); let pcut = XTexture.gi().allCuts[cid]; - if (pcut == null) { + if (pcut === null) { NapiLog.logError('error occured getting object'); return; } @@ -210,7 +212,7 @@ export class X2DFast { let tmat = X2DFast.tmpMat.mat; this.drawCut_(pcut, tmat[0][0], tmat[0][1], tmat[1][0], tmat[1][1], tmat[2][2], tmat[3][0], tmat[3][1], c); } - drawText(s, size = 14, x = 0, y = 0, sw = 1, sh = 1, ra = 0, ox = 0, oy = 0, c = COLOR) { + drawText(s, size = DRAWTEXT_SIZE, x = 0, y = 0, sw = 1, sh = 1, ra = 0, ox = 0, oy = 0, c = COLOR) { if (s.length <= 0) { NapiLog.logError('error occured s is null'); return 0; @@ -230,7 +232,7 @@ export class X2DFast { } freshBuffer() { XTexture.gi()._FreshText(); - if (this.drawCount == 0) { + if (this.drawCount === 0) { return; } let ps = XShader.gi().use(XShader.ID_SHADER_FAST); diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XMat4.js b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XMat4.js index e9cdaba09a8f7b0f0ca3f3aa1776f1e191527ab1..f920b1e45d95ac30016e8867215d14e1497c95c2 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XMat4.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XMat4.js @@ -80,15 +80,15 @@ export class XMat4 { return this; } rotate(x, y, z) { - if (x != 0) { + if (x !== 0) { tmpmat.initRotateMatX((x * Math.PI) / 180); this.mult(tmpmat); } - if (y != 0) { + if (y !== 0) { tmpmat.initRotateMatY((y * Math.PI) / 180); this.mult(tmpmat); } - if (z != 0) { + if (z !== 0) { tmpmat.initRotateMatZ((z * Math.PI) / 180); this.mult(tmpmat); } @@ -127,10 +127,10 @@ export class XMat4 { } PerspectiveMatrix(n, f, w = NO_INITIAL_VAL, h = NO_INITIAL_VAL) { - if (w == NO_INITIAL_VAL) { + if (w === NO_INITIAL_VAL) { w = Scr.logicw; } - if (h == NO_INITIAL_VAL) { + if (h === NO_INITIAL_VAL) { h = Scr.logich; } let ret = w / (tan((30 * pi) / 180) * 2); @@ -156,48 +156,49 @@ export class XMat4 { const RIGHT = -3; const UP = -1; const DOWN = -3; + const BY_MIDDLE = 2; this.unit(); - if (ox == LEFT) { + if (ox === LEFT) { ox = 0; } - if (ox == MIDDLE) { - ox = realw / 2; + if (ox === MIDDLE) { + ox = realw / BY_MIDDLE; } - if (ox == RIGHT) { + if (ox === RIGHT) { ox = realw; } - if (oy == UP) { + if (oy === UP) { oy = 0; } - if (oy == MIDDLE) { - oy = realh / 2; + if (oy === MIDDLE) { + oy = realh / BY_MIDDLE; } - if (oy == DOWN) { + if (oy === DOWN) { oy = realh; } - if (ox != 0 || oy != 0) { + if (ox !== 0 || oy !== 0) { this.move(-ox, -oy, 0); } - if (sw != 1 || sh != 1) { + if (sw !== 1 || sh !== 1) { this.scale(sw, sh, 1); } - if (ra != 0) { + if (ra !== 0) { this.rotate(0, 0, ra); } - if (mx != 0 || my != 0) { + if (mx !== 0 || my !== 0) { this.move(mx, my, 0); } } Make2DTransformMat_(mx, my, sw, sh, ra, ox = 0, oy = 0) { this.unit(); - if (mx != 0 || my != 0) { + if (mx !== 0 || my !== 0) { this.move(-mx, -my, 0); } - if (ra != 0) { + if (ra !== 0) { this.rotate(0, 0, -ra); } - if (sw != 1 || sh != 1) { + if (sw !== 1 || sh !== 1) { this.scale(1 / sw, 1 / sh, 1); } return this; diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XShader.js b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XShader.js index 50a137d01693f6dcdb2c0b78ea61a89703a19744..b2db72e27a8ee89075cbcc8fe5c7ecb3c7435da9 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XShader.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XShader.js @@ -19,7 +19,7 @@ import { gl } from '../GLFrame.js'; export class XShader { static gi() { - if (XShader.pinstance_ == null) { + if (XShader.pinstance_ === null) { XShader.pinstance_ = new XShader(); } return XShader.pinstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XTexture.js b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XTexture.js index a813d60820010d31259e8a0d2fea71315d6bccf3..ad46024f7775cbb6128c784d2bc9866fe0ac71c5 100644 --- a/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XTexture.js +++ b/framework/tools/hcs-view/hcsWebView/src/engine/graphics/XTexture.js @@ -17,7 +17,7 @@ import { gl } from '../GLFrame.js'; export class XTexture { static gi() { - if (XTexture.pinstance_ == null) { + if (XTexture.pinstance_ === null) { XTexture.pinstance_ = new XTexture(); } return XTexture.pinstance_; @@ -51,7 +51,7 @@ export class XTexture { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } loadTextureFromImage(path, keepdata = false) { - if (path == 'CUSTOM_TEXTURE_1') { + if (path === 'CUSTOM_TEXTURE_1') { var rid = this.ximages.length; var texture = gl.createTexture(); @@ -74,7 +74,7 @@ export class XTexture { return rid; } else { for (let i = 0; i < this.ximages.length; i++) { - if (this.ximages[i]['path'] == path) { + if (this.ximages[i].path === path) { return i; } } @@ -105,62 +105,40 @@ export class XTexture { } } TmpCut(rid, x = 0, y = 0, w = -1, h = -1, ww = 1024, hh = 1024) { - if (this.ximages[rid].stat != 1) { + if (this.ximages[rid].stat !== 1) { return -1; } - if (w == -1) { + if (w === -1) { w = ww; } - if (h == -1) { + if (h === -1) { h = hh; } - this.allCuts[this.tmpCutid] = { - rid: rid, - x: x, - y: y, - w: w, - h: h, - u0: x / ww, - v0: y / hh, - u1: (x + w) / ww, - v1: y / hh, - u2: (x + w) / ww, - v2: (y + h) / hh, - u3: x / ww, - v3: (y + h) / hh, - }; + this.callAllCuts(this.tmpCutid, rid, x, y, w, h, ww, hh); this.tmpCutid += 1; return this.tmpCutid - 1; } + callAllCuts(param, rid, x, y, w, h, ww, hh) { + this.allCuts[param] = { + rid: rid, x: x, y: y, w: w, h: h, u0: x / ww, v0: y / hh, u1: (x + w) / ww, v1: y / hh, + u2: (x + w) / ww, v2: (y + h) / hh, u3: x / ww, v3: (y + h) / hh, + }; + } makeCut(rid, x = 0, y = 0, w = -1, h = -1, ww = -1, hh = -1) { - if (ww == -1) { + if (ww === -1) { ww = this.ximages[rid].w; } - if (hh == -1) { + if (hh === -1) { hh = this.ximages[rid].h; } - if (w == -1) { + if (w === -1) { w = ww; } - if (h == -1) { + if (h === -1) { h = hh; } - this.allCuts[this.aiCutid] = { - rid: rid, - x: x, - y: y, - w: w, - h: h, - u0: x / ww, - v0: y / hh, - u1: (x + w) / ww, - v1: y / hh, - u2: (x + w) / ww, - v2: (y + h) / hh, - u3: x / ww, - v3: (y + h) / hh, - }; + this.callAllCuts(this.aiCutid, rid, x, y, w, h, ww, hh); this.aiCutid += 1; return this.aiCutid - 1; } @@ -209,22 +187,23 @@ export class XTexture { let imgd = this.textCtx.getImageData(0, 0, 1024, 256).data; let w = 1024; let h = size + 5; - let x = 256; - while (x == 256) { + let x = 128; + let lenMax = 128; + while (x === lenMax) { h -= 1; - for (x = 0; x < 128; x++) { + for (x = 0; x < lenMax; x++) { let p = (h * 1024 + x) * 4; - if (imgd[p] != 0) { + if (imgd[p] !== 0) { break; } } } let y = h; - while (y == h) { + while (y === h) { w -= 1; for (y = 0; y < h; y++) { let p = (y * 1024 + w) * 4; - if (imgd[p] != 0) { + if (imgd[p] !== 0) { break; } } @@ -253,12 +232,12 @@ export class XTexture { break; } } - if (off != -1) { + if (off !== -1) { rid = k; break; } } - if (rid == -1) { + if (rid === -1) { rid = this.loadTexture(1024, 1024); this.textImgs[rid] = { mask: 0 }; off = 0; diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/CanvasInput.js b/framework/tools/hcs-view/hcsWebView/src/hcs/CanvasInput.js index f5bf0767506a5ea9f71cb4dde6a33bf023dd76f3..3fde44b9ab07ce4f115734524d104fd495cccd8f 100755 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/CanvasInput.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/CanvasInput.js @@ -42,7 +42,7 @@ class CanvasInput { ci.focus(); ci.addEventListener('keydown', (k) => { - if (k.key == 'Enter') { + if (k.key === 'Enter') { if (k.shiftKey) { } else { CanvasInput.Hide(); diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/Generator.js b/framework/tools/hcs-view/hcsWebView/src/hcs/Generator.js index 908a93a649e37330151f0bda211678ce35962b19..6827272cb65b68ff9310eff457edd79575a30504 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/Generator.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/Generator.js @@ -36,15 +36,15 @@ class Generator { astToObjConfigNodeType(nodeType, obj, node) { if ( - nodeType == this.DATA_NODES_INHERIT || - nodeType == this.CLASS_NODES_COPY || - nodeType == this.CLASS_NODES_REFERENCE + nodeType === this.DATA_NODES_INHERIT || + nodeType === this.CLASS_NODES_COPY || + nodeType === this.CLASS_NODES_REFERENCE ) { obj.ref_ = node.refNodePath_; } else if ( - nodeType != this.DATA_NODES_NOT_INHERIT && - nodeType != this.CLASS_NODES_DELETION && - nodeType != this.CLASS_NODES_TEMPLETE + nodeType !== this.DATA_NODES_NOT_INHERIT && + nodeType !== this.CLASS_NODES_DELETION && + nodeType !== this.CLASS_NODES_TEMPLETE ) { NapiLog.logError('unknow node type'); } @@ -53,7 +53,7 @@ class Generator { astToObjConfigNode(ret, child, node) { ret.value_ = []; child = node.child_; - while (child != null) { + while (child !== undefined) { ret.value_.push(this.astToObj(child, ret)); child = child.next_; } @@ -91,7 +91,7 @@ class Generator { case DataType.ARRAY: ret.value_ = []; child = node.child_; - while (child != null) { + while (child !== undefined) { ret.value_.push(this.astToObj(child, ret)); child = child.next_; } @@ -105,7 +105,7 @@ class Generator { ret.value_ = null; break; case DataType.BOOL: - if (node.integerValue_ == 0) { + if (node.integerValue_ === 0) { ret.value_ = false; } else { @@ -172,17 +172,17 @@ class Generator { objToHcsConfigNode(node, deep) { let ret = ''; - if (node.nodeType_ == this.DATA_NODES_NOT_INHERIT) { + if (node.nodeType_ === this.DATA_NODES_NOT_INHERIT) { ret = this.makeSpace(deep) + node.name_ + ' {\n'; - } else if (node.nodeType_ == this.CLASS_NODES_COPY) { + } else if (node.nodeType_ === this.CLASS_NODES_COPY) { ret = this.makeSpace(deep) + node.name_ + ' : ' + node.ref_ + ' {\n'; - } else if (node.nodeType_ == this.CLASS_NODES_REFERENCE) { + } else if (node.nodeType_ === this.CLASS_NODES_REFERENCE) { ret = this.makeSpace(deep) + node.name_ + ' : &' + node.ref_ + ' {\n'; - } else if (node.nodeType_ == this.CLASS_NODES_DELETION) { + } else if (node.nodeType_ === this.CLASS_NODES_DELETION) { ret = this.makeSpace(deep) + node.name_ + ' : delete {\n'; - } else if (node.nodeType_ == this.CLASS_NODES_TEMPLETE) { + } else if (node.nodeType_ === this.CLASS_NODES_TEMPLETE) { ret = this.makeSpace(deep) + 'template ' + node.name_ + ' {\n'; - } else if (node.nodeType_ == this.DATA_NODES_INHERIT) { + } else if (node.nodeType_ === this.DATA_NODES_INHERIT) { ret = this.makeSpace(deep) + node.name_ + ' :: ' + node.ref_ + ' {\n'; } else { NapiLog.logError('unknow node type'); @@ -250,7 +250,7 @@ class Generator { Generator.pInstance_ = null; Generator.gi = function () { - if (Generator.pInstance_ == null) { + if (Generator.pInstance_ === null) { Generator.pInstance_ = new Generator(); } return Generator.pInstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/ModifyNode.js b/framework/tools/hcs-view/hcsWebView/src/hcs/ModifyNode.js index d2926d01f42887d35665a4368f521ac6b99944ff..b0b8e6cd91fd81ac43cc42c5f0a76c78b8d0620b 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/ModifyNode.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/ModifyNode.js @@ -25,7 +25,7 @@ function getParent(node, dest, parent) { function isNameRepeat(node, name) { for (let i in node.value_) { - if (node.value_[i].name_ == name) { + if (node.value_[i].name_ === name) { return true; } } @@ -34,7 +34,7 @@ function isNameRepeat(node, name) { ModifyNode.modifyName = function (files, root, node, name) { let parent = getParent(root, node, null); - if (parent == null) { + if (parent === null) { NapiLog.logError("Can't change root node name"); return false; } @@ -44,7 +44,7 @@ ModifyNode.modifyName = function (files, root, node, name) { ModifyNode.modifyNodeType = function (files, root, node, type) { let parent = getParent(root, node, null); - if (parent == null) { + if (parent === null) { NapiLog.logError("Can't change root node type"); return false; } @@ -99,12 +99,12 @@ ModifyNode.addChildNode = function (root, node) { ModifyNode.deleteNode = function (node) { let parent = node.parent_; - if (parent == null) { + if (parent === null) { NapiLog.logError('不能删除root节点'); return false; } for (let i in parent.value_) { - if (parent.value_[i] == node) { + if (parent.value_[i] === node) { parent.value_.splice(i, 1); return; } @@ -114,38 +114,41 @@ ModifyNode.deleteNode = function (node) { ModifyNode.getInheritList = function (root, node) { let ret = []; let parent = getParent(root, node, null); - if (parent == null) return ret; + if (parent === null) { + return ret; + } + for (let i in parent.value_) { let pn = parent.value_[i]; - if (pn.type_ == DataType.NODE && pn.nodeType_ == NodeType.TEMPLETE) { + if (pn.type_ === DataType.NODE && pn.nodeType_ === NodeType.TEMPLETE) { ret.push(pn); } } let ps = [parent]; while (true) { let pp = getParent(root, parent, null); - if (pp == null) { + if (pp === null) { break; } ps.splice(0, 0, pp); } let ptemp = null; for (let i in ps) { - if (ps[i].nodeType_ == NodeType.INHERIT) { + if (ps[i].nodeType_ === NodeType.INHERIT) { ptemp = NodeTools.findChildByName(ptemp, ps[i].ref_); - } else if (ptemp == null) { + } else if (ptemp === null) { ptemp = ps[i]; } else { ptemp = NodeTools.findChildByName(ptemp, ps[i].name_); } - if (ptemp == null) { + if (ptemp === null) { break; } } - if (ptemp != null && ptemp != parent) { + if (ptemp !== null && ptemp !== parent) { for (let i in ptemp.value_) { let pn = ptemp.value_[i]; - if (pn.type_ == DataType.NODE && pn.nodeType_ == NodeType.TEMPLETE) { + if (pn.type_ === DataType.NODE && pn.nodeType_ === NodeType.TEMPLETE) { ret.push(pn); } } @@ -163,16 +166,16 @@ ModifyNode.getInheritNameList = function (root, node) { }; ModifyNode.getInheritTemplete = function (root, node) { let parent = getParent(root, node, null); - if (parent == null) { + if (parent === null) { return null; } let ilist = ModifyNode.getInheritList(root, node); for (let i in ilist) { - if (parent.nodeType_ == NodeType.TEMPLETE) { - if (parent.ref_ == ilist[i].name_) { + if (parent.nodeType_ === NodeType.TEMPLETE) { + if (parent.ref_ === ilist[i].name_) { return ilist[i]; } - } else if (parent.name_ == ilist[i].name_) { + } else if (parent.name_ === ilist[i].name_) { return ilist[i]; } } diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/NodeTools.js b/framework/tools/hcs-view/hcsWebView/src/hcs/NodeTools.js index 4c7309e82707d4e591320f7ac96d042dc3112f3a..1cacbd0eef3cc0806ab2a4dd1a37619454f1783d 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/NodeTools.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/NodeTools.js @@ -16,7 +16,13 @@ const { NapiLog } = require('./NapiLog'); const re = require('./re'); -var DataType = { +const MAX_DECIMAL = 10; +const MAX_BINARY = 2; +const MAX_OCTAL = 8; +const MAX_HEXADECIMAL = 16; +const STAT_SIZE = 100; + +const DataType = { INT8: 1, INT16: 2, INT32: 3, @@ -29,7 +35,7 @@ var DataType = { DELETE: 10, BOOL: 11, }; -var NodeType = { +const NodeType = { DATA: 0, COPY: 1, REFERENCE: 2, @@ -41,13 +47,15 @@ var NodeType = { class NodeTools {} function getRoot(node) { - while (node.parent_ != undefined) node = node.parent_; + while (node.parent_ !== undefined) { + node = node.parent_; + } return node; } NodeTools.isElders = function (node, elders) { - while (node != undefined) { - if (node == elders) { + while (node !== undefined) { + if (node === elders) { return true; } node = node.parent_; @@ -56,20 +64,20 @@ NodeTools.isElders = function (node, elders) { }; NodeTools.getPathByNode = function (node, expandRef = true) { - if (node == null) { + if (node === null) { return ''; } let ret = node.name_; - while (node != null && node.parent_ != undefined) { + while (node !== null && node.parent_ !== undefined) { node = node.parent_; - if (expandRef && node.nodeType_ == NodeType.REFERENCE) { + if (expandRef && node.nodeType_ === NodeType.REFERENCE) { if (node.ref_.startsWith(getRoot(node).name_)) { node = NodeTools.getNodeByPath(getRoot(node), node.ref_); } else { node = NodeTools.getNodeByPath(node.parent_, node.ref_); } } - if (node != null) { + if (node !== null) { ret = node.name_ + '.' + ret; } } @@ -77,12 +85,12 @@ NodeTools.getPathByNode = function (node, expandRef = true) { }; NodeTools.getNodeByPath = function (node, path) { let ps = path.split('.'); - if (ps[0] == 'root') { + if (ps[0] === 'root') { ps.shift(); } for (let p in ps) { node = NodeTools.findChildByName(node, ps[p]); - if (node == null) { + if (node === null) { return null; } } @@ -91,12 +99,12 @@ NodeTools.getNodeByPath = function (node, path) { NodeTools.lookupInherit = function (node) { if ( - node.type_ == DataType.NODE && - node.nodeType_ == NodeType.INHERIT && - node.parent_.nodeType_ == NodeType.INHERIT + node.type_ === DataType.NODE && + node.nodeType_ === NodeType.INHERIT && + node.parent_.nodeType_ === NodeType.INHERIT ) { let p = NodeTools.lookupInherit(node.parent_); - if (p == null) { + if (p === null) { return p; } return NodeTools.findChildByName(p, node.ref_); @@ -107,27 +115,30 @@ NodeTools.lookupInherit = function (node) { NodeTools.lookup = function (node) { let refname; if ( - node.type_ == DataType.NODE && - (node.nodeType_ == NodeType.COPY || - node.nodeType_ == NodeType.REFERENCE || - node.nodeType_ == NodeType.INHERIT) - ) + node.type_ === DataType.NODE && + (node.nodeType_ === NodeType.COPY || + node.nodeType_ === NodeType.REFERENCE || + node.nodeType_ === NodeType.INHERIT) + ) { refname = node.ref_; + } else if ( - node.type_ == DataType.ATTR && - node.value_.type_ == DataType.REFERENCE - ) + node.type_ === DataType.ATTR && + node.value_.type_ === DataType.REFERENCE + ) { refname = node.value_.value_; + } else { return null; } - if (refname.indexOf('.') >= 0) + if (refname.indexOf('.') >= 0) { return NodeTools.getNodeByPath(getRoot(node), refname); + } let ret = NodeTools.findChildByName(node.parent_, refname); - if (ret == null) { + if (ret === null) { if ( - node.type_ == DataType.NODE && - node.nodeType_ == NodeType.INHERIT && - node.parent_.nodeType_ == NodeType.INHERIT + node.type_ === DataType.NODE && + node.nodeType_ === NodeType.INHERIT && + node.parent_.nodeType_ === NodeType.INHERIT ) { ret = NodeTools.lookupInherit(node); } @@ -136,7 +147,7 @@ NodeTools.lookup = function (node) { }; NodeTools.recursionNode = function (node, callback) { - if (node.type_ == DataType.NODE) { + if (node.type_ === DataType.NODE) { callback(node); for (let n in node.value_) { NodeTools.recursionNode(node.value_[n], callback); @@ -148,7 +159,7 @@ NodeTools.recursionAll = function (node, callback, isForward) { if (isForward) { ret = callback(node); } - if (node.type_ == DataType.NODE) { + if (node.type_ === DataType.NODE) { for (let i = 0; i < node.value_.length; i++) { if (NodeTools.recursionAll(node.value_[i], callback, isForward)) { i--; @@ -178,18 +189,18 @@ NodeTools.redefineCheck = function (node) { }; function separate(node) { let pn = node.parent_; - if (pn == null) { + if (pn === null) { return; } for (let i in pn.value_) { - if (pn.value_[i] == node) { + if (pn.value_[i] === node) { pn.value_.splice(i, 1); } } } NodeTools.findChildByName = function (node, name) { for (let i in node.value_) { - if (node.value_[i].name_ == name) { + if (node.value_[i].name_ === name) { return node.value_[i]; } } @@ -203,7 +214,7 @@ NodeTools.copyNode = function (node, parent) { lineno_: node.lineno_, parent_: parent, }; - if (node.raw_ != undefined) { + if (node.raw_ !== undefined) { ret.raw_ = node.raw_; } switch (node.type_) { @@ -251,7 +262,7 @@ NodeTools.copyNode = function (node, parent) { }; function makeError(node, errStr) { - if (node.raw_ != undefined) { + if (node.raw_ !== undefined) { node.raw_.errMsg_ = errStr; } } @@ -259,8 +270,8 @@ NodeTools.nodeNestCheck = function (node) { NodeTools.recursionAll( node, (pn) => { - if (pn.type_ == DataType.NODE) { - if (pn.nodeType_ == NodeType.COPY && pn.raw_.errMsg_ == null) { + if (pn.type_ === DataType.NODE) { + if (pn.nodeType_ === NodeType.COPY && pn.raw_.errMsg_ === null) { pn.raw_.errMsg_ = '有Copy的嵌套' + pn.raw_.lineno_; } } @@ -271,25 +282,25 @@ NodeTools.nodeNestCheck = function (node) { }; NodeTools.recursionCopyAndReferenceNodes = function (pn) { let ref = NodeTools.lookup(pn); - if (ref == null) { + if (ref === null) { NapiLog.logError( 'reference not exist' + NodeTools.getPathByNode(pn) + ':' + pn.ref_ ); - if (pn.nodeType_ == NodeType.COPY) { + if (pn.nodeType_ === NodeType.COPY) { makeError(pn, pn.name_ + ' 复制目标没找到!'); } else { makeError(pn, pn.name_ + ' 引用目标没找到!'); } return false; - } else if (ref.nodeType_ == NodeType.TEMPLETE) { - if (pn.nodeType_ == NodeType.COPY) { + } else if (ref.nodeType_ === NodeType.TEMPLETE) { + if (pn.nodeType_ === NodeType.COPY) { makeError(pn, pn.name_ + ' 复制目标不能为模板节点!'); } else { makeError(pn, pn.name_ + ' 引用目标不能为模板节点!'); } return false; - } else if (ref.nodeType_ == NodeType.DELETE) { - if (pn.nodeType_ == NodeType.COPY) { + } else if (ref.nodeType_ === NodeType.DELETE) { + if (pn.nodeType_ === NodeType.COPY) { makeError(pn, pn.name_ + ' 复制目标不能为删除节点!'); } else { makeError(pn, pn.name_ + ' 引用目标不能为删除节点!'); @@ -299,14 +310,14 @@ NodeTools.recursionCopyAndReferenceNodes = function (pn) { NapiLog.logError( 'circular reference' + NodeTools.getPathByNode(pn) + ':' + pn.ref_ ); - if (pn.nodeType_ == NodeType.COPY) { + if (pn.nodeType_ === NodeType.COPY) { makeError(pn, pn.name_ + ' 循环复制!'); } else { makeError(pn, pn.name_ + ' 循环引用!'); } return false; - } else if (pn.nodeType_ == NodeType.COPY) { - if (ref.nodeType_ == NodeType.COPY) { + } else if (pn.nodeType_ === NodeType.COPY) { + if (ref.nodeType_ === NodeType.COPY) { pn.raw_.errMsg_ = '有Copy的嵌套:' + pn.raw_.lineno_; } pn.nodeType_ = NodeType.DATA; @@ -315,7 +326,7 @@ NodeTools.recursionCopyAndReferenceNodes = function (pn) { NodeTools.merge(tref, pn); pn.value_ = tref.value_; return false; - } else if (pn.nodeType_ == NodeType.REFERENCE) { + } else if (pn.nodeType_ === NodeType.REFERENCE) { pn.nodeType_ = ref.nodeType_; pn.name_ = ref.name_; pn.ref_ = ref.ref_; @@ -328,56 +339,56 @@ NodeTools.recursionCopyAndReferenceNodes = function (pn) { NodeTools.checkInheritNode = function (pn) { let ref = NodeTools.lookup(pn); - if (ref == null) { + if (ref === null) { makeError(pn, pn.name_ + ' 继承目标找不到!'); - } else if (ref.type_ != DataType.NODE) { + } else if (ref.type_ !== DataType.NODE) { makeError(pn, pn.name_ + ' 不能继承属性!'); - } else if (ref.nodeType_ == NodeType.REFERENCE) { + } else if (ref.nodeType_ === NodeType.REFERENCE) { makeError(pn, pn.name_ + ' 不能继承引用类节点!'); - } else if (ref.nodeType_ == NodeType.DELETE) { + } else if (ref.nodeType_ === NodeType.DELETE) { makeError(pn, pn.name_ + ' 不能继承删除类节点!'); - } else if (ref.nodeType_ == NodeType.DATA) { + } else if (ref.nodeType_ === NodeType.DATA) { makeError(pn, pn.name_ + ' 不能继承数据类节点!'); - } else if (ref.nodeType_ == NodeType.INHERIT) { + } else if (ref.nodeType_ === NodeType.INHERIT) { makeError(pn, pn.name_ + ' 不能继承继承类节点!'); - } else if (ref.nodeType_ == NodeType.COPY) { + } else if (ref.nodeType_ === NodeType.COPY) { makeError(pn, pn.name_ + ' 不能继承复制类节点!'); } }; NodeTools.nodeExpand = function (node) { NodeTools.recursionAll(node, (pn) => { - if (pn.type_ == DataType.NODE) { - if (pn.nodeType_ == NodeType.DELETE) { + if (pn.type_ === DataType.NODE) { + if (pn.nodeType_ === NodeType.DELETE) { separate(pn); return true; } - if (pn.nodeType_ == NodeType.COPY || pn.nodeType_ == NodeType.REFERENCE) { + if (pn.nodeType_ === NodeType.COPY || pn.nodeType_ === NodeType.REFERENCE) { return NodeTools.recursionCopyAndReferenceNodes(pn); } - if (pn.nodeType_ == NodeType.INHERIT) { + if (pn.nodeType_ === NodeType.INHERIT) { NodeTools.checkInheritNode(pn); } - } else if (pn.type_ == DataType.ATTR) { - if (pn.value_.type_ == DataType.DELETE) { + } else if (pn.type_ === DataType.ATTR) { + if (pn.value_.type_ === DataType.DELETE) { separate(pn); return true; } - if (pn.value_.type_ == DataType.REFERENCE) { + if (pn.value_.type_ === DataType.REFERENCE) { let ref = NodeTools.lookup(pn); - if (ref == null || ref.type_ != DataType.NODE || ref.nodeType_ == NodeType.REFERENCE || - ref.nodeType_ == NodeType.TEMPLETE || ref.nodeType_ == NodeType.DELETE + if (ref === null || ref.type_ !== DataType.NODE || ref.nodeType_ === NodeType.REFERENCE || + ref.nodeType_ === NodeType.TEMPLETE || ref.nodeType_ === NodeType.DELETE ) { NapiLog.logError('reference invalid node' + NodeTools.getPathByNode(pn) + ':' + pn.value_.value_); - if (ref == null) { + if (ref === null) { makeError(pn, pn.name_ + ' 找不到引用目标!'); - } else if (ref.type_ != DataType.NODE) { + } else if (ref.type_ !== DataType.NODE) { makeError(pn, pn.name_ + ' 不能引用属性!'); - } else if (ref.nodeType_ == NodeType.REFERENCE) { + } else if (ref.nodeType_ === NodeType.REFERENCE) { makeError(pn, pn.name_ + ' 不能引用引用类节点!'); - } else if (ref.nodeType_ == NodeType.TEMPLETE) { + } else if (ref.nodeType_ === NodeType.TEMPLETE) { makeError(pn, pn.name_ + ' 不能引用模板类节点!'); - } else if (ref.nodeType_ == NodeType.DELETE) { + } else if (ref.nodeType_ === NodeType.DELETE) { makeError(pn, pn.name_ + ' 不能引用删除类节点!'); } } else { @@ -394,17 +405,17 @@ NodeTools.inheritExpand = function (node) { node, (pn) => { let tt = re.match('^[a-zA-Z_]{1}[a-zA-Z_0-9]*$', pn.name_); - if (tt == null) { + if (tt === null) { makeError(pn, pn.name_ + ' 名字不合规范!'); } - if (pn.type_ != DataType.NODE) { + if (pn.type_ !== DataType.NODE) { return false; } - if (pn.nodeType_ != NodeType.INHERIT) { + if (pn.nodeType_ !== NodeType.INHERIT) { return false; } let inherit = NodeTools.lookup(pn); - if (inherit == null) { + if (inherit === null) { NapiLog.logError( 'inherit invalid node: ' + NodeTools.getPathByNode(pn) + ':' + pn.ref_ ); @@ -421,30 +432,30 @@ NodeTools.inheritExpand = function (node) { ); }; NodeTools.merge = function (node1, node2) { - if (node2 == null) { + if (node2 === null) { return true; } - if (node2.raw_ == undefined) { + if (node2.raw_ === undefined) { node1.raw_ = node2; } else { node1.raw_ = node2.raw_; } - if (node1.type_ == DataType.NODE) { - if (node1.name_ != node2.name_) { + if (node1.type_ === DataType.NODE) { + if (node1.name_ !== node2.name_) { return false; } node1.nodeType_ = node2.nodeType_; - if (node2.nodeType_ == NodeType.INHERIT || node2.nodeType_ == NodeType.REFERENCE || node2.nodeType_ == NodeType.COPY) { + if (node2.nodeType_ === NodeType.INHERIT || node2.nodeType_ === NodeType.REFERENCE || node2.nodeType_ === NodeType.COPY) { node1.ref_ = node2.ref_; } - if (node1.value_ == undefined) { + if (node1.value_ === undefined) { node1.value_ = []; } for (let i in node2.value_) { let child2 = node2.value_[i]; let child1 = NodeTools.findChildByName(node1, child2.name_); - if (child1 == null) { + if (child1 === null) { child1 = { type_: child2.type_, name_: child2.name_, @@ -452,14 +463,14 @@ NodeTools.merge = function (node1, node2) { parent_: node1, }; node1.value_.push(child1); - } else if (child1.type_ != child2.type_) { + } else if (child1.type_ !== child2.type_) { child2.raw_.errMsg_ = '所修改的子节的类型和父节点类型不同:' + child2.raw_.lineno_; return false; } NodeTools.merge(child1, child2); } - } else if (node1.type_ == DataType.ATTR) { + } else if (node1.type_ === DataType.ATTR) { node1.value_ = NodeTools.copyNode(node2.value_, node1); } return true; @@ -467,16 +478,16 @@ NodeTools.merge = function (node1, node2) { NodeTools.jinZhi10ToX = function (num, jinzhi) { let ret; switch (jinzhi) { - case 2: + case MAX_BINARY: ret = '0b'; break; - case 8: + case MAX_OCTAL: ret = '0'; break; - case 10: + case MAX_DECIMAL: ret = ''; break; - case 16: + case MAX_HEXADECIMAL: ret = '0x'; break; default: @@ -486,32 +497,32 @@ NodeTools.jinZhi10ToX = function (num, jinzhi) { return ret + num.toString(jinzhi); }; NodeTools.jinZhiXTo10 = function (s) { - if (s == null || s.length == 0) { - return [0, 10]; + if (s === null || s.length === 0) { + return [0, MAX_DECIMAL]; } s = s.trim(); if (!isFinite(s)) { - return [undefined, 10]; + return [undefined, MAX_DECIMAL]; } try { - if (s[0] == '0') { - if (s.length == 1) { - return [BigInt(s), 10]; - } else if (s[1] == 'b' || s[1] == 'B') { - return [BigInt(s), 2]; - } else if (s[1] == 'x' || s[1] == 'X') { - return [BigInt(s), 16]; + if (s[0] === '0') { + if (s.length === 1) { + return [BigInt(s), MAX_DECIMAL]; + } else if (s[1] === 'b' || s[1] === 'B') { + return [BigInt(s), MAX_BINARY]; + } else if (s[1] === 'x' || s[1] === 'X') { + return [BigInt(s), MAX_HEXADECIMAL]; } else { - return [BigInt('0o' + s.substring(1)), 8]; + return [BigInt('0o' + s.substring(1)), MAX_OCTAL]; } } else { - return [BigInt(s), 10]; + return [BigInt(s), MAX_DECIMAL]; } } catch (ex) { NapiLog.logError(ex.message); - return [undefined, 10]; + return [undefined, MAX_DECIMAL]; } }; @@ -522,9 +533,9 @@ NodeTools.createNewNode = function (type, name, value, nodetype) { ret.value_ = value; ret.isOpen_ = true; if (type < DataType.STRING) { - ret.jinzhi_ = 10; + ret.jinzhi_ = MAX_DECIMAL; } - if (type == DataType.NODE) { + if (type === DataType.NODE) { ret.nodeType_ = nodetype; } return ret; @@ -541,14 +552,14 @@ NodeTools.arrayToString = function (node, maxw) { for (let d in node.value_) { if (d > 0) { line += ','; - if (maxw != undefined) { + if (maxw !== undefined) { if (line.length >= maxw) { ret += line + '\n'; line = ''; } } } - if (type == DataType.STRING) { + if (type === DataType.STRING) { line += '"' + node.value_[d].value_ + '"'; } else { line += NodeTools.jinZhi10ToX(node.value_[d].value_, node.value_[d].jinzhi_); @@ -570,18 +581,18 @@ NodeTools.stringToArray = function (s) { let p = 0; let stat = 0; let v; - while (p < s.length && stat < 100) { + while (p < s.length && stat < STAT_SIZE) { switch (stat) { case 0: - if (s[p] == '"') { + if (s[p] === '"') { stat = 1; v = ''; - } else if (s[p] != ' ') { - stat = 100; + } else if (s[p] !== ' ') { + stat = STAT_SIZE; } break; case 1: - if (s[p] == '"') { + if (s[p] === '"') { stat = 2; ret.push(NodeTools.createNewNode(type, '', v)); } else { @@ -589,11 +600,11 @@ NodeTools.stringToArray = function (s) { } break; case 2: - if (s[p] == ',') { + if (s[p] === ',') { stat = 0; } - else if (s[p] != ' ') { - stat = 100; + else if (s[p] !== ' ') { + stat = STAT_SIZE; } break; } @@ -609,7 +620,7 @@ NodeTools.stringToArray = function (s) { function stringToArrayWithQuote(ret, type, arr) { for (let i in arr) { let num = NodeTools.jinZhiXTo10(arr[i]); - if (num[0] == undefined) { + if (num[0] === undefined) { num[0] = 0; } let attr = NodeTools.createNewNode(type, '', num[0]); @@ -631,7 +642,7 @@ function stringToArrayWithQuote(ret, type, arr) { type = DataType.INT64; } } - if (type != DataType.INT8) { + if (type !== DataType.INT8) { for (let i in ret) { ret[i].type_ = type; } diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/ast.js b/framework/tools/hcs-view/hcsWebView/src/hcs/ast.js index e8444614bed54d8c32d9945c442acacfd32163d7..f2f9aa5e8f870bc00498014098ff98c161ea5dbe 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/ast.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/ast.js @@ -60,18 +60,18 @@ var UINT64_MAX = 0xffffffffffffffff; class AstObject { constructor(name, type, value, bindToken, jinzhi) { let callType = Object.prototype.toString.call(name); - if (callType == '[object Object]') { + if (callType === '[object Object]') { this.constructorSis(name.name_, name.type_, name.stringValue_); this.integerValue_ = name.integerValue_; - } else if (callType == '[object String]') { - if (Object.prototype.toString.call(value) == '[object Number]') { - if (Object.prototype.toString.call(bindToken) == '[object Object]') { + } else if (callType === '[object String]') { + if (Object.prototype.toString.call(value) === '[object Number]' || Object.prototype.toString.call(value) === '[object BigInt]') { + if (Object.prototype.toString.call(bindToken) === '[object Object]') { this.constructorSiit(name, type, value, bindToken, jinzhi); } else { this.constructorSii(name, type, value, jinzhi); } - } else if (Object.prototype.toString.call(value) == '[object String]') { - if (Object.prototype.toString.call(bindToken) == '[object Object]') { + } else if (Object.prototype.toString.call(value) === '[object String]') { + if (Object.prototype.toString.call(bindToken) === '[object Object]') { this.constructorSist(name, type, value, bindToken); } else { this.constructorSis(name, type, value); @@ -136,13 +136,13 @@ class AstObject { } } addChild(childObj) { - if (childObj == null) { + if (childObj === null || childObj === undefined) { return false; } - if (this.child_ == null) { + if (this.child_ === null || this.child_ === undefined) { // this.child_ = childObj; let childNext = childObj; - while (childNext != null) { + while (childNext !== null && childNext !== undefined) { childNext.parent_ = this; childNext = childNext.next_; } @@ -154,20 +154,20 @@ class AstObject { } addPeer(peerObject) { - if (peerObject == null) { + if (peerObject === null || peerObject === undefined) { return false; } - if (this == peerObject) { + if (this === peerObject) { NapiLog.logError('add self as peer'); return false; } - if (this.next_ == null) { + if (this.next_ === null || this.next_ === undefined) { this.next_ = peerObject; } else { let lastNode = this.next_; - while (lastNode.next_ != null) { + while (lastNode.next_ !== null && lastNode.next_ !== undefined) { lastNode = lastNode.next_; } lastNode.next_ = peerObject; @@ -183,14 +183,14 @@ class AstObject { } merge(srcObj) { - if (srcObj.name_ != this.name_) { + if (srcObj.name_ !== this.name_) { NapiLog.logError( this.sourceInfo() + 'merge different node to' + srcObj.sourceInfo() ); return false; } - if (srcObj.type_ != this.type_) { + if (srcObj.type_ !== this.type_) { NapiLog.logError( this.sourceInfo() + 'conflict type with ' + srcObj.sourceInfo() ); @@ -205,7 +205,7 @@ class AstObject { return true; } copy(src, overwrite) { - if (src == null) { + if (src === null) { return false; } @@ -239,8 +239,8 @@ class AstObject { lookup(name, type) { let peer = this.child_; - while (peer != null) { - if (peer.name_ == name && (type == 0 || peer.type_ == type)) { + while (peer !== null) { + if (peer.name_ === name && (type === 0 || peer.type_ === type)) { return peer; } @@ -258,28 +258,28 @@ class AstObject { } isNode() { - return this.type_ == ObjectType.PARSEROP_CONFNODE; + return this.type_ === ObjectType.PARSEROP_CONFNODE; } isTerm() { - return this.type_ == ObjectType.PARSEROP_CONFTERM; + return this.type_ === ObjectType.PARSEROP_CONFTERM; } isArray() { - return this.type_ == ObjectType.PARSEROP_ARRAY; + return this.type_ === ObjectType.PARSEROP_ARRAY; } separate() { if (this.parent_ == null) { return; } - if (this.parent_.child_ == this) { + if (this.parent_.child_ === this) { this.parent_.child_ = this.next_; this.next_ = null; return; } let pre = this.parent_.child_; - while (pre != null) { - if (pre.next_ == this) { + while (pre !== null) { + if (pre.next_ === this) { let tmp = this.next_; this.next_ = null; pre.next_ = tmp; @@ -339,8 +339,8 @@ class AstObject { } isElders(child) { let p = child; - while (p != null) { - if (p == this) { + while (p !== null) { + if (p === this) { return true; } p = p.parent_; @@ -354,14 +354,14 @@ class AstObject { class ConfigNode extends AstObject { constructor(name, nodeType, refName) { - if (Object.prototype.toString.call(name) == '[object String]') { + if (Object.prototype.toString.call(name) === '[object String]') { super(name, ObjectType.PARSEROP_CONFNODE, ''); this.refNodePath_ = refName; this.nodeType_ = nodeType; this.inheritIndex_ = 0; this.inheritCount_ = 0; this.templateSignNum_ = 0; - } else if (Object.prototype.toString.call(nodeType) == '[object Number]') { + } else if (Object.prototype.toString.call(nodeType) === '[object Number]') { super(name.strval, ObjectType.PARSEROP_CONFNODE, 0, name); this.refNodePath_ = refName; this.nodeType_ = nodeType; @@ -377,7 +377,7 @@ class ConfigNode extends AstObject { this.templateSignNum_ = 0; let child = name.child_; - while (child != null) { + while (child !== null) { super.addChild(AstObjectFactory.build(child)); child = child.next(); } @@ -406,10 +406,10 @@ class ConfigNode extends AstObject { return this.refNodePath_; } merge(srcObj) { - if (srcObj == null) { + if (srcObj === null) { return true; } - if (!srcObj.isNode() || srcObj.name() != this.name_) { + if (!srcObj.isNode() || srcObj.name() !== this.name_) { NapiLog.logError( sourceInfo() + 'merge conflict type with ' + srcObj.sourceInfo() ); @@ -417,7 +417,7 @@ class ConfigNode extends AstObject { } let srcNode = srcObj; - if (srcNode.getNodeType() == TokenType.DELETE) { + if (srcNode.getNodeType() === TokenType.DELETE) { srcObj.separate(); this.separate(); return true; @@ -427,10 +427,10 @@ class ConfigNode extends AstObject { this.refNodePath_ = srcNode.refNodePath_; let childSrc = srcObj.child(); - while (childSrc != null) { + while (childSrc !== null) { let childSrcNext = childSrc.next(); let childDst = this.lookup(childSrc.name(), childSrc.type()); - if (childDst == null) { + if (childDst === null) { childSrc.separate(); this.addChild(childSrc); } else if (!childDst.merge(childSrc)) { @@ -449,9 +449,9 @@ class ConfigNode extends AstObject { hasDuplicateChild() { let symMap = {}; let child = this.child_; - while (child != null) { + while (child !== null) { let sym = symMap[child.name()]; - if (sym != undefined) { + if (sym !== undefined) { NapiLog.logError( child.sourceInfo() + 'redefined, first definition at ' + @@ -466,7 +466,7 @@ class ConfigNode extends AstObject { return false; } inheritExpand(refObj) { - if (refObj == null) { + if (refObj === null) { NapiLog.logError(sourceInfo() + 'inherit invalid node: ' + refNodePath_); return false; } @@ -484,7 +484,7 @@ class ConfigNode extends AstObject { return true; } refExpand(refObj) { - if (this.nodeType_ == NodeRefType.NODE_DELETE) { + if (this.nodeType_ === NodeRefType.NODE_DELETE) { this.separate(); return true; } @@ -497,9 +497,9 @@ class ConfigNode extends AstObject { } let ret = true; - if (this.nodeType_ == NodeRefType.NODE_REF) { + if (this.nodeType_ === NodeRefType.NODE_REF) { ret = this.nodeRefExpand(refObj); - } else if (nodeType_ == NodeRefType.NODE_COPY) { + } else if (nodeType_ === NodeRefType.NODE_COPY) { ret = nodeCopyExpand(refObj); } @@ -507,9 +507,9 @@ class ConfigNode extends AstObject { } copy(src, overwrite) { let child = src.child(); - while (child != null) { + while (child !== null) { let dst = this.lookup(child.name(), child.type()); - if (dst == null) { + if (dst === null) { this.addChild(AstObjectFactory.build(child)); } else if (!dst.copy(child, overwrite)) { return false; @@ -523,7 +523,7 @@ class ConfigNode extends AstObject { return super.move(src); } nodeRefExpand(ref) { - if (ref == null) { + if (ref === null) { NapiLog.logError( sourceInfo() + "reference node '" + refNodePath_ + "' not exist" ); @@ -532,7 +532,7 @@ class ConfigNode extends AstObject { return ref.move(this); } nodeCopyExpand(ref) { - if (ref == null) { + if (ref === null) { NapiLog.logError( sourceInfo() + "copy node '" + refNodePath_ + "' not exist" ); @@ -543,9 +543,9 @@ class ConfigNode extends AstObject { } compare(other) { let objChild = this.child_; - while (objChild != null) { + while (objChild !== null) { let baseObj = this.lookup(objChild.name(), objChild.type()); - if (baseObj == null) { + if (baseObj === null) { NapiLog.logError( objChild.sourceInfo() + 'not in template node: ' + other.sourceInfo() ); @@ -578,28 +578,28 @@ class ConfigNode extends AstObject { class ConfigTerm extends AstObject { constructor(name, value) { - if (Object.prototype.toString.call(name) == '[object String]') { + if (Object.prototype.toString.call(name) === '[object String]') { super(name, ObjectType.PARSEROP_CONFTERM, 0); this.signNum_ = 0; this.child_ = value; - if (value != null) { + if (value !== null) { value.this.setParent(this); } } else if ( - Object.prototype.toString.call(value) == '[object Object]' || - Object.prototype.toString.call(value) == '[object Null]' + Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Null]' ) { super(name.strval, ObjectType.PARSEROP_CONFTERM, 0, name); this.signNum_ = 0; this.child_ = value; - if (value != null) { + if (value !== null) { value.this.setParent(this); } } else { super(name.name_, ObjectType.PARSEROP_CONFTERM, 0); this.signNum_ = 0; this.child_ = value; - if (value != null) { + if (value !== null) { value.this.setParent(this); } super.addChild(AstObjectFactory.build(name.child_)); @@ -625,21 +625,21 @@ class ConfigTerm extends AstObject { } refExpand(refObj) { - if (child_.type() == ObjectType.PARSEROP_DELETE) { + if (child_.type() === ObjectType.PARSEROP_DELETE) { this.separate(); return true; } - if (child_.type() != ObjectType.PARSEROP_NODEREF) { + if (child_.type() !== ObjectType.PARSEROP_NODEREF) { return true; } if ( - refObj == null || + refObj === null || !refObj.isNode() || - ConfigNode.castFrom(refObj).getNodeType() == NodeRefType.NODE_REF || - ConfigNode.castFrom(refObj).getNodeType() == NodeRefType.NODE_TEMPLATE || - ConfigNode.castFrom(refObj).getNodeType() == NodeRefType.NODE_DELETE + ConfigNode.castFrom(refObj).getNodeType() === NodeRefType.NODE_REF || + ConfigNode.castFrom(refObj).getNodeType() === NodeRefType.NODE_TEMPLATE || + ConfigNode.castFrom(refObj).getNodeType() === NodeRefType.NODE_DELETE ) { NapiLog.logError( sourceInfo() + "reference invalid node '" + child_.stringValue() + "'" @@ -655,7 +655,7 @@ class ConfigTerm extends AstObject { return true; } if ( - this.child_.type() != src.child().type() && + this.child_.type() !== src.child().type() && (!this.child_.isNumber() || !src.child().isNumber()) ) { NapiLog.logError( @@ -682,13 +682,13 @@ class ConfigTerm extends AstObject { } class ConfigArray extends AstObject { constructor(array) { - if (Object.prototype.toString.call(array) == '[object Object]') { + if (Object.prototype.toString.call(array) === '[object Object]') { super('', ObjectType.PARSEROP_ARRAY, 0, array); // bindToken this.arrayType_ = 0; this.arraySize_ = 0; - if (array.type == undefined) { + if (array.type === undefined) { let child = array.child_; - while (child != null) { + while (child !== null) { super.addChild(AstObjectFactory.build(child)); child = child.next(); } @@ -734,7 +734,7 @@ class ConfigArray extends AstObject { let array = ConfigArray.castFrom(src); this.child_ = null; let t = array.child_; - while (t != null) { + while (t !== null) { addChild(AstObjectFactory.build(t)); } return true; @@ -794,13 +794,13 @@ class Ast { NapiLog.logInfo(this.setw(walkDepth * 4) + current.stringValue_); break; case ObjectType.PARSEROP_CONFNODE: // 6 content - if (current.name_ == 'blockSize') { + if (current.name_ === 'blockSize') { current.name_ = 'blockSize'; } NapiLog.logInfo(this.setw(walkDepth * 4) + current.name_ + ' :'); break; case ObjectType.PARSEROP_CONFTERM: // 7 Attribute name - if (current.name_ == 'funcNum') { + if (current.name_ === 'funcNum') { current.name_ = 'funcNum'; } NapiLog.logInfo(this.setw(walkDepth * 4) + current.name_ + ' = '); @@ -832,9 +832,9 @@ class Ast { if (!astIt.redefineCheck()) { return false; } - if (this.astRoot_ != null && !this.astRoot_.merge(astIt.astRoot_)) { + if (this.astRoot_ !== null && !this.astRoot_.merge(astIt.astRoot_)) { return false; - } else if (this.astRoot_ == null) { + } else if (this.astRoot_ === null) { this.astRoot_ = astIt.getAstRoot(); } } @@ -843,8 +843,8 @@ class Ast { getchild(node, name) { let p = node.child_; - while (p != null) { - if (p.name_ == name) { + while (p !== null) { + if (p.name_ === name) { return p; } p = p.next_; @@ -855,7 +855,7 @@ class Ast { getpath(node) { NapiLog.logError('----path start----'); let p = node; - while (p != null) { + while (p !== null) { NapiLog.logError(p.name_); p = p.parent_; } @@ -869,7 +869,7 @@ class Ast { return false; } - if (this.astRoot_.lookup('module', ObjectType.PARSEROP_CONFTERM) == null) { + if (this.astRoot_.lookup('module', ObjectType.PARSEROP_CONFTERM) === null) { NapiLog.logError( astRoot_.sourceInfo() + "miss 'module' attribute under root node" ); @@ -891,14 +891,14 @@ class Ast { return this.walkBackward(this.astRoot_, (current, walkDepth) => { if (current.isNode()) { let node = current; - if (node.getNodeType() == NodeRefType.NODE_DELETE) { + if (node.getNodeType() === NodeRefType.NODE_DELETE) { current.remove(); child_; return HcsErrorNo.NOERR; } if ( - node.getNodeType() != NodeRefType.NODE_REF && - node.getNodeType() != NodeRefType.NODE_COPY + node.getNodeType() !== NodeRefType.NODE_REF && + node.getNodeType() !== NodeRefType.NODE_COPY ) { return HcsErrorNo.NOERR; } @@ -909,11 +909,11 @@ class Ast { } } else if (current.isTerm()) { let ref; - if (current.child_.type() == ObjectType.PARSEROP_DELETE) { + if (current.child_.type() === ObjectType.PARSEROP_DELETE) { current.remove(); return HcsErrorNo.NOERR; } - if (current.child_.type() == ObjectType.PARSEROP_NODEREF) { + if (current.child_.type() === ObjectType.PARSEROP_NODEREF) { ref = lookup(current, current.child_.stringValue()); if (!current.refExpand(ref)) { return HcsErrorNo.EFAIL; @@ -931,13 +931,13 @@ class Ast { let walkDepth = 0; let preVisited = false; - while (backWalkObj != null) { + while (backWalkObj !== null) { let backWalk = true; - if (backWalkObj.child_ == null || preVisited) { + if (backWalkObj.child_ === null || preVisited) { next = backWalkObj.next_; parent = backWalkObj.parent(); - if (callback(backWalkObj, walkDepth) != HcsErrorNo.NOERR) { + if (callback(backWalkObj, walkDepth) !== HcsErrorNo.NOERR) { return false; } } else if (backWalkObj.child_) { @@ -946,11 +946,11 @@ class Ast { backWalk = false; } if (backWalk) { - if (backWalkObj == startObject) { + if (backWalkObj === startObject) { break; } - if (next != null) { + if (next !== null) { backWalkObj = next; preVisited = false; } else { @@ -967,7 +967,7 @@ class Ast { return this.walkForward(this.astRoot_, (current, ii) => { if (current.isNode()) { let node = current; - if (node.getNodeType() != NodeRefType.NODE_INHERIT) { + if (node.getNodeType() !== NodeRefType.NODE_INHERIT) { return HcsErrorNo.NOERR; } let inherit = this.lookup(current, node.getRefPath()); @@ -1002,15 +1002,15 @@ class Ast { let walkDepth = 0; let preVisited = false; - while (forwardWalkObj != null) { + while (forwardWalkObj !== null) { let forward = true; if (!preVisited) { let ret = callback(forwardWalkObj, walkDepth); - if (ret && ret != HcsErrorNo.EASTWALKBREAK) { + if (ret && ret !== HcsErrorNo.EASTWALKBREAK) { return false; } else if ( - ret != HcsErrorNo.EASTWALKBREAK && - forwardWalkObj.child_ != null + ret !== HcsErrorNo.EASTWALKBREAK && + forwardWalkObj.child_ !== null ) { walkDepth++; forwardWalkObj = forwardWalkObj.child_; @@ -1019,11 +1019,11 @@ class Ast { } if (forward) { - if (forwardWalkObj == startObject) { + if (forwardWalkObj === startObject) { break; } - if (forwardWalkObj.next_ != null) { + if (forwardWalkObj.next_ !== null) { forwardWalkObj = forwardWalkObj.next_; preVisited = false; } else { diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/lexer.js b/framework/tools/hcs-view/hcsWebView/src/hcs/lexer.js index b90ffccc971d5bf025d8843f7e53de2859864e6e..dc22c3f5e716d61f9d46805af9384bbdf5bbff70 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/lexer.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/lexer.js @@ -21,7 +21,7 @@ function code(s) { } function isSpace(c) { - return c == code(' ') || c == code('\t') || c == code('\r'); + return c === code(' ') || c === code('\t') || c === code('\r'); } function isalpha(c) { @@ -92,7 +92,7 @@ class Lexer { lexInclude(token) { this.consumeChar(); this.lexFromLiteral(token); - if (token.strval != 'include') { + if (token.strval !== 'include') { return false; } @@ -102,15 +102,15 @@ class Lexer { isConsumeCharCode(c) { if ( - c[0] == code(';') || - c[0] == code(',') || - c[0] == code('[') || - c[0] == code(']') || - c[0] == code('{') || - c[0] == code('}') || - c[0] == code('=') || - c[0] == code('&') || - c[0] == code(':') + c[0] === code(';') || + c[0] === code(',') || + c[0] === code('[') || + c[0] === code(']') || + c[0] === code('{') || + c[0] === code('}') || + c[0] === code('=') || + c[0] === code('&') || + c[0] === code(':') ) { return true; } @@ -125,7 +125,7 @@ class Lexer { token.type = TokenType.EOF; return true; } - if (c[0] == code('#')) { + if (c[0] === code('#')) { return this.lexInclude(token); } if (isalpha(c)) { @@ -137,7 +137,7 @@ class Lexer { return this.lexFromNumber(token); } - if (c[0] == code('/')) { + if (c[0] === code('/')) { if (!this.processComment()) { return false; } @@ -146,11 +146,11 @@ class Lexer { token.type = c[0]; token.lineNo = this.lineno_; break; - } else if (c[0] == code('"')) { + } else if (c[0] === code('"')) { return this.lexFromString(token); - } else if (c[0] == code('+') || c[0] == code('-')) { + } else if (c[0] === code('+') || c[0] === code('-')) { return lexFromNumber(token); - } else if (c[0] == -1) { + } else if (c[0] === -1) { token.type = -1; break; } else { @@ -168,10 +168,10 @@ class Lexer { while ( this.bufferStart_ <= this.bufferEnd_ && (isSpace(this.data_[this.bufferStart_]) || - this.data_[this.bufferStart_] == code('\n')) + this.data_[this.bufferStart_] === code('\n')) ) { this.lineLoc_++; - if (this.data_[this.bufferStart_] == code('\n')) { + if (this.data_[this.bufferStart_] === code('\n')) { this.lineLoc_ = 0; this.lineno_++; } @@ -199,7 +199,7 @@ class Lexer { let c = []; while (this.peekChar(c, false) && !isSpace(c[0])) { - if (!isalnum(c) && c != code('_') && c != code('.') && c != code('\\')) { + if (!isalnum(c) && c[0] !== code('_') && c[0] !== code('.') && c[0] !== code('\\')) { break; } value += toStr(c); @@ -207,11 +207,11 @@ class Lexer { } do { - if (value == 'true') { + if (value === 'true') { token.type = TokenType.BOOL; token.numval = 1; break; - } else if (value == 'false') { + } else if (value === 'false') { token.type = TokenType.BOOL; token.numval = 0; break; @@ -246,7 +246,7 @@ class Lexer { } } - if (chr == code('\n')) { + if (chr === code('\n')) { this.lineno_++; this.lineLoc_ = 0; } @@ -286,7 +286,7 @@ class Lexer { this.consumeChar(); while ( this.peekChar(c, false) && - (c[0] == code('0') || c[0] == code('1')) + (c[0] === code('0') || c[0] === code('1')) ) { param.value += toStr(c); this.consumeChar(); @@ -315,10 +315,10 @@ class Lexer { this.lexFromOctalNumber(c, param); break; } - if (c[0] == code('x') || code('x') == code('X')) { + if (c[0] === code('x') || code('x') === code('X')) { this.lexFromHexNumber(c, param); break; - } else if (c[0] == code('b')) { + } else if (c[0] === code('b')) { this.lexFromBinaryNumber(c, param); break; } @@ -331,12 +331,13 @@ class Lexer { this.consumeChar(); param.value += toStr(c); } - param.v = parseInt(param.value, 10); - param.baseSystem = 10; + let baseSystem = 10; + param.v = BigInt(param.value, baseSystem); + param.baseSystem = baseSystem; break; } - if (errno != 0) { + if (errno !== 0) { dealWithError('illegal number: ' + param.value); return false; } @@ -351,11 +352,11 @@ class Lexer { let c = []; this.getChar(c, false); let value = ''; - while (this.getChar(c, false) && c[0] != code('"')) { + while (this.getChar(c, false) && c[0] !== code('"')) { value += toStr(c); } - if (c != code('"')) { + if (c[0] !== code('"')) { dealWithError('unterminated string'); return false; } @@ -372,23 +373,23 @@ class Lexer { return false; } - if (c[0] == code('/')) { - while (c[0] != code('\n')) { + if (c[0] === code('/')) { + while (c[0] !== code('\n')) { if (!this.getChar(c, true)) { break; } } - if (c[0] != code('\n') && c[0] != TokenType.EOF) { + if (c[0] !== code('\n') && c[0] !== TokenType.EOF) { dealWithError('unterminated signal line comment'); return false; } - } else if (c[0] == code('*')) { + } else if (c[0] === code('*')) { while (this.getChar(c, true)) { - if (c[0] == code('*') && this.getChar(c, true) && c[0] == code('/')) { + if (c[0] === code('*') && this.getChar(c, true) && c[0] === code('/')) { return true; } } - if (c[0] != code('/')) { + if (c[0] !== code('/')) { dealWithError('unterminated multi-line comment'); return false; } diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/parser.js b/framework/tools/hcs-view/hcsWebView/src/hcs/parser.js index 75936e3d5690ee776f40d9a1ee236d7af3354f87..2dbe3485fbfd8fe1bcf641622a4f044684948531 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/parser.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/parser.js @@ -37,14 +37,14 @@ class Parser { this.astList = {}; } parse(fn) { - if (this.srcQueue_.indexOf(fn) == -1) { + if (this.srcQueue_.indexOf(fn) === -1) { this.srcQueue_.push(fn); } while (this.srcQueue_.length > 0) { let includeList = []; let oneAst = this.parseOne(this.srcQueue_[0], includeList); - if (oneAst == null) { + if (oneAst === null) { return false; } @@ -60,7 +60,7 @@ class Parser { convertAbsPath(includeBy, includePath) { if (navigator.userAgent.toLowerCase().indexOf('win') > -1) { //windows - if (includePath[1] != ':') { + if (includePath[1] !== ':') { let currentSrc = includeBy.substring( 0, includeBy.lastIndexOf('\\') + 1 @@ -69,7 +69,7 @@ class Parser { includePath = includePath.replace(/\\\.\\/g, '\\'); } - } else if (includePath[0] != '/') { + } else if (includePath[0] !== '/') { let currentSrc = includeBy.substring(0, includeBy.lastIndexOf('/') + 1); includePath = currentSrc + includePath; } @@ -79,7 +79,7 @@ class Parser { do { if ( !this.lexer_.lex(this.current_) || - this.current_.type != TokenType.STRING + this.current_.type !== TokenType.STRING ) { this.dealWithError( this.lexer_ + 'syntax error, expect include path after ’#include‘' @@ -102,7 +102,7 @@ class Parser { return false; } - if (this.current_.type != TokenType.INCLUDE) { + if (this.current_.type !== TokenType.INCLUDE) { break; } } while (true); @@ -119,29 +119,29 @@ class Parser { } if ( - this.current_.type == TokenType.INCLUDE && + this.current_.type === TokenType.INCLUDE && !this.processInclude(includeList) ) { return null; } let rootNode = null; - if (this.current_.type == TokenType.ROOT) { + if (this.current_.type === TokenType.ROOT) { let preToken = copy(this.current_); preToken.type = TokenType.LITERAL; preToken.strval = 'root'; rootNode = this.parseNode(preToken); - if (rootNode == null) { + if (rootNode === null) { return null; } - } else if (this.current_.type != TokenType.EOF) { + } else if (this.current_.type !== TokenType.EOF) { this.dealWithError('syntax error, expect root node of end of file'); return null; } if ( !this.lexer_.lex(this.current_) || - this.current_.type != TokenType.EOF + this.current_.type !== TokenType.EOF ) { this.dealWithError('syntax error, expect EOF'); return null; @@ -153,7 +153,7 @@ class Parser { parseNode(name, bracesStart) { if (!bracesStart) { - if (!this.lexer_.lex(this.current_) || this.current_.type != code('{')) { + if (!this.lexer_.lex(this.current_) || this.current_.type !== code('{')) { this.dealWithError("syntax error, node miss '{'"); return null; } @@ -161,7 +161,7 @@ class Parser { let node = new ConfigNode(name, NodeRefType.NODE_NOREF, ''); let child; - while (this.lexer_.lex(this.current_) && this.current_.type != 125) { + while (this.lexer_.lex(this.current_) && this.current_.type !== code('}')) { switch (this.current_.type) { case TokenType.TEMPLATE: child = this.parseTemplate(); @@ -179,14 +179,14 @@ class Parser { ); return null; } - if (child == null) { + if (child === null) { return null; } node.addChild(child); } - if (this.current_.type != code('}')) { + if (this.current_.type !== code('}')) { this.dealWithError(this.lexer_ + "syntax error, node miss '}'"); return null; } @@ -222,10 +222,10 @@ class Parser { let array = new ConfigArray(this.current_); let arrayType = 0; - while (this.lexer_.lex(this.current_) && this.current_.type != code(']')) { - if (this.current_.type == TokenType.STRING) { + while (this.lexer_.lex(this.current_) && this.current_.type !== code(']')) { + if (this.current_.type === TokenType.STRING) { array.addChild(new AstObject('', ObjectType.PARSEROP_STRING, this.current_.strval, this.current_)); - } else if (this.current_.type == TokenType.NUMBER) { + } else if (this.current_.type === TokenType.NUMBER) { array.addChild(new AstObject('', ObjectType.PARSEROP_UINT64, this.current_.numval, this.current_, this.current_.baseSystem)); } else { @@ -233,23 +233,23 @@ class Parser { return nullptr; } - if (arrayType == 0) { + if (arrayType === 0) { arrayType = this.current_.type; - } else if (arrayType != this.current_.type) { + } else if (arrayType !== this.current_.type) { this.dealWithError(this.lexer_ + 'syntax error, not allow mix type array'); return null; } if (this.lexer_.lex(this.current_)) { - if (this.current_.type == code(']')) { + if (this.current_.type === code(']')) { break; - } else if (this.current_.type != code(',')) { + } else if (this.current_.type !== code(',')) { this.dealWithError(this.lexer_ + "syntax error, except ',' or ']'"); return null; } } else { return null; } } - if (this.current_.type != code(']')) { + if (this.current_.type !== code(']')) { this.dealWithError(this.lexer_ + "syntax error, miss ']' at end of array"); return null; } @@ -273,7 +273,7 @@ class Parser { break; case code('['): { let list = this.parseArray(); - if (list == null) { + if (list === null) { return null; } else { term.addChild(list); @@ -281,7 +281,7 @@ class Parser { break; } case code('&'): - if (!this.lexer_.lex(this.current_) || (this.current_.type != TokenType.LITERAL && this.current_.type != TokenType.REF_PATH)) { + if (!this.lexer_.lex(this.current_) || (this.current_.type !== TokenType.LITERAL && this.current_.type !== TokenType.REF_PATH)) { this.dealWithError('syntax error, invalid config term definition'); return null; } @@ -295,7 +295,7 @@ class Parser { return null; } - if (!this.lexer_.lex(this.current_) || this.current_.type != code(';')) { + if (!this.lexer_.lex(this.current_) || this.current_.type !== code(';')) { this.dealWithError("syntax error, miss ';'"); return null; } @@ -305,14 +305,14 @@ class Parser { parseTemplate() { if ( !this.lexer_.lex(this.current_) || - this.current_.type != TokenType.LITERAL + this.current_.type !== TokenType.LITERAL ) { this.dealWithError('syntax error, template miss name'); return null; } let name = copy(this.current_); let node = this.parseNode(name, false); - if (node == null) { + if (node === null) { return node; } @@ -323,8 +323,8 @@ class Parser { parseNodeRef(name) { if ( !this.lexer_.lex(this.current_) || - (this.current_.type != TokenType.LITERAL && - this.current_.type != TokenType.REF_PATH) + (this.current_.type !== TokenType.LITERAL && + this.current_.type !== TokenType.REF_PATH) ) { this.dealWithError( this.lexer_ + 'syntax error, miss node reference path' @@ -333,7 +333,7 @@ class Parser { } let refPath = this.current_.strval; let node = this.parseNode(name); - if (node == null) { + if (node === null) { return null; } @@ -344,7 +344,7 @@ class Parser { } parseNodeDelete(name) { let node = this.parseNode(name); - if (node == null) { + if (node === null) { return null; } @@ -355,7 +355,7 @@ class Parser { let nodePath = this.current_.strval; let node = this.parseNode(name); - if (node == null) { + if (node === null) { return null; } @@ -387,8 +387,8 @@ class Parser { parseNodeInherit(name) { if ( !this.lexer_.lex(this.current_) || - (this.current_.type != TokenType.LITERAL && - this.current_.type != TokenType.REF_PATH) + (this.current_.type !== TokenType.LITERAL && + this.current_.type !== TokenType.REF_PATH) ) { this.dealWithError('syntax error, miss node inherit path'); return null; @@ -397,7 +397,7 @@ class Parser { let inheritPath = this.current_.strval; let node = this.parseNode(name); - if (node == null) { + if (node === null) { return null; } diff --git a/framework/tools/hcs-view/hcsWebView/src/hcs/re.js b/framework/tools/hcs-view/hcsWebView/src/hcs/re.js index 806631dbd5b54735872d1eee6a2831b3c7a51810..4f5af0010a97009aecfd38e22760aff3622f2ade 100644 --- a/framework/tools/hcs-view/hcsWebView/src/hcs/re.js +++ b/framework/tools/hcs-view/hcsWebView/src/hcs/re.js @@ -17,14 +17,14 @@ function search(ss, data) { ss = replaceAll(ss, '\\.', '\\.'); let reg = new RegExp(ss); let tt = reg.exec(data); - if (tt == null) { + if (tt === null) { return null; } let ret = { regs: [] }; for (let i = 0; i < tt.length; i++) { let p = data.indexOf(tt[i]); let regs = 'regs'; - if (tt[i] == null) { + if (tt[i] === null) { ret[regs].push([-1, -1]); } else { ret[regs].push([p, p + tt[i].length]); @@ -36,7 +36,7 @@ function search(ss, data) { function match(ss, data) { let tt = search(ss, data); - if (tt != null && tt.regs[0][0] == 0) { + if (tt !== null && tt.regs[0][0] === 0) { return tt; } return null; diff --git a/framework/tools/hcs-view/hcsWebView/src/index.js b/framework/tools/hcs-view/hcsWebView/src/index.js index 13ec9e425a7f2b9b30cc7033a907993f7020e0a9..a806acb457b7eeb522b6c4825962ffa81241b6f4 100644 --- a/framework/tools/hcs-view/hcsWebView/src/index.js +++ b/framework/tools/hcs-view/hcsWebView/src/index.js @@ -22,15 +22,16 @@ const { NapiLog } = require('./hcs/NapiLog'); const { MainEditor } = require('./MainEditor'); let canvas = document.getElementById('visual_area'); -canvas.width = window.innerWidth - 420; +let widthOffset = 420; +canvas.width = window.innerWidth - widthOffset; canvas.height = window.innerHeight; function myDraw() { if ( - canvas.width != window.innerWidth - 420 || - canvas.height != window.innerHeight + canvas.width !== window.innerWidth - widthOffset || + canvas.height !== window.innerHeight ) { - canvas.width = window.innerWidth - 420; + canvas.width = window.innerWidth - widthOffset; canvas.height = window.innerHeight; Scr.setLogicScreenSize(canvas.width, canvas.height); diff --git a/framework/tools/hcs-view/hcsWebView/src/message/XMessage.js b/framework/tools/hcs-view/hcsWebView/src/message/XMessage.js index 611925027b4bb03b11321d807a9200e069d7fad0..35528550d6ad802fa6f6dd472697a99e10a3399a 100644 --- a/framework/tools/hcs-view/hcsWebView/src/message/XMessage.js +++ b/framework/tools/hcs-view/hcsWebView/src/message/XMessage.js @@ -33,17 +33,17 @@ class XMessage { this.callbackFunc = func; } onRecv(event) { - if (XMessage.gi().callbackFunc != null) { + if (XMessage.gi().callbackFunc !== null) { XMessage.gi().callbackFunc(event.data.type, event.data.data); } } send(msgtype, msgdata) { - if (this.messageType == XMessage.TYPE_VSCODE) { + if (this.messageType === XMessage.TYPE_VSCODE) { this.vscode.postMessage({ type: msgtype, data: msgdata, }); - } else if (this.messageType == XMessage.TYPE_NONE) { + } else if (this.messageType === XMessage.TYPE_NONE) { MockMessage.gi().processMessage({ type: msgtype, data: msgdata, @@ -57,7 +57,7 @@ XMessage.TYPE_VSCODE = 1; XMessage.pinstance_ = null; XMessage.gi = function () { - if (XMessage.pinstance_ == null) { + if (XMessage.pinstance_ === null) { XMessage.pinstance_ = new XMessage(); } return XMessage.pinstance_; diff --git a/framework/tools/hcs-view/hcsWebView/src/message/mock.js b/framework/tools/hcs-view/hcsWebView/src/message/mock.js index 2e348226d40002df80ab5dd32fca5b286bd14b8e..cb7395fd106399d7f3f614e3cd7601987faf779a 100644 --- a/framework/tools/hcs-view/hcsWebView/src/message/mock.js +++ b/framework/tools/hcs-view/hcsWebView/src/message/mock.js @@ -45,7 +45,7 @@ root { function getArray(fn) { for (let i in mockTest) { - if (mockTest[i].fn == fn) { + if (mockTest[i].fn === fn) { let ret = []; for (let j in mockTest[i].data) { ret.push(mockTest[i].data.charCodeAt(j)); @@ -73,9 +73,9 @@ class MockMessage { NapiLog.logInfo('---MockMessage start---'); NapiLog.logInfo(msg.type); NapiLog.logInfo(msg.data); - if (msg.type == 'inited') { + if (msg.type === 'inited') { this.send('parse', mockTest[0].fn); - } else if (msg.type == 'getfiledata') { + } else if (msg.type === 'getfiledata') { this.send('filedata', { fn: msg.data, data: getArray(msg.data), @@ -87,7 +87,7 @@ class MockMessage { MockMessage.pInstance_ = null; MockMessage.gi = function () { - if (MockMessage.pInstance_ == null) { + if (MockMessage.pInstance_ === null) { MockMessage.pInstance_ = new MockMessage(); } return MockMessage.pInstance_; diff --git a/framework/tools/hdi-gen/ast/ast.cpp b/framework/tools/hdi-gen/ast/ast.cpp index d83a2d6bc4bea61e87a91ef1c67960d2abc557ca..f4a73aabed7bd92bce02caa4939e7363007a693f 100644 --- a/framework/tools/hdi-gen/ast/ast.cpp +++ b/framework/tools/hdi-gen/ast/ast.cpp @@ -158,7 +158,8 @@ AutoPtr AST::FindType(const std::string &typeName, bool lookImports) } for (const auto &type : types_) { - if (type.second->GetName() == typeName) { + if ((typeName.find('.') == std::string::npos && type.second->GetName() == typeName) || + type.first == typeName) { return type.second; } } diff --git a/framework/tools/hdi-gen/ast/ast_attribute.h b/framework/tools/hdi-gen/ast/ast_attribute.h index bc272ab3a8a14caf498030bc8c3f687cb8c55fc8..7a438580aa95594b991cf5a5b08b81d156f7da37 100644 --- a/framework/tools/hdi-gen/ast/ast_attribute.h +++ b/framework/tools/hdi-gen/ast/ast_attribute.h @@ -34,6 +34,11 @@ public: value_ |= value; } + inline Attribute GetValue() const + { + return value_; + } + bool HasValue(Attribute attr) const { return (value_ & attr) != 0; diff --git a/framework/tools/hdi-gen/ast/ast_enum_type.cpp b/framework/tools/hdi-gen/ast/ast_enum_type.cpp index a9051a780982bcb6aea1cb5fef80ba3930f8771d..ae8d2c797e94f62fef4128f99b39e72a1f50476b 100644 --- a/framework/tools/hdi-gen/ast/ast_enum_type.cpp +++ b/framework/tools/hdi-gen/ast/ast_enum_type.cpp @@ -16,12 +16,33 @@ void ASTEnumType::SetBaseType(const AutoPtr &baseType) if (baseType == nullptr) { return; } - baseType_ = baseType; + if (baseType->GetTypeKind() == TypeKind::TYPE_ENUM) { + AutoPtr parentEnumType = dynamic_cast(baseType.Get()); + std::vector> parentMembers = parentEnumType->GetMembers(); + for (auto member : parentMembers) { + members_.push_back(member); + } + parentType_= baseType; + baseType_ = parentEnumType->GetBaseType(); + } else { + baseType_ = baseType; + } } -void ASTEnumType::AddMember(const AutoPtr &member) +bool ASTEnumType::AddMember(const AutoPtr &member) { + for (auto members : members_) { + if (member->GetName() == members->GetName()) { + return false; + } + } members_.push_back(member); + return true; +} + +AutoPtr ASTEnumType::GetBaseType() +{ + return baseType_; } bool ASTEnumType::IsEnumType() @@ -34,7 +55,12 @@ std::string ASTEnumType::Dump(const std::string &prefix) StringBuilder sb; sb.Append(prefix).Append(attr_->Dump(prefix)).Append(" "); if (baseType_ != nullptr) { - sb.AppendFormat("enum %s : %s {\n", name_.c_str(), baseType_->ToString().c_str()); + if (parentType_ != nullptr) { + sb.AppendFormat("enum %s : %s ", name_.c_str(), parentType_->ToString().c_str()); + sb.AppendFormat(" : %s {\n", baseType_->ToString().c_str()); + } else { + sb.AppendFormat("enum %s : %s {\n", name_.c_str(), baseType_->ToString().c_str()); + } } else { sb.AppendFormat("enum %s {\n", name_.c_str()); } @@ -80,13 +106,13 @@ std::string ASTEnumType::EmitCppType(TypeMode mode) const { switch (mode) { case TypeMode::NO_MODE: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_IN: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_OUT: - return StringHelper::Format("%s&", name_.c_str()); + return StringHelper::Format("%s&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::LOCAL_VAR: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); default: return "unknow type"; } diff --git a/framework/tools/hdi-gen/ast/ast_enum_type.h b/framework/tools/hdi-gen/ast/ast_enum_type.h index 15aefe27a70b1518f9c7d977764292eafbccc1e7..e371055b5260147b86b82e984330a7fa4066b4dc 100644 --- a/framework/tools/hdi-gen/ast/ast_enum_type.h +++ b/framework/tools/hdi-gen/ast/ast_enum_type.h @@ -87,14 +87,16 @@ public: } void SetBaseType(const AutoPtr &baseType); - - inline AutoPtr GetBaseType() + + AutoPtr GetBaseType(); + + bool AddMember(const AutoPtr &member); + + inline std::vector> GetMembers() { - return baseType_; + return members_; } - - void AddMember(const AutoPtr &member); - + inline size_t GetMemberNumber() { return members_.size(); @@ -156,6 +158,7 @@ public: private: AutoPtr attr_ = new ASTAttr(); AutoPtr baseType_; + AutoPtr parentType_; std::vector> members_; }; } // namespace HDI diff --git a/framework/tools/hdi-gen/ast/ast_interface_type.cpp b/framework/tools/hdi-gen/ast/ast_interface_type.cpp index 8aa6eb710719e7fc7ada40128047696b211cdfaf..b2ce86b05e804d73003c7944f1cd3d4232c633ab 100644 --- a/framework/tools/hdi-gen/ast/ast_interface_type.cpp +++ b/framework/tools/hdi-gen/ast/ast_interface_type.cpp @@ -200,9 +200,16 @@ void ASTInterfaceType::EmitCppReadVar(const std::string &parcelName, const std:: if (initVariable) { sb.Append(prefix).AppendFormat("sptr<%s> %s;\n", GetNameWithNamespace(namespace_, name_).c_str(), name.c_str()); } - sb.Append(prefix).AppendFormat("if (!ReadInterface<%s>(%s, %s)) {\n", - GetNameWithNamespace(namespace_, name_).c_str(), parcelName.c_str(), name.c_str()); - sb.Append(prefix + TAB).Append("HDF_LOGE(\"%{public}s: failed to read interface object\", __func__);\n"); + sb.Append(prefix).AppendFormat("sptr %sRemote = %s.ReadRemoteObject();\n", name.c_str(), + parcelName.c_str()); + sb.Append(prefix).AppendFormat("if (%sRemote == nullptr) {\n", name.c_str()); + sb.Append(prefix + TAB).Append("HDF_LOGE(\"%{public}s: read an invalid remote object\", __func__);\n"); + sb.Append(prefix + TAB).Append("return HDF_ERR_INVALID_PARAM;\n"); + sb.Append(prefix).Append("}\n\n"); + sb.Append(prefix).AppendFormat("%s = new %s(%sRemote);\n", name.c_str(), + ((StringHelper::StartWith(name_, "I") ? name_.substr(1) : name_) + "Proxy").c_str(), name.c_str()); + sb.Append(prefix).AppendFormat("if (%s == nullptr) {\n", name.c_str()); + sb.Append(prefix + TAB).Append("HDF_LOGE(\"%{public}s: failed to create interface object\", __func__);\n"); sb.Append(prefix + TAB).Append("return HDF_ERR_INVALID_PARAM;\n"); sb.Append(prefix).Append("}\n"); } @@ -247,10 +254,6 @@ void ASTInterfaceType::RegisterReadMethod(Language language, SerMode mode, UtilM methods.emplace(methodName, std::bind(&ASTInterfaceType::EmitCReadMethods, this, _1, _2, _3, _4)); break; } - case Language::CPP: { - methods.emplace("ReadInterface", std::bind(&ASTInterfaceType::EmitCppReadMethods, this, _1, _2, _3, _4)); - break; - } default: break; } @@ -307,34 +310,5 @@ void ASTInterfaceType::EmitCReadMethods(StringBuilder &sb, const std::string &pr sb.Append(prefix + TAB).AppendFormat("return %sGet(remote);\n", name_.c_str()); sb.Append(prefix).Append("}\n"); } - -void ASTInterfaceType::EmitCppReadMethods(StringBuilder &sb, const std::string &prefix, - const std::string &methodPrefix, bool isDecl) const -{ - std::string methodName = StringHelper::Format("%sReadInterface", methodPrefix.c_str(), name_.c_str()); - sb.Append(prefix).AppendFormat("template\n"); - sb.Append(prefix).AppendFormat("static bool %s(MessageParcel &parcel, sptr& object)", - methodName.c_str()); - if (isDecl) { - sb.Append(";\n"); - return; - } else { - sb.Append("\n"); - } - - sb.Append(prefix).Append("{\n"); - sb.Append(prefix + TAB).Append("sptr remote = parcel.ReadRemoteObject();\n"); - sb.Append(prefix + TAB).Append("if (remote == nullptr) {\n"); - sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s: read an invalid remote object\", __func__);\n"); - sb.Append(prefix + TAB + TAB).Append("return false;\n"); - sb.Append(prefix + TAB).Append("}\n\n"); - sb.Append(prefix + TAB).Append("object = hdi_facecast(remote);\n"); - sb.Append(prefix + TAB).Append("if (object == nullptr) {\n"); - sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s: failed to cast interface object\", __func__);\n"); - sb.Append(prefix + TAB + TAB).Append("return false;\n"); - sb.Append(prefix + TAB).Append("}\n"); - sb.Append(prefix + TAB).Append("return true;\n"); - sb.Append(prefix).Append("}\n"); -} } // namespace HDI } // namespace OHOS diff --git a/framework/tools/hdi-gen/ast/ast_interface_type.h b/framework/tools/hdi-gen/ast/ast_interface_type.h index 6d1868418f038fa697b41695350db155fd1c60a8..3e642408e5a0b3dfe3aa387790674842e7f81e93 100644 --- a/framework/tools/hdi-gen/ast/ast_interface_type.h +++ b/framework/tools/hdi-gen/ast/ast_interface_type.h @@ -186,9 +186,6 @@ public: void EmitCReadMethods( StringBuilder &sb, const std::string &prefix, const std::string &methodPrefix, bool isDecl) const; - - void EmitCppReadMethods( - StringBuilder &sb, const std::string &prefix, const std::string &methodPrefix, bool isDecl) const; private: std::string license_; diff --git a/framework/tools/hdi-gen/ast/ast_method.h b/framework/tools/hdi-gen/ast/ast_method.h index 2eeaa5b92d9a285e52df4c1d4ad9c604d33ed2b7..89e44ce4a5e17de743dbdfb6c3b62be300421369 100644 --- a/framework/tools/hdi-gen/ast/ast_method.h +++ b/framework/tools/hdi-gen/ast/ast_method.h @@ -29,10 +29,10 @@ public: return name_; } - inline void SetAttribute(const AutoPtr &attr) + inline void SetAttribute(AutoPtr attr) { - if (attr != nullptr) { - attr_ = attr; + if (attr_ != nullptr && attr != nullptr) { + attr_->SetValue(attr->GetValue()); } } diff --git a/framework/tools/hdi-gen/ast/ast_sequenceable_type.cpp b/framework/tools/hdi-gen/ast/ast_sequenceable_type.cpp index cf6894ba4c76f8b0d8b70fa2eb6a5275efd35fef..74858a4a8210c4cb82dd19aef8e6922e6bc63060 100644 --- a/framework/tools/hdi-gen/ast/ast_sequenceable_type.cpp +++ b/framework/tools/hdi-gen/ast/ast_sequenceable_type.cpp @@ -58,13 +58,13 @@ std::string ASTSequenceableType::EmitCppType(TypeMode mode) const { switch (mode) { case TypeMode::NO_MODE: - return StringHelper::Format("sptr<%s>", name_.c_str()); + return StringHelper::Format("sptr<%s>", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_IN: - return StringHelper::Format("const sptr<%s>&", name_.c_str()); + return StringHelper::Format("const sptr<%s>&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_OUT: - return StringHelper::Format("sptr<%s>&", name_.c_str()); + return StringHelper::Format("sptr<%s>&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::LOCAL_VAR: - return StringHelper::Format("sptr<%s>", name_.c_str()); + return StringHelper::Format("sptr<%s>", GetNameWithNamespace(namespace_, name_).c_str()); default: return "unknow type"; } diff --git a/framework/tools/hdi-gen/ast/ast_struct_type.cpp b/framework/tools/hdi-gen/ast/ast_struct_type.cpp index 68fe13006e998ba13f15fa4ea36b8ac98bca907e..ff7f14bdc01496bb737a6c3c83683d1811980764 100644 --- a/framework/tools/hdi-gen/ast/ast_struct_type.cpp +++ b/framework/tools/hdi-gen/ast/ast_struct_type.cpp @@ -70,13 +70,13 @@ std::string ASTStructType::EmitCppType(TypeMode mode) const { switch (mode) { case TypeMode::NO_MODE: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_IN: - return StringHelper::Format("const %s&", name_.c_str()); + return StringHelper::Format("const %s&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_OUT: - return StringHelper::Format("%s&", name_.c_str()); + return StringHelper::Format("%s&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::LOCAL_VAR: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); default: return "unknow type"; } diff --git a/framework/tools/hdi-gen/ast/ast_union_type.cpp b/framework/tools/hdi-gen/ast/ast_union_type.cpp index af4899120d62bf820c26819078175d54d0eb35bc..0cc2a553ca66b48187619c3d28e6c24d4ca5be63 100644 --- a/framework/tools/hdi-gen/ast/ast_union_type.cpp +++ b/framework/tools/hdi-gen/ast/ast_union_type.cpp @@ -67,13 +67,13 @@ std::string ASTUnionType::EmitCppType(TypeMode mode) const { switch (mode) { case TypeMode::NO_MODE: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_IN: - return StringHelper::Format("const %s&", name_.c_str()); + return StringHelper::Format("const %s&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::PARAM_OUT: - return StringHelper::Format("%s&", name_.c_str()); + return StringHelper::Format("%s&", GetNameWithNamespace(namespace_, name_).c_str()); case TypeMode::LOCAL_VAR: - return StringHelper::Format("%s", name_.c_str()); + return StringHelper::Format("%s", GetNameWithNamespace(namespace_, name_).c_str()); default: return "unknow type"; } diff --git a/framework/tools/hdi-gen/codegen/code_emitter.cpp b/framework/tools/hdi-gen/codegen/code_emitter.cpp index 5ea7d0bac461d11446a272ad72647e2f43bbc435..d5645eb2475f49a1833966c2d956f61af1fe49e7 100644 --- a/framework/tools/hdi-gen/codegen/code_emitter.cpp +++ b/framework/tools/hdi-gen/codegen/code_emitter.cpp @@ -138,6 +138,19 @@ std::string CodeEmitter::PackageToFilePath(const std::string &packageName) const return filePath.ToString(); } +std::string CodeEmitter::InterfaceToFilePath(const std::string &interfaceName) const +{ + std::string fullName = interfaceName; + if (StringHelper::EndWith(fullName, "]")) { + fullName = fullName.substr(0, fullName.find("[")); + } + size_t index = fullName.rfind("."); + std::string prefix = fullName.substr(0, index + 1); + std::string suffix = fullName.substr(index + 1); + std::string fileName = prefix + (StringHelper::StartWith(suffix, "I") ? suffix.substr(1) : suffix) + "Proxy"; + return PackageToFilePath(fileName); +} + std::string CodeEmitter::EmitMethodCmdID(const AutoPtr &method) { return StringHelper::Format("CMD_%s_%s", ConstantName(baseName_).c_str(), ConstantName(method->GetName()).c_str()); diff --git a/framework/tools/hdi-gen/codegen/code_emitter.h b/framework/tools/hdi-gen/codegen/code_emitter.h index c5d925a16ecbdfdabdcf829b37fc6edf7f316970..62fc955e0bf09f7c09ebf6d396e0ac70c22d2cdc 100644 --- a/framework/tools/hdi-gen/codegen/code_emitter.h +++ b/framework/tools/hdi-gen/codegen/code_emitter.h @@ -89,6 +89,8 @@ protected: std::string PackageToFilePath(const std::string &packageName) const; + std::string InterfaceToFilePath(const std::string &interfaceName) const; + std::string EmitMethodCmdID(const AutoPtr &method); virtual void EmitInterfaceMethodCommands(StringBuilder &sb, const std::string &prefix); diff --git a/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.cpp b/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.cpp index 2a2ab9f2c545f3ab7fc004f7a7e393b53b4af88b..a94942b9e936856f8e76d467bf3720797e3b1de6 100644 --- a/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.cpp +++ b/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.cpp @@ -9,6 +9,7 @@ #include "codegen/cpp_client_proxy_code_emitter.h" #include "util/file.h" #include "util/logger.h" +#include "util/string_helper.h" namespace OHOS { namespace HDI { @@ -118,6 +119,7 @@ void CppClientProxyCodeEmitter::EmitProxyConstructor(StringBuilder &sb, const st void CppClientProxyCodeEmitter::EmitProxyMethodDecls(StringBuilder &sb, const std::string &prefix) const { + EmitProxyIsProxyMethodImpl(sb, prefix); AutoPtr interface = interface_; while (interface != nullptr) { for (const auto &method : interface->GetMethodsBySystem(Options::GetInstance().GetSystemLevel())) { @@ -269,12 +271,17 @@ void CppClientProxyCodeEmitter::EmitProxySourceFile() GetUtilMethods(utilMethods); EmitUtilMethods(sb, "", utilMethods, true); sb.Append("\n"); + if (interface_->GetExtendsInterface() != nullptr) { + EmitProxyCastFromMethodImplTemplate(sb, ""); + sb.Append("\n"); + } if (!interface_->IsSerializable()) { EmitGetMethodImpl(sb, ""); sb.Append("\n"); EmitGetInstanceMethodImpl(sb, ""); sb.Append("\n"); } + EmitProxyCastFromMethodImpls(sb, ""); EmitUtilMethods(sb, "", utilMethods, false); EmitProxyMethodImpls(sb, ""); sb.Append("\n"); @@ -291,6 +298,7 @@ void CppClientProxyCodeEmitter::EmitProxySourceInclusions(StringBuilder &sb) HeaderFile::HeaderFileSet headerFiles; headerFiles.emplace(HeaderFileType::OWN_HEADER_FILE, EmitVersionHeaderName(proxyName_)); GetSourceOtherLibInclusions(headerFiles); + GetSourceOtherFileInclusions(headerFiles); for (const auto &file : headerFiles) { sb.AppendFormat("%s\n", file.ToString().c_str()); @@ -335,6 +343,22 @@ void CppClientProxyCodeEmitter::GetSourceOtherLibInclusions(HeaderFile::HeaderFi } } +void CppClientProxyCodeEmitter::GetSourceOtherFileInclusions(HeaderFile::HeaderFileSet &headerFiles) const +{ + for (const auto &method : interface_->GetMethodsBySystem(Options::GetInstance().GetSystemLevel())) { + for (size_t paramIndex = 0; paramIndex < method->GetParameterNumber(); paramIndex++) { + AutoPtr param = method->GetParameter(paramIndex); + AutoPtr paramType = param->GetType(); + if (param->GetAttribute() == ParamAttr::PARAM_OUT && + (param->GetType()->IsInterfaceType() || paramType->HasInnerType(TypeKind::TYPE_INTERFACE))) { + AutoPtr type = dynamic_cast(paramType.Get()); + std::string FileName = InterfaceToFilePath(paramType->ToString()); + headerFiles.emplace(HeaderFileType::OWN_MODULE_HEADER_FILE, FileName); + } + } + } +} + void CppClientProxyCodeEmitter::EmitGetMethodImpl(StringBuilder &sb, const std::string &prefix) const { sb.Append(prefix).AppendFormat("%s %s::Get(bool isStub)\n", interface_->EmitCppType().c_str(), @@ -367,9 +391,10 @@ void CppClientProxyCodeEmitter::EmitGetInstanceMethodImpl(StringBuilder &sb, con sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:get remote object failed!\", __func__);\n"); sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); sb.Append(prefix + TAB).Append("}\n\n"); - sb.Append(prefix + TAB).AppendFormat("sptr<%s> %s = OHOS::HDI::hdi_facecast<%s>(remote);\n", + sb.Append(prefix + TAB).AppendFormat("sptr<%s> %s = new %s(remote);\n", EmitDefinitionByInterface(interface_, interfaceName_).c_str(), objName.c_str(), - EmitDefinitionByInterface(interface_, interfaceName_).c_str()); + ((StringHelper::StartWith(interfaceName_, "I") ? interfaceName_.substr(1) : interfaceName_) + + "Proxy").c_str()); sb.Append(prefix + TAB).AppendFormat("if (%s == nullptr) {\n", objName.c_str()); sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:iface_cast failed!\", __func__);\n"); sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); @@ -451,6 +476,89 @@ void CppClientProxyCodeEmitter::EmitProxyMethodImpls(StringBuilder &sb, const st } } +void CppClientProxyCodeEmitter::EmitProxyIsProxyMethodImpl(StringBuilder &sb, const std::string &prefix) const +{ + sb.Append(prefix).Append("inline bool IsProxy() override\n"); + sb.Append(prefix).Append("{\n"); + sb.Append(prefix + TAB).Append("return true;\n"); + sb.Append(prefix).Append("}\n\n"); +} + +void CppClientProxyCodeEmitter::EmitProxyCastFromMethodImpls(StringBuilder &sb, const std::string &prefix) const +{ + AutoPtr interface = interface_->GetExtendsInterface(); + while (interface != nullptr) { + EmitProxyCastFromMethodImpl(interface, sb, prefix); + sb.Append(prefix).Append("\n"); + interface = interface->GetExtendsInterface(); + } +} + +void CppClientProxyCodeEmitter::EmitProxyCastFromMethodImpl(const AutoPtr interface, + StringBuilder &sb, const std::string &prefix) const +{ + std::string currentInterface = EmitDefinitionByInterface(interface_, interfaceName_); + std::string parentInterface = EmitDefinitionByInterface(interface, interfaceName_); + + sb.Append(prefix).AppendFormat("sptr<%s> %s::CastFrom(const sptr<%s> &parent)\n", + currentInterface.c_str(), currentInterface.c_str(), parentInterface.c_str()); + sb.Append(prefix).Append("{\n"); + sb.Append(prefix + TAB).AppendFormat("return CastFromTemplate<%s, %s>(parent);\n", + currentInterface.c_str(), parentInterface.c_str()); + sb.Append(prefix).Append("}\n"); +} + +void CppClientProxyCodeEmitter::EmitProxyCastFromMethodImplTemplate(StringBuilder &sb, const std::string &prefix) const +{ + std::string serMajorName = "serMajorVer"; + std::string serMinorName = "serMinorVer"; + + sb.Append(prefix).Append("template\n"); + sb.Append(prefix).Append("static sptr CastFromTemplate(const sptr &parent)\n"); + sb.Append(prefix).Append("{\n"); + sb.Append(prefix + TAB).Append("if (parent == nullptr) {\n"); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:parent is nullptr!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).Append("if (!parent->IsProxy()) {\n"); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:not proxy, not support castfrom!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).AppendFormat("sptr remote = OHOS::HDI::hdi_objcast(parent);\n"); + sb.Append(prefix + TAB).Append("if (remote == nullptr) {\n"); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:hdi_objcast failed!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).AppendFormat("sptr proxy = OHOS::HDI::hdi_facecast(remote);\n"); + sb.Append(prefix + TAB).Append("if (proxy == nullptr) {\n"); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:hdi_facecast failed!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).AppendFormat("uint32_t %s = 0;\n", serMajorName.c_str()); + sb.Append(prefix + TAB).AppendFormat("uint32_t %s = 0;\n", serMinorName.c_str()); + sb.Append(prefix + TAB).AppendFormat("int32_t %s = proxy->GetVersion(%s, %s);\n", + errorCodeName_.c_str(), serMajorName.c_str(), serMinorName.c_str()); + sb.Append(prefix + TAB).AppendFormat("if (%s != HDF_SUCCESS) {\n", errorCodeName_.c_str()); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:get version failed!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).AppendFormat("if (%s != %d) {\n", serMajorName.c_str(), ast_->GetMajorVer()); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s:check version failed! "); + sb.Append("version of service:%u.%u"); + sb.AppendFormat(", version of client:%d.%d\", __func__, ", ast_->GetMajorVer(), ast_->GetMinorVer()); + sb.AppendFormat("%s, %s);\n", serMajorName.c_str(), serMinorName.c_str()); + sb.Append(prefix + TAB + TAB).Append("return nullptr;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); + + sb.Append(prefix + TAB).Append("return proxy;\n"); + sb.Append(prefix).Append("}\n"); +} + void CppClientProxyCodeEmitter::EmitProxyMethodImpl(const AutoPtr interface, const AutoPtr &method, StringBuilder &sb, const std::string &prefix) { @@ -542,7 +650,10 @@ void CppClientProxyCodeEmitter::EmitProxyStaticMethodBody( } } } - + sb.Append(prefix + TAB).AppendFormat("if (remote == nullptr) {\n"); + sb.Append(prefix + TAB + TAB).Append("HDF_LOGE(\"%{public}s: invalid remote object!\", __func__);\n"); + sb.Append(prefix + TAB + TAB).Append("return HDF_ERR_INVALID_OBJECT;\n"); + sb.Append(prefix + TAB).Append("}\n\n"); sb.Append(prefix + TAB).AppendFormat("int32_t %s = remote->SendRequest(%s, %s, %s, %s);\n", errorCodeName_.c_str(), EmitMethodCmdID(method).c_str(), dataParcelName_.c_str(), replyParcelName_.c_str(), optionName_.c_str()); sb.Append(prefix + TAB).AppendFormat("if (%s != HDF_SUCCESS) {\n", errorCodeName_.c_str()); diff --git a/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.h b/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.h index bb0eae80b1756b28c233c4fb8c4462b7c6bfdd5d..f04dc15134dbcb9db7643e0a5508d54b1f43e1e9 100644 --- a/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.h +++ b/framework/tools/hdi-gen/codegen/cpp_client_proxy_code_emitter.h @@ -30,6 +30,8 @@ private: void GetHeaderOtherLibInclusions(HeaderFile::HeaderFileSet &headerFiles) const; + void GetSourceOtherFileInclusions(HeaderFile::HeaderFileSet &headerFiles) const; + void EmitProxyDecl(StringBuilder &sb, const std::string &prefix); void EmitProxyConstructor(StringBuilder &sb, const std::string &prefix) const; @@ -83,6 +85,12 @@ private: void EmitProxyStaticMethodImpl(const AutoPtr &method, StringBuilder &sb, const std::string &prefix); void EmitProxyStaticMethodBody(const AutoPtr &method, StringBuilder &sb, const std::string &prefix); + + void EmitProxyIsProxyMethodImpl(StringBuilder &sb, const std::string &prefix) const; + void EmitProxyCastFromMethodImpls(StringBuilder &sb, const std::string &prefix) const; + void EmitProxyCastFromMethodImpl(const AutoPtr interface, StringBuilder &sb, + const std::string &prefix) const; + void EmitProxyCastFromMethodImplTemplate(StringBuilder &sb, const std::string &prefix) const; }; } // namespace HDI } // namespace OHOS diff --git a/framework/tools/hdi-gen/codegen/cpp_custom_types_code_emitter.cpp b/framework/tools/hdi-gen/codegen/cpp_custom_types_code_emitter.cpp index 7045e7e132d068c71c7991d8446fb33d7e6ab1b7..29be0230386eda6732cbb5fdb083dc31149e2a21 100644 --- a/framework/tools/hdi-gen/codegen/cpp_custom_types_code_emitter.cpp +++ b/framework/tools/hdi-gen/codegen/cpp_custom_types_code_emitter.cpp @@ -279,7 +279,7 @@ void CppCustomTypesCodeEmitter::EmitCustomTypeMarshallingImpl( { std::string objName("dataBlock"); - sb.AppendFormat("bool %sBlockMarshalling(OHOS::MessageParcel& data, const %s& %s)\n", type->EmitCppType().c_str(), + sb.AppendFormat("bool %sBlockMarshalling(OHOS::MessageParcel& data, const %s& %s)\n", type->GetName().c_str(), type->EmitCppType().c_str(), objName.c_str()); sb.Append("{\n"); diff --git a/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.cpp b/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.cpp index b8cd9fa9da1ad0d8e72b4c02a44a8f0f369fe5a7..91982cd02cc9b226e8c1f3b061de49944bb01a4c 100644 --- a/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.cpp +++ b/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.cpp @@ -124,6 +124,10 @@ void CppInterfaceCodeEmitter::EmitInterfaceDefinition(StringBuilder &sb) EmitGetMethodDecl(sb, TAB); sb.Append("\n"); } + if (interface_->GetExtendsInterface() != nullptr) { + EmitCastFromDecl(sb, TAB); + sb.Append("\n"); + } EmitInterfaceMethodsDecl(sb, TAB); sb.Append("\n"); EmitGetDescMethod(sb, TAB); @@ -150,6 +154,19 @@ void CppInterfaceCodeEmitter::EmitInterfaceDescriptor(StringBuilder &sb, const s sb.Append(TAB).AppendFormat("DECLARE_HDI_DESCRIPTOR(u\"%s\");\n", interfaceFullName_.c_str()); } +void CppInterfaceCodeEmitter::EmitCastFromDecl(StringBuilder &sb, const std::string &prefix) const +{ + std::string currentInterface = EmitDefinitionByInterface(interface_, interfaceName_); + + AutoPtr interface = interface_->GetExtendsInterface(); + while (interface != nullptr) { + std::string parentInterface = EmitDefinitionByInterface(interface, interfaceName_); + sb.Append(prefix).AppendFormat("static sptr<%s> CastFrom(const sptr<%s> &parent);\n", + currentInterface.c_str(), parentInterface.c_str()); + interface = interface->GetExtendsInterface(); + } +} + void CppInterfaceCodeEmitter::EmitGetMethodDecl(StringBuilder &sb, const std::string &prefix) const { sb.Append(prefix).AppendFormat("static %s Get(bool isStub = false);\n", interface_->EmitCppType().c_str()); @@ -170,6 +187,10 @@ void CppInterfaceCodeEmitter::EmitInterfaceMethodsDecl(StringBuilder &sb, const } EmitInterfaceGetVersionMethod(sb, prefix); + if (interface_->GetExtendsInterface() == nullptr) { + sb.Append("\n"); + EmitInterfaceIsProxyMethod(sb, prefix); + } } void CppInterfaceCodeEmitter::EmitInterfaceMethodDecl( @@ -225,6 +246,15 @@ void CppInterfaceCodeEmitter::EmitInterfaceGetVersionMethod(StringBuilder &sb, c sb.Append(prefix).Append("}\n"); } +void CppInterfaceCodeEmitter::EmitInterfaceIsProxyMethod(StringBuilder &sb, const std::string &prefix) const +{ + sb.Append(prefix).AppendFormat("virtual bool %s(", "IsProxy"); + sb.Append(")\n"); + sb.Append(prefix).Append("{\n"); + sb.Append(prefix + TAB).Append("return false;\n"); + sb.Append(prefix).Append("}\n"); +} + void CppInterfaceCodeEmitter::EmitInterfaceMethodParameter( const AutoPtr ¶m, StringBuilder &sb, const std::string &prefix) const { diff --git a/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.h b/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.h index e7d0fd079a5bcb29813177493a823b8444c03ab3..5a3a9f5843b895080b5d2a015a449093bb88e556 100644 --- a/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.h +++ b/framework/tools/hdi-gen/codegen/cpp_interface_code_emitter.h @@ -46,12 +46,15 @@ private: void EmitInterfaceGetVersionMethod(StringBuilder &sb, const std::string &prefix) const; + void EmitInterfaceIsProxyMethod(StringBuilder &sb, const std::string &prefix) const; + void EmitInterfaceMethodParameter( const AutoPtr ¶m, StringBuilder &sb, const std::string &prefix) const; void EmitInterfaceMethodCommandsWithExtends(StringBuilder &sb, const std::string &prefix); void EmitGetDescMethod(StringBuilder &sb, const std::string &prefix) const; + void EmitCastFromDecl(StringBuilder &sb, const std::string &prefix) const; }; } // namespace HDI } // namespace OHOS diff --git a/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.cpp b/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.cpp index 17ac7ce0ebbd1ad76f196f610a5fdb4689acb41a..e48f11c22207d5f0ae66d0a87f0fd0f4957eaf96 100644 --- a/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.cpp +++ b/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.cpp @@ -211,6 +211,7 @@ void CppServiceStubCodeEmitter::EmitStubSourceInclusions(StringBuilder &sb) HeaderFile::HeaderFileSet headerFiles; headerFiles.emplace(HeaderFileType::OWN_HEADER_FILE, EmitVersionHeaderName(stubName_)); GetSourceOtherLibInclusions(headerFiles); + GetSourceOtherFileInclusions(headerFiles); for (const auto &file : headerFiles) { sb.AppendFormat("%s\n", file.ToString().c_str()); @@ -254,6 +255,22 @@ void CppServiceStubCodeEmitter::GetSourceOtherLibInclusions(HeaderFile::HeaderFi headerFiles.emplace(HeaderFileType::OTHER_MODULES_HEADER_FILE, "hdf_log"); } +void CppServiceStubCodeEmitter::GetSourceOtherFileInclusions(HeaderFile::HeaderFileSet &headerFiles) const +{ + for (const auto &method : interface_->GetMethodsBySystem(Options::GetInstance().GetSystemLevel())) { + for (size_t paramIndex = 0; paramIndex < method->GetParameterNumber(); paramIndex++) { + AutoPtr param = method->GetParameter(paramIndex); + AutoPtr paramType = param->GetType(); + if (param->GetAttribute() == ParamAttr::PARAM_IN && + (param->GetType()->IsInterfaceType() || paramType->HasInnerType(TypeKind::TYPE_INTERFACE))) { + AutoPtr type = dynamic_cast(paramType.Get()); + std::string FileName = InterfaceToFilePath(paramType->ToString()); + headerFiles.emplace(HeaderFileType::OWN_MODULE_HEADER_FILE, FileName); + } + } + } +} + void CppServiceStubCodeEmitter::EmitInterfaceGetMethodImpl(StringBuilder &sb, const std::string &prefix) const { if (!interface_->IsSerializable()) { diff --git a/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.h b/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.h index aa115865037e4035e63c65dcbb687c3ce4f99e3f..1dfdb4e6ecab50e5d64e3ac8b8cef360f2f49174 100644 --- a/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.h +++ b/framework/tools/hdi-gen/codegen/cpp_service_stub_code_emitter.h @@ -54,6 +54,8 @@ private: void GetSourceOtherLibInclusions(HeaderFile::HeaderFileSet &headerFiles) const; + void GetSourceOtherFileInclusions(HeaderFile::HeaderFileSet &headerFiles) const; + void EmitInterfaceGetMethodImpl(StringBuilder &sb, const std::string &prefix) const; void EmitGetMethodImpl(StringBuilder &sb, const std::string &prefix) const; diff --git a/framework/tools/hdi-gen/parser/parser.cpp b/framework/tools/hdi-gen/parser/parser.cpp index de44c8992e31bf8e7c3fde12a64c4c8555ba984c..7f95b33b1f4f836ec7e259d4e60d1d124ed0234a 100644 --- a/framework/tools/hdi-gen/parser/parser.cpp +++ b/framework/tools/hdi-gen/parser/parser.cpp @@ -238,6 +238,11 @@ void Parser::ParseImportInfo() return; } + if (!CheckImportsVersion(importAst)) { + LogError(token, StringHelper::Format("extends import version must less than current import version")); + return; + } + if (!ast_->AddImport(importAst)) { LogError(token, StringHelper::Format("multiple import of '%s'", importName.c_str())); return; @@ -257,7 +262,7 @@ void Parser::ParseSequenceableInfo() size_t index = seqName.rfind('.'); if (index != std::string::npos) { seqType->SetName(seqName.substr(index + 1)); - seqType->SetNamespace(ast_->ParseNamespace(seqName.substr(0, index))); + seqType->SetNamespace(ast_->ParseNamespace(seqName)); } else { seqType->SetName(seqName); } @@ -610,7 +615,7 @@ void Parser::CheckMethodAttr(const AutoPtr &interface, const A { // if the attribute of method is empty, the default value is attribute of interface if (!method->IsMini() && !method->IsLite() && !method->IsFull()) { - method->GetAttribute()->SetValue(ASTAttr::FULL | ASTAttr::LITE | ASTAttr::MINI); + method->SetAttribute(interface->GetAttribute()); } if (!interface->IsMini() && method->IsMini()) { @@ -1050,6 +1055,7 @@ AutoPtr Parser::ParseEnumBaseType() case TypeKind::TYPE_USHORT: case TypeKind::TYPE_UINT: case TypeKind::TYPE_ULONG: + case TypeKind::TYPE_ENUM: break; default: { LogError(token, StringHelper::Format("illegal base type of enum", baseType->ToString().c_str())); @@ -1079,8 +1085,10 @@ void Parser::ParserEnumMember(const AutoPtr &enumType) } enumValue->SetType(enumType->GetBaseType()); - enumType->AddMember(enumValue); - + if (!enumType->AddMember(enumValue)) { + LogError(StringHelper::Format("AddMemberException:member '%s' already exists !", + enumValue->GetName().c_str())); + } token = lexer_.PeekToken(); if (token.kind == TokenType::COMMA) { lexer_.GetToken(); @@ -1793,6 +1801,14 @@ bool Parser::CheckExtendsVersion( return true; } +bool Parser::CheckImportsVersion(AutoPtr extendsAst) +{ + if (extendsAst->GetMajorVer() != ast_->GetMajorVer() || extendsAst->GetMinorVer() > ast_->GetMinorVer()) { + return false; + } + return true; +} + void Parser::SetInterfaceVersion(AutoPtr &interfaceType) { size_t majorVer = ast_->GetMajorVer(); diff --git a/framework/tools/hdi-gen/parser/parser.h b/framework/tools/hdi-gen/parser/parser.h index aac32b37e1d3920194d4b83bdacb54bbc916a29e..9b307f6ee9b23877e6263010bf2713b27d8394a3 100644 --- a/framework/tools/hdi-gen/parser/parser.h +++ b/framework/tools/hdi-gen/parser/parser.h @@ -194,6 +194,8 @@ private: bool CheckExtendsVersion( AutoPtr &interfaceType, const std::string &extendsName, AutoPtr extendsAst); + bool CheckImportsVersion(AutoPtr extendsAst); + void SetInterfaceVersion(AutoPtr &interfaceType); inline static bool IsPrimitiveType(Token token) diff --git a/interfaces/inner_api/osal/uhdf/hdf_log_adapter.h b/interfaces/inner_api/osal/uhdf/hdf_log_adapter.h index ae74b564210550a67be2c385ca3c27fabf9a05dd..a27a0fb978c9a36396f6ef2c6141266af1e99716 100644 --- a/interfaces/inner_api/osal/uhdf/hdf_log_adapter.h +++ b/interfaces/inner_api/osal/uhdf/hdf_log_adapter.h @@ -46,7 +46,7 @@ extern "C" { * @brief Defines the log domain of the HDF. */ #undef LOG_DOMAIN -#define LOG_DOMAIN 0xD002500 +#define LOG_DOMAIN 0xD002510 /** * @brief Defines the default log label of the HDF. diff --git a/interfaces/inner_api/utils/hdf_base.h b/interfaces/inner_api/utils/hdf_base.h index 2e8405334e32e984eb31417525d24fcf133c3693..165b4b9959c517e92e6418bd9f614d61d662880c 100644 --- a/interfaces/inner_api/utils/hdf_base.h +++ b/interfaces/inner_api/utils/hdf_base.h @@ -125,7 +125,7 @@ typedef enum { /** * @brief Declares the full path of the HDF module library. */ -#ifdef __aarch64__ +#if (defined(__aarch64__) || defined(__x86_64__)) #define HDF_LIBRARY_FULL_PATH(x) "/vendor/lib64/" x ".z.so" #else #define HDF_LIBRARY_FULL_PATH(x) "/vendor/lib/" x ".z.so"