code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
internal fun ComposeView1500Text() {
// val startTime = remember { getTimeMillis() }
//
// // 等待首帧绘制完毕后输出耗时
// LaunchedEffect(Unit) {
// val duration = getTimeMillis() - startTime
// println("dzy Compose 页面构建 + 渲染耗时:${duration}ms")
// }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(1500) { index ->
Text(
text = "Item #$index",
fontSize = 16.sp,
modifier = Modifier
.width(300.dp)
.height(50.dp)
.border(1.dp, Color.Gray)
.padding(10.dp)
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeText1500.kt | Kotlin | apache-2.0 | 1,335 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeText1500CApi() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(500) { index ->
ArkUIView(
name = "cApiSingleText",
modifier = Modifier
.width(300.dp)
.height(50.dp),
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeText1500CApi.kt | Kotlin | apache-2.0 | 1,437 |
package com.tencent.compose.sample
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
//import androidx.compose.ui.Modifier
import kotlinx.cinterop.ExperimentalForeignApi
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.runtime.*
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import test725.print_const_string
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun ComposeToCPage() {
// 创建滚动状态
val scrollState = rememberScrollState()
// 存储滚动距离(像素)
var scrollPosition by remember { mutableStateOf(0) }
// 使用dp单位记录滚动距离
val scrollPositionDp = with(LocalDensity.current) { scrollPosition.toDp() }
var count = 0;
// 监听滚动状态变化
LaunchedEffect(scrollState.value) {
count = count + 1;
print_const_string("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789")
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(scrollState) // 启用垂直滚动
) {
// 生成长列表(100个条目)
repeat(100) { index ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(4.dp)
.background(Color.LightGray),
contentAlignment = Alignment.Center
) {
Text("列表项 #$index")
}
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeToC.kt.kt | Kotlin | apache-2.0 | 3,649 |
package com.tencent.compose.sample
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.image_cat
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.layout.onGloballyPositioned
import test725.trace_tag_begin
import test725.trace_tag_end
import test725.trace_tag_cnt
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.cstr
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun ComposeView1500Page() {
val loaded = remember { mutableStateOf(false) }
// val startTime = remember { getTimeMillis() }
//
// LaunchedEffect(Unit) {
// trace_tag_begin()
// val duration = getTimeMillis() - startTime
// println("dzy Compose 页面构建 + 渲染耗时:${duration}ms")
// }
// SideEffect {
// trace_tag_end()
// }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
// trace_tag_begin()
// 创建1500个Box
repeat(1500) { index ->
Box(
modifier = Modifier
.size(300.dp, 100.dp) // 设置宽高均为300dp
.border(
width = 2.dp, // 边框宽度
color = Color.Red, // 边框颜色为红色
)
.then(
if (index == 1499) Modifier.onGloballyPositioned {
// 最后一个 Box 被布局 -> 页面“加载完成”
loaded.value = true
trace_tag_end()
} else Modifier
)
) {
Text(
text = "Item #$index",
)
}
}
// trace_tag_end()
}
if (loaded.value) {
// 可以做其它“加载完成”后的逻辑
println("页面加载完成 ✅")
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeView1500.kt | Kotlin | apache-2.0 | 3,576 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeView1500CApi() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(300) { index ->
ArkUIView(
name = "cApiStackSingleView",
modifier = Modifier
.size(300.dp, 100.dp)
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeView1500CApi.kt | Kotlin | apache-2.0 | 1,315 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.material.Button
import test725.crash_in_c
import kotlinx.cinterop.ExperimentalForeignApi
import androidx.compose.ui.napi.JsEnv
import com.tencent.compose.utils.TsFoo
import com.tencent.compose.utils.TsEnv
import com.tencent.compose.utils.FooObject
import kotlinx.cinterop.*
@Composable
@OptIn(ExperimentalForeignApi::class)
internal fun Dfx() {
// Replace Kotlin-managed array OOB (which throws) with a native-heap overflow
// that can be detected by AddressSanitizer when the binary is built/linked with ASan.
triggerHeapBufferOverflow()
Column(Modifier.fillMaxWidth().fillMaxHeight().padding(30.dp)) {
Button(onClick = {
val arr = arrayOf(0, 1, 2);
arr[3] = 3;
}) {
Text("C->K 崩溃")
}
Button(onClick = {
crash_in_c()
}) {
Text("C->K->C 崩溃")
}
Button(onClick = {
}) {
Text("dump内存")
}
Button(onClick = {
println("KN: js_leak start:")
fooTest()
}) {
Text("触发js_leak")
}
}
}
// --- ASan test helpers ---
@OptIn(ExperimentalForeignApi::class)
fun triggerHeapBufferOverflow() {
println("KN: triggerHeapBufferOverflow allocating 1 byte and writing 1024 bytes")
val p = nativeHeap.allocArray<ByteVar>(1)
// Overwrite far beyond the allocated 1 byte -> should trigger ASan heap-buffer-overflow
// Use explicit writes to avoid C function signature mismatches.
for (i in 0 until 1024) {
p[i] = 0.toByte()
}
// Free (may not be reached if ASan aborts)
nativeHeap.free(p)
}
@OptIn(ExperimentalForeignApi::class)
fun fooTest() {
println("KN: fooTest call start:")
val loopCount = 10
val foo = FooObject(
id = "rootId",
boolValue = true,
intValue = 1000,
longValue = 10001000L,
doubleValue = 101.2123,
cache = arrayOf(FooObject(id = "id2", fooValue = FooObject(id = "id3", longValue = 20001000))),
fooValue = FooObject(id = "id2", fooValue = FooObject(id = "id3", longValue = 20001000))
)
val global = JsEnv.getGlobal()
val funcName = JsEnv.createStringUtf8("fooArkTsFunc1")
val func1 = JsEnv.getProperty(global, funcName)
println("KN: fooTest call start 2:")
TsEnv.callFunction(global, func1, TsFoo.toNapiValue(foo))
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/Dfx.kt | Kotlin | apache-2.0 | 2,635 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
internal fun FfiBenchmark() {
Column() {
ArkUIView(
name = "FfiBenchmark",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/FfiBenchmark.kt | Kotlin | apache-2.0 | 501 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalForeignApi::class, ExperimentalResourceApi::class)
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.skia.Image
import platform.resource.OH_ResourceManager_CloseRawFile
import platform.resource.OH_ResourceManager_GetRawFileSize
import platform.resource.OH_ResourceManager_OpenRawFile
import platform.resource.OH_ResourceManager_ReadRawFile
typealias NativeResourceManager = CPointer<cnames.structs.NativeResourceManager>?
var nativeResourceManager: NativeResourceManager = null
private val emptyImageBitmap: ImageBitmap by lazy { ImageBitmap(1, 1) }
@Composable
internal actual fun rememberLocalImage(id: DrawableResource): ImageBitmap {
var imageBitmap: ImageBitmap by remember { mutableStateOf(emptyImageBitmap) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, id.resourceItemPath())
val size = OH_ResourceManager_GetRawFileSize(rawFile)
val buffer = ByteArray(size.toInt())
buffer.usePinned { pinnedBuffer ->
OH_ResourceManager_ReadRawFile(rawFile, pinnedBuffer.addressOf(0), size.toULong())
}
OH_ResourceManager_CloseRawFile(rawFile)
imageBitmap = Image.makeFromEncoded(buffer).toComposeImageBitmap()
}
}
return imageBitmap
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/Images.ohosArm64.kt | Kotlin | apache-2.0 | 2,846 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.asString
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.*
import test725.*
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun InteropButton() {
Column(Modifier.fillMaxWidth().fillMaxHeight().padding(30.dp)) {
Button(onClick = {
println("KN: testNum call start:")
var res = testNum(10)
println("KN: testNum result: $res")
}) {
Text("Append Text")
}
Button(onClick = { testMemScoped() }) {
Text("testMemScoped")
}
}
}
@OptIn(ExperimentalForeignApi::class)
fun testMemScoped() {
memScoped {
// 分配内存(包括 null 终止符)
val buffer = allocArray<ByteVar>(5) // "abcd" + '\0'
// 写入数据
buffer[0] = 'a'.code.toByte()
buffer[1] = 'b'.code.toByte()
buffer[2] = 'c'.code.toByte()
buffer[3] = 'd'.code.toByte()
buffer[4] = 0 // Null 终止符
// 传递指针给 C
print_string(buffer)
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropButton.kt | Kotlin | apache-2.0 | 2,689 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
@Composable
internal fun InteropListNested() {
Box {
Column(Modifier.background(Color.LightGray)) {
LazyColumn(Modifier.background(Color.Red)) {
items(80) { index ->
when (index) {
1 -> {
ArkUIView(
name = "verticalList",
modifier = Modifier.width(250.dp).height(300.dp),
parameter = js {
"text"("ArkUI Button $index")
"backgroundColor"("#FF0000FF")
}
)
}
3 -> {
ArkUIView(
name = "horizontalList",
modifier = Modifier.width(250.dp).height(300.dp),
parameter = js {
"text"("ArkUI Button $index")
"backgroundColor"("#FFFF00FF")
}
)
}
else -> {
Button({
println("Compose Button $index clicked")
}, modifier = Modifier.height(50.dp).fillMaxWidth()) {
Text("Compose Button $index")
}
}
}
}
}
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropListNested.kt | Kotlin | apache-2.0 | 3,005 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
@Composable
internal fun InteropListSimple() {
Box {
Column(Modifier.background(Color.LightGray).fillMaxSize()) {
LazyColumn(Modifier.background(Color.Red).fillMaxSize()) {
items(80) { index ->
Column {
ArkUIView(
name = "label",
modifier = Modifier.width(250.dp).height(100.dp),
parameter = js {
"text"("ArkUI Button $index")
"backgroundColor"("#FF0000FF")
},
)
Button({
println("Compose Button $index clicked")
}, modifier = Modifier.height(30.dp).fillMaxWidth()) {
Text("Compose Button $index")
}
}
}
}
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropListSimple.kt | Kotlin | apache-2.0 | 2,425 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
@Composable
internal fun InteropRenderOrder() {
// // 触发kotlin的crash
// val arr = IntArray(5)
// arr[5] = 1
var interLayer by remember { mutableStateOf(false) }
Column {
Box {
ArkUIView(
"layer", Modifier.width(400.dp).height(300.dp),
js {
"text"("1")
"backgroundColor"("#FF0000FF")
},
)
ArkUIView(
"layer", Modifier.width(350.dp).height(250.dp),
js {
"text"("2")
"backgroundColor"("#FF00FF00")
},
)
if (interLayer) {
ArkUIView(
"layer", Modifier.width(300.dp).height(200.dp),
js {
"text"("3")
"backgroundColor"("#FFFF0000")
},
)
}
ArkUIView(
"layer", Modifier.width(250.dp).height(150.dp),
js {
"text"("4")
"backgroundColor"("#FF00FFFF")
},
)
ArkUIView(
"layer", Modifier.width(200.dp).height(100.dp),
js {
"text"("5")
"backgroundColor"("#FFFFFF00")
},
)
}
Button({ interLayer = !interLayer }) {
Text("Show / Hide")
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropRenderOrder.kt | Kotlin | apache-2.0 | 2,874 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.asString
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun InteropTextInput() {
Column(Modifier.fillMaxWidth().fillMaxHeight().padding(30.dp)) {
var inputText by remember { mutableStateOf("混排状态变量双向通信 输入文本...") }
val state = remember(inputText) {
js { "text"(inputText) }
}
ArkUIView(
name = "textInput",
modifier = Modifier.width(450.dp).wrapContentHeight(),
parameter = state,
update = {
inputText = it["text"].asString().toString()
}
)
Spacer(modifier = Modifier.height(50.dp))
Text(text = "Compose组件更新:", color = Color.Gray)
Text(
text = inputText,
modifier = Modifier.fillMaxWidth()
.border(width = 1.dp, color = Color.Gray)
.padding(10.dp)
)
Button(onClick = { inputText += "[文本]" }) {
Text("Append Text")
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropTextInput.kt | Kotlin | apache-2.0 | 2,777 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.asString
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun InteropVideo() {
Column() {
ArkUIView(
name = "video",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropVideo.kt | Kotlin | apache-2.0 | 2,014 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.napi.asString
import androidx.compose.ui.napi.js
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun InteropWebView() {
Column() {
ArkUIView(
name = "webView",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/InteropWebView.kt | Kotlin | apache-2.0 | 2,018 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun KotlinNativeArktsPage() {
// kotlin native arkts 相互调用测试,页面入口
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(500) { index ->
ArkUIView(
name = "kotlinNativeArktsPage",
modifier = Modifier
.fillMaxWidth()
.height(220.dp),
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/KotlinNativeArktsPage.kt | Kotlin | apache-2.0 | 1,412 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
@Composable
internal fun NestedLayerEntry() {
var depth by remember { mutableStateOf<Int?>(null) }
if (depth == null) {
NestedLayerInputScreen { enteredDepth ->
depth = enteredDepth
}
} else {
NestedLayerScreen(
depth = depth!!,
onBack = { depth = null }
)
}
}
@Composable
internal fun NestedLayerInputScreen(onGenerate: (Int) -> Unit) {
var text by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
Scaffold(
topBar = { TopAppBar(title = { Text("嵌套层数") }) }
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.padding(16.dp)
) {
OutlinedTextField(
value = text,
onValueChange = { text = it; error = null },
label = { Text("嵌套层数") },
isError = error != null,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true
)
Spacer(Modifier.height(20.dp))
Button(onClick = {
val depth = text.toIntOrNull()
if (depth == null || depth < 0 || depth > 5000) {
error = "input layer number"
} else {
onGenerate(depth)
}
}) {
Text("生成 layers")
}
}
}
}
@Composable
internal fun NestedLayerScreen(depth: Int, onBack: () -> Unit) {
var currentLayer: @Composable () -> Unit = { Text("Inner Text") }
repeat(depth) {
val prev = currentLayer
currentLayer = { Row (modifier = Modifier.wrapContentWidth()) { prev() } }
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("嵌套层数:$depth") },
navigationIcon = {
TextButton(onClick = onBack) { Text("Back") }
}
)
}
) { padding ->
Box(
modifier = Modifier
.padding(padding)
.padding(12.dp),
contentAlignment = Alignment.TopStart
) {
currentLayer()
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/NestedLayer.kt | Kotlin | apache-2.0 | 3,369 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.backhandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.platform.LocalArkUIViewController
@Composable
internal actual fun BackHandler(enable: Boolean, onBack: () -> Unit) {
val onBackPressedDispatcher = LocalArkUIViewController.current.onBackPressedDispatcher
val enableState by rememberUpdatedState(enable)
DisposableEffect(Unit) {
val cancel = onBackPressedDispatcher.addOnBackPressedCallback {
if (enableState) {
onBack()
true
} else {
false
}
}
onDispose(cancel)
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/backhandler/BackHandler.ohosArm64.kt | Kotlin | apache-2.0 | 1,536 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage
import com.tencent.compose.sample.AutoScrollingInfiniteList
import com.tencent.compose.sample.CApiView1500Image
import com.tencent.compose.sample.InteropListNested
import com.tencent.compose.sample.InteropListSimple
import com.tencent.compose.sample.InteropRenderOrder
import com.tencent.compose.sample.InteropButton
import com.tencent.compose.sample.InteropTextInput
import com.tencent.compose.sample.InteropVideo
import com.tencent.compose.sample.InteropWebView
import com.tencent.compose.sample.ComposeView1500Page
import com.tencent.compose.sample.CApiView1500Page
import com.tencent.compose.sample.CApiView1500Text
import com.tencent.compose.sample.CircularReferenceDemo
import com.tencent.compose.sample.ComposeLazyView1500Page
import com.tencent.compose.sample.ComposeImage1500CApi
import com.tencent.compose.sample.KotlinNativeArktsPage
import com.tencent.compose.sample.ComposeLazy1500ViewWithString
import com.tencent.compose.sample.ComposeText1500CApi
import com.tencent.compose.sample.ComposeToCPage
import com.tencent.compose.sample.ComposeView1500CApi
import com.tencent.compose.sample.ComposeView1500Text
import com.tencent.compose.sample.FfiBenchmark
import com.tencent.compose.sample.NestedLayerEntry
import com.tencent.compose.sample.data.DisplayItem
import com.tencent.compose.sample.Dfx
import com.tencent.compose.sample.mainpage.sectionItem.composeView1500Page
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.interop_list
import composesample.composeapp.generated.resources.interop_nested_scroll
import composesample.composeapp.generated.resources.interop_state
import composesample.composeapp.generated.resources.layers
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
internal actual fun platformSections(): List<DisplayItem> {
return listOf(
DisplayItem("混排层级", Res.drawable.layers) { InteropRenderOrder() },
DisplayItem("混排滑动", Res.drawable.interop_list) { InteropListSimple() },
DisplayItem("混排嵌滑", Res.drawable.interop_nested_scroll) { InteropListNested() },
DisplayItem("混排状态", Res.drawable.interop_state) { InteropTextInput() },
DisplayItem("InteropButton", Res.drawable.interop_state) { InteropButton() },
DisplayItem("FfiBenchmark", Res.drawable.layers) { FfiBenchmark() },
DisplayItem("短视频", Res.drawable.interop_state) { InteropVideo() },
DisplayItem("WebView", Res.drawable.interop_state) { InteropWebView() },
DisplayItem("Kotlin to C", Res.drawable.interop_state) { ComposeToCPage() },
DisplayItem("Compose 1500View", Res.drawable.interop_state) { ComposeView1500Page() },
DisplayItem("Compose Lazy 1500View", Res.drawable.interop_state) { ComposeLazyView1500Page()},
DisplayItem("CApi 1500View", Res.drawable.interop_state) { CApiView1500Page() },
DisplayItem("Compose 1500View CApi", Res.drawable.interop_state) { ComposeView1500CApi() },
DisplayItem("Compose 1500Text", Res.drawable.interop_state) { ComposeView1500Text() },
DisplayItem("CApi 1500Text", Res.drawable.interop_state) { CApiView1500Text() },
DisplayItem("Compose 1500Text CApi", Res.drawable.interop_state) { ComposeText1500CApi() },
DisplayItem("CApi 1500Image", Res.drawable.interop_state) { CApiView1500Image() },
DisplayItem("Compose 1500Image CApi", Res.drawable.interop_state) { ComposeImage1500CApi() },
DisplayItem("Kotlin Native Arkts", Res.drawable.interop_state) { KotlinNativeArktsPage() },
DisplayItem("AutoScrollingInfiniteList", Res.drawable.interop_state) { AutoScrollingInfiniteList() },
DisplayItem("Circular Reference Demo", Res.drawable.interop_state) { CircularReferenceDemo() },
DisplayItem("组件嵌套 Demo", Res.drawable.interop_state) { NestedLayerEntry() },
DisplayItem("滑动+字符串 Demo", Res.drawable.interop_state) { ComposeLazy1500ViewWithString() },
DisplayItem("DFX", Res.drawable.interop_state) { Dfx() },
DisplayItem("1500view2.2ohos-04", Res.drawable.interop_state) { composeView1500Page() },
)
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.ohosArm64.kt | Kotlin | apache-2.0 | 4,983 |
@file:OptIn(ExperimentalForeignApi::class)
package com.tencent.compose.utils
import androidx.compose.ui.napi.JsEnv
import kotlinx.cinterop.ExperimentalForeignApi
import platform.ohos.napi_value
data class FooObject(
val id: String,
val strValue: String = "test0911",
val boolValue: Boolean = false,
val intValue: Int = 0,
val longValue: Long = 0,
val doubleValue: Double = 0.0,
val cache: Array<FooObject> = arrayOf(),
val fooValue: FooObject? = null // 使用可空类型避免无限递归
)
fun JsEnv.setNamedProperty(obj: napi_value?, key: String, value: napi_value?) {
JsEnv.setProperty(obj, JsEnv.createStringUtf8(key), value)
}
fun TsEnv.setNamedProperty(obj: napi_value?, key: String, value: napi_value?) {
TsEnv.setProperty(obj, TsEnv.createStringUtf8(key), value)
}
object JsFoo {
fun toNapiValue(foo: FooObject?): napi_value? {
if (foo == null) return null
val obj = JsEnv.createObject() ?: return null
JsEnv.setNamedProperty(obj, "id", JsEnv.createStringUtf8(foo.id))
JsEnv.setNamedProperty(obj, "strValue", JsEnv.createStringUtf8(foo.strValue))
JsEnv.setNamedProperty(obj, "boolValue", JsEnv.getBoolean(foo.boolValue))
JsEnv.setNamedProperty(obj, "intValue", JsEnv.createInt32(foo.intValue))
JsEnv.setNamedProperty(obj, "longValue", JsEnv.createInt64(foo.longValue))
JsEnv.setNamedProperty(obj, "doubleValue", JsEnv.createDouble(foo.doubleValue))
JsEnv.setNamedProperty(obj, "cache", JsEnv.createDouble(foo.doubleValue))
if (foo.fooValue != null) {
JsEnv.setNamedProperty(obj, "fooValue", toNapiValue(foo.fooValue))
} else {
JsEnv.setNamedProperty(obj, "fooValue", null)
}
return obj
}
fun toFooObject(value: napi_value?): FooObject? {
if (value == null) return null
val id =
JsEnv.getNamedProperty(value, "id")?.let { JsEnv.getValueStringUtf8(it) } ?: return null
val strValue =
JsEnv.getNamedProperty(value, "strValue")?.let { JsEnv.getValueStringUtf8(it) } ?: ""
val boolValue =
JsEnv.getNamedProperty(value, "boolValue")?.let { JsEnv.getValueBool(it) } ?: false
val intValue =
JsEnv.getNamedProperty(value, "intValue")?.let { JsEnv.getValueInt32(it) } ?: 0
val longValue =
JsEnv.getNamedProperty(value, "longValue")?.let { JsEnv.getValueInt64(it) } ?: 0L
val doubleValue =
JsEnv.getNamedProperty(value, "doubleValue")?.let { JsEnv.getValueDouble(it) } ?: 0.0
val fooValue = JsEnv.getNamedProperty(value, "fooValue")?.let { toFooObject(it) }
return FooObject(id, strValue, boolValue, intValue, longValue, doubleValue, arrayOf(), fooValue)
}
}
object TsFoo {
fun toNapiValue(foo: FooObject?): napi_value? {
if (foo == null) return null
val obj = TsEnv.createObject() ?: return null
TsEnv.setNamedProperty(obj, "id", TsEnv.createStringUtf8(foo.id))
TsEnv.setNamedProperty(obj, "strValue", TsEnv.createStringUtf8(foo.strValue))
TsEnv.setNamedProperty(obj, "boolValue", TsEnv.getBoolean(foo.boolValue))
TsEnv.setNamedProperty(obj, "intValue", TsEnv.createInt32(foo.intValue))
TsEnv.setNamedProperty(obj, "longValue", TsEnv.createInt64(foo.longValue))
TsEnv.setNamedProperty(obj, "doubleValue", TsEnv.createDouble(foo.doubleValue))
if (foo.fooValue != null) {
TsEnv.setNamedProperty(obj, "fooValue", toNapiValue(foo.fooValue))
} else {
TsEnv.setNamedProperty(obj, "fooValue", null)
}
return obj
}
fun toFooObject(value: napi_value?): FooObject? {
if (value == null) return null
val id =
TsEnv.getNamedProperty(value, "id")?.let { TsEnv.getValueStringUtf8(it) } ?: return null
val strValue =
TsEnv.getNamedProperty(value, "strValue")?.let { TsEnv.getValueStringUtf8(it) } ?: ""
val boolValue =
TsEnv.getNamedProperty(value, "boolValue")?.let { TsEnv.getValueBool(it) } ?: false
val intValue =
TsEnv.getNamedProperty(value, "intValue")?.let { TsEnv.getValueInt32(it) } ?: 0
val longValue =
TsEnv.getNamedProperty(value, "longValue")?.let { TsEnv.getValueInt64(it) } ?: 0L
val doubleValue =
TsEnv.getNamedProperty(value, "doubleValue")?.let { TsEnv.getValueDouble(it) } ?: 0.0
val fooValue = TsEnv.getNamedProperty(value, "fooValue")?.let { toFooObject(it) }
return FooObject(id, strValue, boolValue, intValue, longValue, doubleValue, arrayOf(),fooValue)
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/utils/FooObject.kt | Kotlin | apache-2.0 | 4,684 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalForeignApi::class)
package com.tencent.compose.utils
import androidx.compose.ui.graphics.kLog
import androidx.compose.ui.graphics.isDebugLogEnabled
import androidx.compose.ui.napi.JsCallContext
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.asStableRef
import kotlinx.cinterop.cValuesOf
import kotlinx.cinterop.get
import kotlinx.cinterop.staticCFunction
import kotlinx.cinterop.toKString
import platform.ohos.napi_acquire_threadsafe_function
import platform.ohos.napi_call_threadsafe_function
import platform.ohos.napi_callback
import platform.ohos.napi_callback_info
import platform.ohos.napi_delete_reference
import platform.ohos.napi_env
import platform.ohos.napi_ok
import platform.ohos.napi_ref
import platform.ohos.napi_set_element
import platform.ohos.napi_set_property
import platform.ohos.napi_status
import platform.ohos.napi_threadsafe_function
import platform.ohos.napi_threadsafe_function_call_js
import platform.ohos.napi_threadsafe_function_call_mode
import platform.ohos.napi_value
import platform.ohos.napi_valuetype
import platform.napiwrapper.*
object TsEnv {
private var globalNApiEnv: napi_env? = null
fun init(env: napi_env) {
globalNApiEnv = env
}
fun env(): napi_env = globalNApiEnv ?: error("napi_env is not initialized. Call JsEnv.init(env) first.")
private fun checkStatus(status: napi_status): Boolean {
if (status != napi_ok) {
if (isDebugLogEnabled) {
kLog("napi failed: $status")
}
return false
}
return true
}
fun getElement(obj: napi_value?, index: Int): napi_value? {
obj ?: return null
return kn_get_element(env(), obj, index)
}
fun setElement(obj: napi_value?, index: Int, value: napi_value?) {
obj ?: return
checkStatus(napi_set_element(env(), obj, index.toUInt(), value))
}
fun getArrayLength(array: napi_value?): Int {
array ?: return 0
return kn_get_array_length(env(), array).toInt()
}
fun getAllPropertyNames(obj: napi_value?): napi_value? {
return kn_get_property_names(env(), obj)
}
fun strictEquals(trgObject: napi_value?, srcObject: napi_value?): Boolean {
return kn_equals(env(), trgObject, srcObject)
}
fun getProperty(obj: napi_value?, key: napi_value?): napi_value? {
obj ?: return null
key ?: return null
return kn_get_property(env(), obj, key)
}
fun setProperty(obj: napi_value?, key: napi_value?, value: napi_value?) {
obj ?: return
key ?: return
checkStatus(napi_set_property(env(), obj, key, value ?: getNull()))
}
fun getNamedProperty(obj: napi_value?, str: String): napi_value? {
obj ?: return null
return kn_get_named_property(env(), obj, str)
}
fun createObject(): napi_value? {
return kn_create_object(env())
}
fun getReferenceValue(ref: napi_ref?): napi_value? {
ref ?: return null
return kn_get_reference_value(env(), ref)
}
fun createReference(value: napi_value?): napi_ref? {
return kn_create_reference(env(), value)
}
fun deleteReference(ref: napi_ref?) {
ref ?: return
checkStatus(napi_delete_reference(env(), ref))
}
fun createFunction(name: String?, cb: napi_callback?, data: COpaquePointer?): napi_value? {
return kn_create_function(env(), name, cb, data)
}
fun callFunction(
receiver: napi_value?,
func: napi_value?,
vararg args: napi_value?
): napi_value? {
func ?: return null
return kn_call_function(
env(),
receiver,
func,
args.size,
cValuesOf(*args),
null
)
}
fun createStringUtf8(str: String): napi_value? {
return kn_string_to_napi(env(), str)
}
fun createDouble(value: Double): napi_value? {
return kn_double_to_napi(env(), value)
}
fun createFloat(value: Float): napi_value? = createDouble(value.toDouble())
fun createObjectWithWrap(value: Any): napi_value? {
val obj = kn_create_object(env())
val valueRef = StableRef.create(value)
kn_wrap(
env(),
obj,
valueRef.asCPointer(),
staticCFunction { _: napi_env?, data: COpaquePointer?, _: COpaquePointer? ->
if (data == null) return@staticCFunction
data.asStableRef<Any>().dispose()
})
return obj
}
fun getBoolean(value: Boolean): napi_value? {
return kn_boolean_to_napi(env(), value)
}
fun createInt32(value: Int): napi_value? {
return kn_int_to_napi(env(), value)
}
fun createInt64(value: Long): napi_value? {
return kn_long_to_napi(env(), value)
}
fun getValueInt32(value: napi_value?): Int? {
value ?: return null
return kn_to_int(env(), value)
}
fun getValueInt32(value: napi_value?, default: Int): Int {
value ?: return default
return kn_to_int(env(), value) ?: default
}
fun getValueInt64(value: napi_value?): Long? {
value ?: return null
return kn_to_long(env(), value)
}
fun getValueInt64(value: napi_value?, default: Long): Long {
value ?: return default
return kn_to_long(env(), value) ?: default
}
fun getValueDouble(value: napi_value?): Double? {
value ?: return null
return kn_to_double(env(), value)
}
fun getValueFloat(value: napi_value?): Float? = getValueDouble(value)?.toFloat()
fun getValueStringUtf8(value: napi_value?): String? {
value ?: return null
return kn_to_string(env(), value)?.toKString()
}
fun getValueBool(value: napi_value?): Boolean? {
value ?: return null
return kn_to_boolean(env(), value)
}
fun getUndefined(): napi_value? {
return kn_get_undefined(env())
}
fun isUndefined(value: napi_value?): Boolean =
getType(value) == napi_valuetype.napi_undefined
private fun getNull(): napi_value? {
return kn_get_null(env())
}
fun getType(value: napi_value?): napi_valuetype? {
return kn_typeof(env(), value)
}
fun getCbInfo(callbackInfo: napi_callback_info?): JsCallContext {
val argc = kn_get_cb_info_argc(env(), callbackInfo)
val args = kn_get_cb_info_args(env(), callbackInfo, argc)
val jsThis = kn_get_cb_info_jsThis(env(), callbackInfo)
val data = kn_get_cb_info_data(env(), callbackInfo)
val arguments = ArrayList<napi_value?>()
for (i in 0..<argc) {
arguments.add(args?.get(i))
}
return JsCallContext(jsThis, arguments, data)
}
fun getGlobal(): napi_value? {
return kn_get_global(env())
}
fun createThreadsafeFunction(
workName: String,
callback: napi_threadsafe_function_call_js?
): napi_threadsafe_function? {
return kn_create_threadsafe_function_with_callback(
env(),
workName,
callback
)
}
fun callThreadsafeFunction(function: napi_threadsafe_function?, data: COpaquePointer?) {
napi_acquire_threadsafe_function(function)
napi_call_threadsafe_function(
function, data, napi_threadsafe_function_call_mode.napi_tsfn_nonblocking
)
}
fun stringify(value: napi_value?): String? {
val global = getGlobal()
val json = getProperty(global, createStringUtf8("JSON"))
val stringifyFunc = getProperty(json, createStringUtf8("stringify"))
val result = callFunction(json, stringifyFunc, value)
return getValueStringUtf8(result)
}
fun printValue(value: napi_value?, key: String? = "") {
val type = getType(value)
when (type) {
napi_valuetype.napi_undefined -> kLog("JsEnv::printValue: $key is undefined")
napi_valuetype.napi_null -> kLog("JsEnv::printValue: $key is null")
napi_valuetype.napi_symbol -> kLog("JsEnv::printValue: $key is symbol")
napi_valuetype.napi_object -> kLog("JsEnv::printValue: $key is object")
napi_valuetype.napi_function -> kLog("JsEnv::printValue: $key is function")
napi_valuetype.napi_number -> kLog("JsEnv::printValue: $key is number")
napi_valuetype.napi_string -> kLog("JsEnv::printValue: $key is string")
napi_valuetype.napi_boolean -> kLog("JsEnv::printValue: $key is boolean")
napi_valuetype.napi_bigint -> kLog("JsEnv::printValue: $key is bigint")
napi_valuetype.napi_external -> kLog("JsEnv::printValue: $key is external")
null -> kLog("JsEnv::printValue: $key is null")
else -> {}
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/utils/TsEnv.kt | Kotlin | apache-2.0 | 9,704 |
@file:OptIn(ExperimentalForeignApi::class)
package com.tencent.compose.utils
import androidx.compose.ui.napi.JsEnv
import kotlinx.cinterop.*
import platform.ohos.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.time.measureTime
import com.tencent.compose.utils.TsEnv
private fun BridgeForGlobalKNStringParams(env: napi_env?, info: napi_callback_info?): napi_value? {
val params = JsEnv.getCbInfo(info).arguments
// val params = info!!.params(1)
var arg0: String?
val duration = measureTime {
arg0 = params[0]!!.asString()
}
println("KN: BridgeForGlobalKNStringParams time=${duration.inWholeNanoseconds} ns")
val result = kn_string_params(arg0)
if (result == null) {
return null
}
return null
}
private fun BridgeForGlobalKNStringResult(env: napi_env?, info: napi_callback_info?): napi_value? {
val result = kn_string_result()
if (result == null) {
return null
}
var str: napi_value?
val duration = measureTime {
str = createString(result)
}
println("KN: BridgeForGlobalKNStringResult time=${duration.inWholeNanoseconds} ns")
return str;
}
// origin functions
fun kn_string_params(a: String?) {
// val len = a.length
}
const val TestString = "Kotlin: a1aa,a,a1aa,Ga,baa,Ja,bb,rb,sb,vb,Bb,eaa,Pb,Vb,bc,cc,dc,ec,fc,hc,lc,faa,gaa,nc,qc,Bc,Ec,Kc,Lc,Fc,kd,ud,Ed,Hd,oaa,Wd,raa,taa,ce,oe,uaa,Ee,Ce,Fe,B,Xe,af,gf,mf,xf,Cf,Lf,zaa,Aaa,Baa,Caa,Qf,Tf,ag,cg,gg,kg,ng,Gaa,Haa,Iaa,Jaa,Kaa,Laa,Gg,Maa,Naa,Og,Sg,Oaa,Taa,Raa,gh,Uaa,Yaa,qh,th, aa,aba,vh,Jh,eba,fba,Oh,gba,ai,iba,di,pi,jba,kba,qi,ri,si,lba,mba,nba,yi,oba,pba,uba,rba,sba,tba,vba,Ai,hi,Mi,Ni,Aba,Cba,Dba,Ri,Fba,Gba,Iba,Jba,Kba,Mba,Nba,aa,hj,ij,Oba,kj,Rba,tj,Sba,Tba,Ej,Fj,Uba; _.ba=function(a){return function(){return aa[a].apply(this,arguments)}};_.ca=function(a,b){return aa[a]=b};_.da=function(a){_.n.setTimeout(function(){throw a;},0)};_.ea=function(a){a&&typeof a.dispose== function &&a.dispose()};ia=function(a){for(var b=0,c=arguments.length;b<c;++b){var d=arguments[b];_.fa(d)?ia.apply(null,d):_.ea(d)}}; _.ja=function(a,b){if(Error.captureStackTrace)Error.captureStackTrace(this,_.ja);else{var c=Error().stack;c&&(this.stack=c)}a&&(this.message=String(a));b!==void 0&&(this.cause=b);this.j=!0};_.ka=function(a){return a[a.length-1]};_.la=function(a,b,c){for(var d=typeof a=== string ?a.split( ):a,e=a.length-1;e>=0;--e)e in d&&b.call(c,d[e],e,a)};_.na=function(a,b,c){b=_.ma(a,b,c);return b<0?null:typeof a=== string ?a.charAt(b):a[b]}; _.ma=function(a,b,c){for(var d=a.length,e=typeof a=== string ?a.split( ):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return f;return-1};_.qa=function(a,b){return(0,_.pa)(a,b)>=0};_.ra=function(a,b){_.qa(a,b)||a.push(b)};_.ta=function(a,b){b=(0,_.pa)(a,b);var c;(c=b>=0)&&_.sa(a,b);return c};_.sa=function(a,b){return Array.prototype.splice.call(a,b,1).length==1};_.ua=function(a){return Array.prototype.concat.apply([],arguments)}; _.va=function(a){var b=a.length;if(b>0){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]};_.wa=function(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c];if(_.fa(d)){var e=a.length||0,f=d.length||0;a.length=e+f;for(var g=0;g<f;g++)a[e+g]=d[g]}else a.push(d)}};_.ya=function(a,b,c){return arguments.length<=2?Array.prototype.slice.call(a,b):Array.prototype.slice.call(a,b,c)}; _.Ba=function(a,b){b=b||a;for(var c=0,d=0,e={};d<a.length;){var f=a[d++],g=_.za(f)? o +_.Aa(f):(typeof f).charAt(0)+f;Object.prototype.hasOwnProperty.call(e,g)||(e[g]=!0,b[c++]=f)}b.length=c};_.Ca=function(a,b){if(!_.fa(a)||!_.fa(b)||a.length!=b.length)return!1;for(var c=a.length,d=aaa,e=0;e<c;e++)if(!d(a[e],b[e]))return!1;return!0};_.Da=function(a,b){return a>b?1:a<b?-1:0};aaa=function(a,b){return a===b};_.Fa=function(a,b){var c={};(0,_.Ea)(a,function(d,e){c[b.call(void 0,d,e,a)]=d});return c}; Ga=function(a){return{valueOf:a}.valueOf()};baa=function(){var a=null;if(!Ha)return a;try{var b=function(c){return c};a=Ha.createPolicy( OneGoogleWidgetUi#html ,{createHTML:b,createScript:b,createScriptURL:b})}catch(c){}return a};Ja=function(){Ia===void 0&&(Ia=baa());return Ia};_.Ma=function(a){var b=Ja();a=b?b.createHTML(a):a;return new _.Ka(_.La,a)};_.Na=function(a){return a instanceof _.Ka};_.Oa=function(a){if(_.Na(a))return a.j;throw Error( u );}; _.Qa=function(a){return function ==typeof _.Pa&&a instanceof _.Pa};_.Ra=function(a){if(_.Qa(a))return a.j;throw Error( u );};_.Ta=function(a){var b=Ja();a=b?b.createScriptURL(a):a;return new _.Sa(_.La,a)};_.Ua=function(a){return a instanceof _.Sa};_.Va=function(a){if(_.Ua(a))return a.j;throw Error( u );};_.Xa=function(a){return new _.Wa(_.La,a)};_.Ya=function(a){return a instanceof _.Wa};_.Za=function(a){if(_.Ya(a))return a.j;throw Error( u );}; bb=function(a){return new ab(function(b){return b.substr(0,a.length+1).toLowerCase()===a+ : })};_.eb=function(a,b){b=b===void 0?_.cb:b;if(_.Ya(a))return a;for(var c=0;c<b.length;++c){var d=b[c];if(d instanceof ab&&d.Tj(a))return _.Xa(a)}};_.gb=function(a){var b=!caa.test(a);b&&_.fb(a);if(!b)return a};_.hb=function(a){return a instanceof _.Wa?_.Za(a):_.gb(a)};_.jb=function(a){var b=Ja();a=b?b.createScript(a):a;return new _.ib(_.La,a)};_.kb=function(a){return a instanceof _.ib}; _.lb=function(a){if(_.kb(a))return a.j;throw Error( u );};_.nb=function(a,b){if(_.Na(a))return a;a=_.mb(String(a));if(b==null?0:b.V8)a=a.replace(/(^|[\\r\\n\\t ]) /g, 1  );if(b==null?0:b.U8)a=a.replace(/(\\r\\n|\\n|\\r)/g, <br> );if(b==null?0:b.X8)a=a.replace(/(\\t+)/g,'<span style= white-space:pre > 1</span>');return _.Ma(a)};_.mb=function(a){return a.replace(/&/g, & ).replace(/</g, < ).replace(/>/g, > ).replace(/ /g, " ).replace(/'/g, ' )}; _.pb=function(a){var b=_.ob.apply(1,arguments);if(b.length===0)return _.Ta(a[0]);for(var c=a[0],d=0;d<b.length;d++)c+=encodeURIComponent(b[d])+a[d+1];return _.Ta(c)};rb=function(a){a=a.Ox.charCodeAt(a.Mb++);return qb[a]};sb=function(a){var b=0,c=0;do{var d=rb(a);b|=(d&31)<<c;c+=5}while(d&32);return b<0?b+4294967296:b};vb=function(a){if(_.tb)a(_.tb);else{var b;((b=ub)!=null?b:ub=[]).push(a)}};_.yb=function(){!_.tb&&_.wb&&_.xb(_.wb());return _.tb}; _.xb=function(a){_.tb=a;var b;(b=ub)==null||b.forEach(vb);ub=void 0};_.u=function(a){_.tb&&daa(a)};_.w=function(){_.tb&&Ab(_.tb)};Bb=function(a,b){a.__closure__error__context__984382||(a.__closure__error__context__984382={});a.__closure__error__context__984382.severity=b};eaa=function(){for(var a;a=Cb.remove();){try{a.Lh.call(a.scope)}catch(b){_.da(b)}Db(Eb,a)}Fb=!1};_.Gb=function(a,b,c){for(var d in a)b.call(c,a[d],d,a)}; _.Hb=function(a,b){var c={},d;for(d in a)b.call(void 0,a[d],d,a)&&(c[d]=a[d]);return c};_.Ib=function(a,b,c){var d={},e;for(e in a)d[e]=b.call(c,a[e],e,a);return d};_.Jb=function(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b};_.Kb=function(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b};_.Lb=function(a){for(var b in a)return!1;return!0};_.Mb=function(a){var b={},c;for(c in a)b[c]=a[c];return b}; _.Ob=function(a,b){for(var c,d,e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<Nb.length;f++)c=Nb[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c])}};Pb=function(a){var b=arguments.length;if(b==1&&Array.isArray(arguments[0]))return Pb.apply(null,arguments[0]);for(var c={},d=0;d<b;d++)c[arguments[d]]=!0;return c};_.Qb=function(a,b){return a.lastIndexOf(b,0)==0};_.Rb=function(a,b){var c=a.length-b.length;return c>=0&&a.indexOf(b,c)==c};_.Sb=function(a){return/^[\\s\\xa0]* /.test(a)}; _.Tb=function(a,b){return a.indexOf(b)!=-1};_.Wb=function(a,b){var c=0;a=(0,_.Ub)(String(a)).split( . );b=(0,_.Ub)(String(b)).split( . );for(var d=Math.max(a.length,b.length),e=0;c==0&&e<d;e++){var f=a[e]|| ,g=b[e]|| ;do{f=/( *)( *)(.*)/.exec(f)||[ , , , ];g=/( *)( *)(.*)/.exec(g)||[ , , , ];if(f[0].length==0&&g[0].length==0)break;c=Vb(f[1].length==0?0:parseInt(f[1],10),g[1].length==0?0:parseInt(g[1],10))||Vb(f[2].length==0,g[2].length==0)||Vb(f[2],g[2]);f=f[3];g=g[3]}while(c==0)}return c}; Vb=function(a,b){return a<b?-1:a>b?1:0};_.Xb=function(){var a=_.n.navigator;return a&&(a=a.userAgent)?a: };bc=function(a){if(! b||!ac)return!1;for(var b=0;b<ac.brands.length;b++){var c=ac.brands[b].brand;if(c&&_.Tb(c,a))return!0}return!1};cc=function(a){return _.Tb(_.Xb(),a)};dc=function(){return b?!!ac&&ac.brands.length>0:!1};ec=function(){return dc()?!1:cc( Opera )};fc=function(){return dc()?!1:cc( Trident )||cc( MSIE )};hc=function(){return dc()?bc( Microsoft Edge ):cc( Edg/ )}; _.ic=function(){return cc( Firefox )||cc( FxiOS )};_.kc=function(){return cc( Safari )&&!(_.jc()||(dc()?0:cc( Coast ))||ec()||(dc()?0:cc( Edge ))||hc()||(dc()?bc( Opera ):cc( OPR ))||_.ic()||cc( Silk )||cc( Android ))};_.jc=function(){return dc()?bc( Chromium ):(cc( Chrome )||cc( CriOS ))&&!(dc()?0:cc( Edge ))||cc( Silk )};lc=function(){return cc( Android )&&!(_.jc()||_.ic()||ec()||cc( Silk ))}; faa=function(a){var b={};a.forEach(function(c){b[c[0]]=c[1]});return function(c){return b[c.find(function(d){return d in b})]|| }}; gaa=function(a){var b=_.Xb();if(a=== Internet Explorer ){if(fc())if((a=/rv: *([ \\.]*)/.exec(b))&&a[1])b=a[1];else{a= ;var c=/MSIE +([ \\.]+)/.exec(b);if(c&&c[1])if(b=/Trident\\/( . )/.exec(b),c[1]== 7.0 )if(b&&b[1])switch(b[1]){case 4.0 :a= 8.0 ;break;case 5.0 :a= 9.0 ;break;case 6.0 :a= 10.0 ;break;case 7.0 :a= 11.0 }else a= 7.0 ;else a=c[1];b=a}else b= ;return b}var d=RegExp( ([A-Z][\\\\w ]+)/([^\\\\s]+)\\\\s*(?:\\\\((.*?)\\\\))? , g );c=[];for(var e;e=d.exec(b);)c.push([e[1],e[2],e[3]||void 0]); b=faa(c);switch(a){case Opera :if(ec())return b([ Version , Opera ]);if(dc()?bc( Opera ):cc( OPR ))return b([ OPR ]);break;case Microsoft Edge :if(dc()?0:cc( Edge ))return b([ Edge ]);if(hc())return b([ Edg ]);break;case Chromium :if(_.jc())return b([ Chrome , CriOS , HeadlessChrome ])}return a=== Firefox &&_.ic()||a=== Safari &&_.kc()||a=== Android Browser &&lc()||a=== Silk &&cc( Silk )?(b=c[2])&&b[1]|| : }; _.mc=function(a){if(dc()&&a!== Silk ){var b=ac.brands.find(function(c){return c.brand===a});if(!b||!b.version)return NaN;b=b.version.split( . )}else{b=gaa(a);if(b=== )return NaN;b=b.split( . )}return b.length===0?NaN:Number(b[0])};nc=function(){return b?!!ac&&!!ac.platform:!1};_.pc=function(){return nc()?ac.platform=== Android :cc( Android )};qc=function(){return cc( iPhone )&&!cc( iPod )&&!cc( iPad )};_.rc=function(){return qc()||cc( iPad )||cc( iPod )}; _.sc=function(){return nc()?ac.platform=== macOS :cc( Macintosh )};_.tc=function(){return nc()?ac.platform=== Windows :cc( Windows )};_.uc=function(){return nc()?ac.platform=== Chrome OS :cc( CrOS )};_.vc=function(a){return haa&&a!=null&&a instanceof Uint8Array};_.wc=function(){return typeof BigInt=== function };_.xc=function(a){a.b8=!0;return a}; rome ])}return a=== Firefox &&_.ic()||a=== Safari &&_.kc()||a=== Android Browser &&lc()||a=== Silk &&cc( Silk )?(b=c[2])&&b[1]|| : }; _.mc=function(a){if(dc()&&a!== Silk ){var b=ac.brands.find(function(c){return c.brand===a});if(!b||!b.version)return NaN;b=b.version.split( . )}else{b=gaa(a);if(b=== )return NaN;b=b.split( . )}return b.length===0?NaN:Number(b[0])};nc=function(){return b?!!ac&&!!ac.platform:!1};_.pc=function(){return nc()?ac.platform=== Android :cc( Android )};qc=function(){return cc("
fun kn_string_result(): String {
return TestString
}
private fun BridgeForOriginStringParams(env: napi_env?, info: napi_callback_info?): napi_value? {
val params = JsEnv.getCbInfo(info).arguments
// val params = info!!.params(1)
// val arg0 = params[0]!!.asString()
var arg0: String?
val duration = measureTime {
arg0 = JsEnv.getValueStringUtf8(params[0])
}
println("KN: BridgeForOriginStringParams time=${duration.inWholeNanoseconds} ns")
val result = kn_string_params(arg0)
if (result == null) {
return null
}
return null
}
private fun BridgeForOriginStringResult(env: napi_env?, info: napi_callback_info?): napi_value? {
val result = kn_string_result()
if (result == null) {
return null
}
// return createString(result)
val res: napi_value?
var duration = measureTime {
res = JsEnv.createStringUtf8(result)
}
println("KN: BridgeForOriginStringResult time=${duration.inWholeNanoseconds} ns")
return res
}
// define function
@CName("define_string_function")
@OptIn(ExperimentalNativeApi::class)
fun defineStringFunction(env: napi_env, exports: napi_value?) {
JsEnv.init(env)
TsEnv.init(env)
val descArray = nativeHeap.allocArray<napi_property_descriptor>(4)
descArray[0].name = createString("kn_string_params")
descArray[0].method = staticCFunction(::BridgeForGlobalKNStringParams)
descArray[0].attributes = napi_default
descArray[1].name = createString("kn_string_result")
descArray[1].method = staticCFunction(::BridgeForGlobalKNStringResult)
descArray[1].attributes = napi_default
descArray[2].name = createString("origin_string_params")
descArray[2].method = staticCFunction(::BridgeForOriginStringParams)
descArray[2].attributes = napi_default
descArray[3].name = createString("origin_string_result")
descArray[3].method = staticCFunction(::BridgeForOriginStringResult)
descArray[3].attributes = napi_default
println("KN: defineStringFunction tag1")
val res = napi_define_properties(env, exports, 4u, descArray)
println("KN: defineStringFunction tag3, res=$res")
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/utils/string.kt | Kotlin | apache-2.0 | 13,463 |
@file:OptIn(ExperimentalForeignApi::class)
package com.tencent.compose.utils
import androidx.compose.ui.napi.JsEnv
import androidx.compose.ui.napi.asString
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.NativePtr
import kotlinx.cinterop.interpretCPointer
import platform.ohos.napi_value
@OptIn(ExperimentalForeignApi::class)
fun napi_value.asString(): String? {
// return napi_get_kotlin_string_utf16(JsEnv.env().rawValue, this.rawValue)
//TODO bug need to be fixed
return ""
}
fun napi_value.asStringUtf8(): String? {
return JsEnv.getValueStringUtf8(this)
}
fun createString(value: String): napi_value? {
val nativePtr: NativePtr = JsEnv.env().rawValue
// val result: napi_value? = interpretCPointer(value.getNapiValue(nativePtr))
//TODO bug need to be fixed
// val str1 = result.asString()
// val str2 = result?.asStringUtf8()
// println("kn: result.asString length=${str1?.length}, result=${str1}, charArray=${toPrintChar(str1)}")
// println("kn: result.asStringUtf8 length=${str2?.length}, result=${str2}, charArray=${toPrintChar(str2)}")
return null
}
fun toPrintChar(asString: String?): List<String>? {
return asString?.split("")?.map { item -> "(${item.length},${item})" }
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/utils/utils.kt | Kotlin | apache-2.0 | 1,262 |
/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { harTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
} | 2201_76010299/Compose_huawei_benchmark | harmonyApp/commons/base/hvigorfile.ts | TypeScript | apache-2.0 | 836 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/hvigorfile.ts | TypeScript | apache-2.0 | 970 |
# the minimum version of CMake.
cmake_minimum_required(VERSION 3.5.0)
project(harmonyApp)
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
if(DEFINED PACKAGE_FIND_FILE)
include(${PACKAGE_FIND_FILE})
endif()
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include)
find_package(skikobridge)
add_library(entry SHARED test725.cpp container.cpp manager.cpp napi_init.cpp kn_wrapper.cpp)
find_library(
hilog-lib
hilog_ndk.z
)
find_library(
libace-lib
ace_ndk.z
)
find_library(
libnapi-lib
ace_napi.z
)
target_link_libraries(entry PUBLIC libace_napi.z.so)
target_link_libraries(entry PUBLIC libdeviceinfo_ndk.z.so)
target_link_libraries(entry PUBLIC librawfile.z.so)
target_link_libraries(entry PUBLIC ${NATIVERENDER_ROOT_PATH}/../../../libs/arm64-v8a/libkn.so)
target_link_libraries(entry PUBLIC skikobridge::skikobridge)
target_link_libraries(entry PUBLIC ${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib} libc++_shared.so)
target_link_libraries(entry PUBLIC libhitrace_ndk.z.so) | 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/CMakeLists.txt | CMake | apache-2.0 | 1,090 |
#include <string>
#include <hilog/log.h>
#include "container.h"
namespace NativeXComponentSample {
std::unordered_map<std::string, Container *> Container::instance_;
Container::Container(const std::string &id) {
this->id_ = id;
}
Container *Container::GetInstance(const std::string &id) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "TextXXX container.cpp GetInstance");
if (instance_.find(id) == instance_.end()) {
Container *instance = new Container(id);
instance_[id] = instance;
return instance;
} else {
return instance_[id];
}
}
void Container::Release(const std::string &id) {
Container *render = Container::GetInstance(id);
if (render != nullptr) {
free(render);
}
}
void Container::RegisterCallback(OH_NativeXComponent *nativeXComponent) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "TextXXX container.cpp RegisterCallback");
}
} | 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/container.cpp | C++ | apache-2.0 | 958 |
//
// Created on 2025/7/21.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".
#ifndef HARMONYAPP_CONTAINER_H
#define HARMONYAPP_CONTAINER_H
#include <string>
#include <unordered_map>
#include <ace/xcomponent/native_interface_xcomponent.h>
const unsigned int LOG_PRINT_DOMAIN = 0xFF00;
namespace NativeXComponentSample {
class Container {
public:
explicit Container(const std::string &id);
~Container() = default;
static Container *GetInstance(const std::string &id);
static void Release(const std::string &id);
void RegisterCallback(OH_NativeXComponent *nativeXComponent);
public:
static std::unordered_map<std::string, Container *> instance_;
std::string id_;
private:
OH_NativeXComponent_Callback containerCallback_;
OH_NativeXComponent_MouseEvent_Callback mouseCallback_;
};
}
#endif //HARMONYAPP_CONTAINER_H
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/container.h | C++ | apache-2.0 | 958 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "hitrace/trace.h"
#include <string>
#include <sstream>
struct HiTraceSystraceSection {
public:
template <typename... ConvertsToStringPiece>
explicit HiTraceSystraceSection(
const char *name,
ConvertsToStringPiece &&...args) {
std::ostringstream oss;
(oss << ... << args);
std::string result = std::string(name) + oss.str();
OH_HiTrace_StartTrace(result.c_str());
}
~HiTraceSystraceSection() {
OH_HiTrace_FinishTrace();
}
};
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/include/HiTraceSystraceSection.h | C++ | apache-2.0 | 714 |
#ifndef GLOBAL_TEST_0725_H
#define GLOBAL_TEST_0725_H
#include <napi/native_api.h>
#ifdef __cplusplus
extern "C" {
#endif
napi_value kn_create_array(napi_env env);
uint32_t kn_get_array_length(napi_env env, napi_value value);
napi_value kn_get_element(napi_env env, napi_value value, int index);
void kn_set_element(napi_env env, napi_value array, int index, napi_value value);
bool kn_is_array(napi_env env, napi_value value);
bool kn_is_arraybuffer(napi_env env, napi_value value);
bool kn_is_typedarray(napi_env env, napi_value value);
size_t kn_get_arraybuffer_length(napi_env env, napi_value value);
uint8_t *kn_get_arraybuffer_value(napi_env env, napi_value value);
napi_typedarray_type kn_get_typedarray_type(napi_env env, napi_value value);
uint8_t *kn_get_typedarray_value(napi_env env, napi_value value);
size_t kn_get_typedarray_length(napi_env env, napi_value value);
napi_value kn_create_arraybuffer(napi_env env, uint8_t *ptr, size_t length);
size_t kn_get_typedarray_item_size(napi_typedarray_type typed);
napi_value kn_create_typedarray(napi_env env, uint8_t *data, size_t count, napi_typedarray_type typed);
int kn_get_cb_info_argc(napi_env env, napi_callback_info info);
void *kn_get_cb_info_data(napi_env env, napi_callback_info info);
napi_value *kn_get_cb_info_args(napi_env env, napi_callback_info info, int size);
napi_value kn_get_cb_info_jsThis(napi_env env, napi_callback_info info);
napi_value kn_new_instance(napi_env env, napi_value constructor);
//typedef void *(*callJSFunction)(void *data);
//struct CallbackData;
napi_value kn_call_function(napi_env env, napi_value recv, napi_value func, int size, const napi_value *argv,
napi_value *exceptionObj);
napi_value kn_create_function(napi_env env, const char *name, napi_callback callback, void *release);
napi_threadsafe_function kn_create_threadsafe_function_with_callback(napi_env env, const char *workName, void *callback);
void kn_call_threadsafe_function_with_data(napi_threadsafe_function tsfn, void *data);
static void kn_call_js(napi_env env, napi_value noUsed, void *context, void *data);
napi_threadsafe_function kn_create_threadsafe_function_sync(napi_env env, const char *workName);
void *kn_call_threadsafe_function(napi_threadsafe_function tsfn, void *callback, void *data, bool sync, int tsfnOriginTid);
napi_status kn_load_module_with_info(napi_env env, const char *path, const char *module_info, napi_value *result);
napi_status kn_load_module(napi_env env, const char *path, napi_value *result);
napi_value kn_create_object(napi_env env);
napi_value kn_get_global(napi_env env);
napi_value kn_get_undefined(napi_env env);
napi_value kn_get_null(napi_env env);
void kn_wrap(napi_env env, napi_value js_object, void *finalize_data, void *finalize_cb);
void *kn_unwrap(napi_env env, napi_value js_object);
bool kn_equals(napi_env env, napi_value a, napi_value b);
bool kn_instanceof(napi_env env, napi_value constructor, napi_value object);
napi_value kn_get_property_names(napi_env env, napi_value value);
napi_value kn_get_property(napi_env env, napi_value obj, napi_value key);
napi_value kn_get_named_property(napi_env env, napi_value obj, const char *key);
void kn_set_named_property(napi_env env, napi_value obj, const char *key, napi_value value);
napi_ref kn_create_reference(napi_env env, napi_value value);
void kn_delete_reference(napi_env env, napi_ref ref);
napi_value kn_get_reference_value(napi_env env, napi_ref ref);
char *kn_to_string(napi_env env, napi_value value);
napi_value kn_string_to_napi(napi_env env, const char *value);
int kn_to_int(napi_env env, napi_value value);
napi_value kn_int_to_napi(napi_env env, int value);
long kn_to_long(napi_env env, napi_value value);
napi_value kn_long_to_napi(napi_env env, long value);
bool kn_to_boolean(napi_env env, napi_value value);
napi_value kn_boolean_to_napi(napi_env env, bool value);
double kn_to_double(napi_env env, napi_value value);
napi_value kn_double_to_napi(napi_env env, double value);
napi_valuetype kn_typeof(napi_env env, napi_value value);
#ifdef __cplusplus
};
#endif
/** @} */
#endif // GLOBAL_TEST_0725_H
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/include/kn_wrapper.h | C | apache-2.0 | 4,178 |
#ifndef GLOBAL_TEST_0725_H
#define GLOBAL_TEST_0725_H
#include <js_native_api.h>
#include <js_native_api_types.h>
#ifdef __cplusplus
extern "C" {
#endif
void crash_in_c();
int KotlinCallNative(int num, napi_env env, napi_callback_info info);
int testNum(int num);
void print_string(char* msg);
void print_const_string(const char* msg);
void trace_tag_begin();
void trace_tag_end();
void trace_tag_cnt(int num);
typedef void (*register_callback_holder)(int, void*);
void native_register(void* kotlin_obj, register_callback_holder callback, bool holdRef);
void native_trigger();
void native_register_simple_callback(const char* id, void* stable_ref, void (*callback)(void*));
void native_trigger_simple_callback(const char* id);
void native_cleanup_simple_callback(const char* id);
void native_cleanup_all_simple_callbacks();
int native_get_simple_callback_count();
void native_print_simple_callback_status();
#ifdef __cplusplus
};
#endif
/** @} */
#endif // GLOBAL_TEST_0725_H
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/include/test_0725.h | C | apache-2.0 | 983 |
#include "kn_wrapper.h"
#include <cstdint>
#include <future>
#include <napi/native_api.h>
#include <string>
#include <unistd.h>
#include "HiTraceSystraceSection.h"
#include "hilog/log.h"
napi_value kn_create_array(napi_env env) {
napi_value array;
napi_create_array(env, &array);
return array;
}
uint32_t kn_get_array_length(napi_env env, napi_value value) {
uint32_t length;
napi_get_array_length(env, value, &length);
return length;
}
napi_value kn_get_element(napi_env env, napi_value value, int index) {
napi_value result;
napi_get_element(env, value, index, &result);
return result;
}
void kn_set_element(napi_env env, napi_value array, int index, napi_value value) {
napi_set_element(env, array, index, value);
}
bool kn_is_array(napi_env env, napi_value value) {
bool result = false;
napi_is_array(env, value, &result);
return result;
}
bool kn_is_arraybuffer(napi_env env, napi_value value) {
bool isArrayBuffer;
napi_is_arraybuffer(env, value, &isArrayBuffer);
return isArrayBuffer;
}
bool kn_is_typedarray(napi_env env, napi_value value) {
bool isTypedArray;
napi_is_typedarray(env, value, &isTypedArray);
return isTypedArray;
}
size_t kn_get_arraybuffer_length(napi_env env, napi_value value) {
size_t length;
void *data;
napi_get_arraybuffer_info(env, value, &data, &length);
return length;
}
uint8_t *kn_get_arraybuffer_value(napi_env env, napi_value value) {
void *data;
size_t length;
napi_get_arraybuffer_info(env, value, &data, &length);
return static_cast<uint8_t *>(data);
}
napi_typedarray_type kn_get_typedarray_type(napi_env env, napi_value value) {
napi_typedarray_type type;
napi_value buffer;
size_t length;
size_t offset;
void *data;
napi_get_typedarray_info(env, value, &type, &length, &data, &buffer, &offset);
return type;
}
uint8_t *kn_get_typedarray_value(napi_env env, napi_value value) {
napi_typedarray_type type;
napi_value buffer;
size_t length;
size_t offset;
void *data;
napi_get_typedarray_info(env, value, &type, &length, &data, &buffer, &offset);
return static_cast<uint8_t *>(data);
}
size_t kn_get_typedarray_length(napi_env env, napi_value value) {
napi_typedarray_type type;
napi_value buffer;
size_t length;
size_t offset;
void *data;
napi_get_typedarray_info(env, value, &type, &length, &data, &buffer, &offset);
return length;
}
napi_value kn_create_arraybuffer(napi_env env, uint8_t *ptr, size_t length) {
napi_value arrayBuffer;
uint8_t *outputBuff = nullptr;
napi_create_arraybuffer(env, length, reinterpret_cast<void **>(&outputBuff), &arrayBuffer);
uint8_t *inputBytes = ptr;
for (size_t i = 0; i < length; i++) {
outputBuff[i] = inputBytes[i];
}
return arrayBuffer;
}
size_t kn_get_typedarray_item_size(napi_typedarray_type typed) {
size_t size = 1;
switch (typed) {
case napi_int8_array:
case napi_uint8_array:
case napi_uint8_clamped_array:
size = 1;
break;
case napi_int16_array:
case napi_uint16_array:
size = sizeof(uint16_t);
break;
case napi_int32_array:
case napi_uint32_array:
size = sizeof(uint32_t);
break;
case napi_float32_array:
size = sizeof(float);
break;
case napi_float64_array:
size = sizeof(double);
break;
case napi_bigint64_array:
case napi_biguint64_array:
size = sizeof(uint64_t);
break;
default:
size = 1;
break;
}
return size;
}
napi_value kn_create_typedarray(napi_env env, uint8_t *data, size_t count, napi_typedarray_type typed) {
size_t length = count * kn_get_typedarray_item_size(typed);
napi_value arrayBuffer = kn_create_arraybuffer(env, data, length);
napi_value typedArray;
napi_create_typedarray(env, typed, count, arrayBuffer, 0, &typedArray);
return typedArray;
}
int kn_get_cb_info_argc(napi_env env, napi_callback_info info) {
size_t argc;
napi_get_cb_info(env, info, &argc, NULL, NULL, NULL);
return argc;
}
void *kn_get_cb_info_data(napi_env env, napi_callback_info info) {
void *data = NULL;
napi_get_cb_info(env, info, 0, NULL, NULL, &data);
return data;
}
napi_value *kn_get_cb_info_args(napi_env env, napi_callback_info info, int size) {
size_t argc = (size_t)size;
napi_value *args = (napi_value *)malloc((size) * sizeof(napi_value));
napi_get_cb_info(env, info, &argc, args, NULL, NULL);
return args;
}
napi_value kn_get_cb_info_jsThis(napi_env env, napi_callback_info info) {
napi_value jsThis;
napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, nullptr);
return jsThis;
}
napi_value kn_new_instance(napi_env env, napi_value constructor) {
napi_value result;
napi_new_instance(env, constructor, 0, NULL, &result);
return result;
}
typedef void *(*callJSFunction)(void *data);
#ifdef DEBUG
// 同步调用最大超时时间
constexpr int kThreadSafeFunctionMaxTimeoutSeconds = 10;
#endif
struct CallbackData {
void *data;
void *callback;
std::promise<void *> result;
bool sync;
};
napi_value kn_call_function(napi_env env, napi_value recv, napi_value func, int size, const napi_value *argv,
napi_value *exceptionObj) {
napi_value result;
auto status = napi_call_function(env, recv, func, size, argv, &result);
if (exceptionObj != nullptr && status == napi_pending_exception) {
napi_get_and_clear_last_exception(env, exceptionObj);
}
return result;
}
napi_value kn_create_function(napi_env env, const char *name, napi_callback callback, void *release) {
napi_value result;
napi_create_function(env, name, NAPI_AUTO_LENGTH, callback, release, &result);
return result;
}
napi_threadsafe_function kn_create_threadsafe_function_with_callback(napi_env env, const char *workName, void *callback) {
napi_value workNameNapiValue = 0;
napi_create_string_utf8(env, workName, NAPI_AUTO_LENGTH, &workNameNapiValue);
napi_threadsafe_function tsfn;
napi_create_threadsafe_function(env, 0, NULL, workNameNapiValue, 0, 1, NULL, NULL, NULL,
(napi_threadsafe_function_call_js)callback, &tsfn);
return tsfn;
}
void kn_call_threadsafe_function_with_data(napi_threadsafe_function tsfn, void *data) {
napi_acquire_threadsafe_function(tsfn);
napi_call_threadsafe_function(tsfn, data, napi_tsfn_nonblocking);
}
static void kn_call_js(napi_env env, napi_value noUsed, void *context, void *data) {
auto *callbackData = reinterpret_cast<CallbackData *>(data);
napi_handle_scope scope;
napi_open_handle_scope(env, &scope);
auto callback = (callJSFunction)callbackData->callback;
auto result = callback(callbackData->data);
if (callbackData->sync) {
callbackData->result.set_value(result);
}
napi_close_handle_scope(env, scope);
}
napi_threadsafe_function kn_create_threadsafe_function_sync(napi_env env, const char *workName) {
napi_value workNameNapiValue = nullptr;
napi_create_string_utf8(env, workName, NAPI_AUTO_LENGTH, &workNameNapiValue);
napi_threadsafe_function tsfn;
napi_create_threadsafe_function(env, 0, NULL, workNameNapiValue, 0, 1, NULL, NULL, NULL,
(napi_threadsafe_function_call_js)kn_call_js, &tsfn);
return tsfn;
}
void *kn_call_threadsafe_function(napi_threadsafe_function tsfn, void *callback, void *data, bool sync, int tsfnOriginTid) {
napi_acquire_threadsafe_function(tsfn);
auto *callbackData = new CallbackData{.data = data, .callback = callback, .result = {}, .sync = sync};
auto mainTid = getpid();
if (tsfnOriginTid == mainTid) {
napi_call_threadsafe_function_with_priority(tsfn, callbackData, napi_priority_high, true);
} else {
napi_call_threadsafe_function(tsfn, reinterpret_cast<void *>(callbackData), napi_tsfn_blocking);
}
if (sync) {
auto future = callbackData->result.get_future();
#ifdef DEBUG
if (tsfnOriginTid == mainTid) {
return future.get();
} else {
auto state = future.wait_for(std::chrono::seconds(kThreadSafeFunctionMaxTimeoutSeconds));
if (state == std::future_status::ready) {
return future.get();
} else {
OH_LOG_Print(LogType::LOG_APP, LOG_INFO, 1u, "knoi", "thread safe function timeout.");
abort();
}
}
#else
return future.get();
#endif
} else {
return nullptr;
}
}
napi_status kn_load_module_with_info(napi_env env, const char *path, const char *module_info, napi_value *result) {
return napi_load_module_with_info(env, path, module_info, result);
}
napi_status kn_load_module(napi_env env, const char *path, napi_value *result) {
return napi_load_module(env, path, result);
}
napi_value kn_create_object(napi_env env) {
napi_value obj;
napi_create_object(env, &obj);
return obj;
}
napi_value kn_get_global(napi_env env) {
napi_value global;
napi_get_global(env, &global);
return global;
}
napi_value kn_get_undefined(napi_env env) {
napi_value undefined;
napi_get_undefined(env, &undefined);
return undefined;
}
napi_value kn_get_null(napi_env env) {
napi_value result;
napi_get_null(env, &result);
return result;
}
void kn_wrap(napi_env env, napi_value js_object, void *finalize_data, void *finalize_cb) {
napi_wrap(env, js_object, finalize_data, (napi_finalize)finalize_cb, nullptr, nullptr);
}
void *kn_unwrap(napi_env env, napi_value js_object) {
void *nativeObj;
napi_unwrap(env, js_object, &nativeObj);
return nativeObj;
}
bool kn_equals(napi_env env, napi_value a, napi_value b) {
bool result;
napi_strict_equals(env, a, b, &result);
return result;
}
bool kn_instanceof(napi_env env, napi_value constructor, napi_value object) {
bool result;
napi_instanceof(env, object, constructor, &result);
return result;
}
napi_value kn_get_property_names(napi_env env, napi_value value) {
napi_value names;
napi_get_property_names(env, value, &names);
return names;
}
napi_value kn_get_property(napi_env env, napi_value obj, napi_value key) {
napi_value result;
napi_get_property(env, obj, key, &result);
return result;
}
napi_value kn_get_named_property(napi_env env, napi_value obj, const char *key) {
napi_value result;
napi_get_named_property(env, obj, key, &result);
return result;
}
void kn_set_named_property(napi_env env, napi_value obj, const char *key, napi_value value) {
napi_set_named_property(env, obj, key, value);
}
/***
* 创建引用,防止被回收,不再使用时请调用 deleteReference
*/
napi_ref kn_create_reference(napi_env env, napi_value value) {
napi_ref ref;
napi_create_reference(env, value, 1, &ref);
return ref;
}
void kn_delete_reference(napi_env env, napi_ref ref) { napi_delete_reference(env, ref); }
napi_value kn_get_reference_value(napi_env env, napi_ref ref) {
napi_value value;
napi_get_reference_value(env, ref, &value);
return value;
}
char *kn_to_string(napi_env env, napi_value value) {
size_t length = 0;
napi_get_value_string_utf8(env, value, NULL, 0, &length);
char *c_str = (char *)malloc((length + 1) * sizeof(char));
napi_get_value_string_utf8(env, value, c_str, length + 1, &length);
return c_str;
}
napi_value kn_string_to_napi(napi_env env, const char *value) {
napi_value result = NULL;
napi_create_string_utf8(env, value, strlen(value), &result);
return result;
}
int kn_to_int(napi_env env, napi_value value) {
int32_t result;
napi_get_value_int32(env, value, &result);
return result;
}
napi_value kn_int_to_napi(napi_env env, int value) {
napi_value result = NULL;
int32_t num = (int32_t)(value);
napi_create_int32(env, num, &result);
return result;
}
long kn_to_long(napi_env env, napi_value value) {
int64_t result;
napi_get_value_int64(env, value, &result);
return result;
}
napi_value kn_long_to_napi(napi_env env, long value) {
napi_value result = NULL;
int64_t num = (int64_t)(value);
napi_create_int64(env, num, &result);
return result;
}
bool kn_to_boolean(napi_env env, napi_value value) {
bool result;
napi_get_value_bool(env, value, &result);
return result;
}
napi_value kn_boolean_to_napi(napi_env env, bool value) {
napi_value result = NULL;
napi_get_boolean(env, value, &result);
return result;
}
double kn_to_double(napi_env env, napi_value value) {
double result;
napi_get_value_double(env, value, &result);
return result;
}
napi_value kn_double_to_napi(napi_env env, double value) {
napi_value result = NULL;
napi_create_double(env, value, &result);
return result;
}
napi_valuetype kn_typeof(napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
return type;
}
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/kn_wrapper.cpp | C++ | apache-2.0 | 13,109 |
#include <cstdint>
#include <string>
#include <cstdio>
#include <arkui/native_interface.h>
#include <arkui/native_node.h>
#include <arkui/native_node_napi.h>
#include <hilog/log.h>
#include "manager.h"
#include "HiTraceSystraceSection.h"
#include <hitrace/trace.h>
#include "libkn_api.h"
ArkUI_NodeContentHandle nodeContentHandle_ = nullptr;
namespace NativeXComponentSample {
#define TEST_TEXT_NUMBER 20
ArkUI_NodeHandle gTextBuf[TEST_TEXT_NUMBER];
int gBarWidth = 10;
Manager Manager::manager_;
static ArkUI_NativeNodeAPI_1 *nodeAPI;
Manager::~Manager() {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp ~Manager");
for (auto iter = nativeXComponentMap_.begin(); iter != nativeXComponentMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
nativeXComponentMap_.clear();
for (auto iter = nativeNodeMap_.begin(); iter != nativeNodeMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
nativeNodeMap_.clear();
for (auto iter = containerMap_.begin(); iter != containerMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
containerMap_.clear();
}
ArkUI_NodeHandle createStackExample() {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp createStackExample");
ArkUI_NodeHandle scroll = nodeAPI->createNode(ARKUI_NODE_SCROLL);
ArkUI_NodeHandle stack = nodeAPI->createNode(ARKUI_NODE_STACK);
ArkUI_NodeHandle text = nodeAPI->createNode(ARKUI_NODE_TEXT);
ArkUI_NumberValue value[] = {480};
ArkUI_AttributeItem item = {value, 1};
ArkUI_AttributeItem content = {.string = "ContentSlot, this is capi view"};
nodeAPI->setAttribute(scroll, NODE_WIDTH, &item);
nodeAPI->setAttribute(stack, NODE_WIDTH, &item);
value[0].f32 = 300;
nodeAPI->setAttribute(scroll, NODE_HEIGHT, &item);
value[0].f32 = 300;
nodeAPI->setAttribute(stack, NODE_HEIGHT, &item);
value[0].u32 = 0xFFFFFF00;
nodeAPI->setAttribute(stack, NODE_BACKGROUND_COLOR, &item);
nodeAPI->setAttribute(text, NODE_TEXT_CONTENT, &content);
nodeAPI->registerNodeEvent(scroll, NODE_SCROLL_EVENT_ON_SCROLL, 1, nullptr);
auto onScroll = [](ArkUI_NodeEvent *event) {
if (OH_ArkUI_NodeEvent_GetTargetId(event) == 1) {
}
};
nodeAPI->registerNodeEventReceiver(onScroll);
nodeAPI->addChild(stack, text);
for (int i = 0; i < 1500; i++) {
nodeAPI->addChild(scroll, stack);
}
return scroll;
}
ArkUI_NodeHandle createSimpleStackOnly()
{
HiTraceSystraceSection d("Compose::create start");
// 创建 Stack
ArkUI_NodeHandle stack = nodeAPI->createNode(ARKUI_NODE_STACK);
ArkUI_NumberValue stackSize[] = { 300 };
ArkUI_AttributeItem stackWidth = { stackSize, 1 };
nodeAPI->setAttribute(stack, NODE_WIDTH, &stackWidth);
stackSize[0].f32 = 100;
ArkUI_AttributeItem stackHeight = { stackSize, 1 };
nodeAPI->setAttribute(stack, NODE_HEIGHT, &stackHeight);
ArkUI_NumberValue borderWidth[] = { 2.0f };
ArkUI_AttributeItem borderWidthItem = { borderWidth, 1 };
nodeAPI->setAttribute(stack, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColor[] = { { .i32 = (int32_t)0xFFFF0000 } };
ArkUI_AttributeItem borderColorItem = { borderColor, 1 };
nodeAPI->setAttribute(stack, NODE_BORDER_COLOR, &borderColorItem);
return stack;
}
ArkUI_NodeHandle createSimpleColumnWithStack()
{
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "ArkUIExample", "createSimpleColumnWithStack");
// 创建最外层 Column
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
// 设置 Column 宽度
ArkUI_NumberValue columnWidth[] = { 300 };
ArkUI_AttributeItem columnWidthItem = { columnWidth, 1 };
nodeAPI->setAttribute(column, NODE_WIDTH, &columnWidthItem);
// 创建 Stack
ArkUI_NodeHandle stack = nodeAPI->createNode(ARKUI_NODE_STACK);
ArkUI_NumberValue stackSize[] = { 300 };
ArkUI_AttributeItem stackWidth = { stackSize, 1 };
nodeAPI->setAttribute(stack, NODE_WIDTH, &stackWidth);
stackSize[0].f32 = 100;
ArkUI_AttributeItem stackHeight = { stackSize, 1 };
nodeAPI->setAttribute(stack, NODE_HEIGHT, &stackHeight);
ArkUI_NumberValue borderWidth[] = { 2.0f };
ArkUI_AttributeItem borderWidthItem = { borderWidth, 1 };
nodeAPI->setAttribute(stack, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColor[] = { { .i32 = (int32_t)0xFFFF0000 } };
ArkUI_AttributeItem borderColorItem = { borderColor, 1 };
nodeAPI->setAttribute(stack, NODE_BORDER_COLOR, &borderColorItem);
ArkUI_NodeHandle text = nodeAPI->createNode(ARKUI_NODE_TEXT);
ArkUI_AttributeItem textVal = { .string = "1" };
nodeAPI->setAttribute(text, NODE_TEXT_CONTENT, &textVal);
nodeAPI->addChild(stack, text);
nodeAPI->addChild(column, stack);
return column;
}
ArkUI_NodeHandle createScrollWithContainersEachWithStack()
{
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "ArkUIExample", "createScrollWithContainersEachWithStack");
OH_HiTrace_StartTrace("Compose::createScrollWithContainersEachWithStack begin");
ArkUI_NodeHandle scroll = nodeAPI->createNode(ARKUI_NODE_SCROLL);
ArkUI_NumberValue size[] = { 480 };
size[0].f32 = 1920;
ArkUI_AttributeItem heightItem = { size, 1 };
nodeAPI->setAttribute(scroll, NODE_HEIGHT, &heightItem);
// 设置为垂直滚动
ArkUI_NumberValue scrollDir[] = { { .i32 = ARKUI_SCROLL_DIRECTION_VERTICAL } };
ArkUI_AttributeItem dirItem = { scrollDir, 1 };
nodeAPI->setAttribute(scroll, NODE_SCROLL_SCROLL_DIRECTION, &dirItem);
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
ArkUI_NumberValue containerSize[] = { 300 };
ArkUI_AttributeItem containerWidth = { containerSize, 1 };
nodeAPI->setAttribute(column, NODE_WIDTH, &containerWidth);
for (int i = 0; i < 1500; ++i) {
ArkUI_NodeHandle container = nodeAPI->createNode(ARKUI_NODE_COLUMN);
ArkUI_NumberValue containerSize[] = { 300 };
ArkUI_AttributeItem containerWidth = { containerSize, 1 };
nodeAPI->setAttribute(container, NODE_WIDTH, &containerWidth);
ArkUI_NodeHandle stack = nodeAPI->createNode(ARKUI_NODE_STACK);
ArkUI_NumberValue stackWidth[] = {300};
ArkUI_AttributeItem widthItem = {stackWidth, 1};
nodeAPI->setAttribute(stack, NODE_WIDTH, &widthItem);
ArkUI_NumberValue stackHeight[] = {100}; // 固定高度100
ArkUI_AttributeItem heightItem = {stackHeight, 1};
nodeAPI->setAttribute(stack, NODE_HEIGHT, &heightItem);
ArkUI_NodeHandle text = nodeAPI->createNode(ARKUI_NODE_TEXT);
char buf[32];
snprintf(buf, sizeof(buf), "Item #%d", i + 1);
ArkUI_AttributeItem textVal = { .string = buf };
nodeAPI->setAttribute(text, NODE_TEXT_CONTENT, &textVal);
ArkUI_NumberValue borderWidth[] = {2.0f};
ArkUI_AttributeItem borderWidthItem = {borderWidth, 1};
nodeAPI->setAttribute(stack, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColor[] = { { .i32 = (int32_t)0xFFFF0000 } };
ArkUI_AttributeItem borderColorItem = {borderColor, 1};
nodeAPI->setAttribute(stack, NODE_BORDER_COLOR, &borderColorItem);
nodeAPI->addChild(stack, text);
nodeAPI->addChild(container, stack);
nodeAPI->addChild(column, container);
{
HiTraceSystraceSection s("#Compose::createStackViewExample::KeyToCPPList");
}
}
nodeAPI->addChild(scroll, column);
OH_HiTrace_FinishTrace();
return scroll;
}
ArkUI_NodeHandle createStackViewExample() {
HiTraceSystraceSection s("#Compose::createStackViewExample begin");
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp createStackExample");
ArkUI_NodeHandle scroll = nodeAPI->createNode(ARKUI_NODE_SCROLL);
// 设置Scroll尺寸
ArkUI_NumberValue value[] = {480};
ArkUI_AttributeItem item = {value, 1};
nodeAPI->setAttribute(scroll, NODE_WIDTH, &item);
value[0].f32 = 1920;
nodeAPI->setAttribute(scroll, NODE_HEIGHT, &item);
// 创建纵向布局容器(Column)
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
// 注册滚动事件
nodeAPI->registerNodeEvent(scroll, NODE_SCROLL_EVENT_ON_SCROLL, 1, nullptr);
auto onScroll = [](ArkUI_NodeEvent *event) {
if (OH_ArkUI_NodeEvent_GetTargetId(event) == 1) {
}
};
nodeAPI->registerNodeEventReceiver(onScroll);
// 创建并添加1500个Stack到Column中
for (int i = 0; i < 1500; i++) {
// 创建Stack并设置固定大小
ArkUI_NodeHandle stack = nodeAPI->createNode(ARKUI_NODE_STACK);
// 设置Stack宽度和高度
ArkUI_NumberValue stackWidth[] = {300};
ArkUI_AttributeItem widthItem = {stackWidth, 1};
nodeAPI->setAttribute(stack, NODE_WIDTH, &widthItem);
ArkUI_NumberValue stackHeight[] = {300}; // 固定高度100
ArkUI_AttributeItem heightItem = {stackHeight, 1};
nodeAPI->setAttribute(stack, NODE_HEIGHT, &heightItem);
// +++ 添加红色边框 +++
// 1. 设置边框宽度(四边统一为2单位)
ArkUI_NumberValue borderWidthValue[] = {2.0f};
ArkUI_AttributeItem borderWidthItem = {borderWidthValue, 1};
nodeAPI->setAttribute(stack, NODE_BORDER_WIDTH, &borderWidthItem);
// 2. 设置边框颜色(红色,ARGB格式:0xFFFF0000)
ArkUI_NumberValue borderColorValue[] = {0xFFFF0000}; // 红色
ArkUI_AttributeItem borderColorItem = {borderColorValue, 1};
nodeAPI->setAttribute(stack, NODE_BORDER_COLOR, &borderColorItem);
// 3. 设置边框样式为实线
ArkUI_NumberValue borderStyleValue[] = {{.i32 = ARKUI_BORDER_STYLE_SOLID}};
ArkUI_AttributeItem borderStyleItem = {borderStyleValue, 1};
nodeAPI->setAttribute(stack, NODE_BORDER_STYLE, &borderStyleItem);
// 将Stack添加到Column(关键修改)
nodeAPI->addChild(column, stack);
}
// 将Column添加到Scroll中
nodeAPI->addChild(scroll, column);
HiTraceSystraceSection d("#Compose::createStackViewExample end");
return scroll;
}
ArkUI_NodeHandle createTextSingleViewExample() {
ArkUI_NodeHandle text = nodeAPI->createNode(ARKUI_NODE_TEXT);
std::string contentStr = "Item #" ;
ArkUI_AttributeItem content = {.string = contentStr.c_str()};
nodeAPI->setAttribute(text, NODE_TEXT_CONTENT, &content);
ArkUI_NumberValue width[] = { 300 };
ArkUI_AttributeItem widthItem = { width, 1 };
nodeAPI->setAttribute(text, NODE_WIDTH, &widthItem);
ArkUI_NumberValue borderWidth[] = { 1.0f };
ArkUI_AttributeItem borderWidthItem = { borderWidth, 1 };
nodeAPI->setAttribute(text, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColor[] = {{ .i32 = static_cast<int32_t>(0xFF888888) }};
ArkUI_AttributeItem borderColorItem = { borderColor, 1 };
nodeAPI->setAttribute(text, NODE_BORDER_COLOR, &borderColorItem);
// 设置内边距为 10(上下左右统一)
ArkUI_NumberValue padding[] = { 10, 10, 10, 10 }; // left, top, right, bottom
ArkUI_AttributeItem paddingItem = { padding, 4 };
nodeAPI->setAttribute(text, NODE_PADDING, &paddingItem);
return text;
}
ArkUI_NodeHandle createTextViewExample() {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp createStackExample");
ArkUI_NodeHandle scroll = nodeAPI->createNode(ARKUI_NODE_SCROLL);
// 设置Scroll尺寸
ArkUI_NumberValue value[] = {300};
ArkUI_AttributeItem item = {value, 1};
nodeAPI->setAttribute(scroll, NODE_WIDTH, &item);
value[0].f32 = 1920;
nodeAPI->setAttribute(scroll, NODE_HEIGHT, &item);
// 创建纵向布局容器(Column)
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
// 设置Column填满父容器
// ArkUI_AttributeItem fillParent = {value, 1};
// value[0].f32 = 1.0f; // 1.0表示100%比例
// nodeAPI->setAttribute(column, NODE_WIDTH, &fillParent);
// nodeAPI->setAttribute(column, NODE_HEIGHT, &fillParent);
// 注册滚动事件
nodeAPI->registerNodeEvent(scroll, NODE_SCROLL_EVENT_ON_SCROLL, 1, nullptr);
auto onScroll = [](ArkUI_NodeEvent *event) {
if (OH_ArkUI_NodeEvent_GetTargetId(event) == 1) {
}
};
nodeAPI->registerNodeEventReceiver(onScroll);
// 创建并添加1500个Stack到Column中
for (int i = 0; i < 1500; i++) {
// 创建Text并设置内容(唯一区别)
ArkUI_NodeHandle text = nodeAPI->createNode(ARKUI_NODE_TEXT);
std::string contentStr = "Item #" + std::to_string(i);
ArkUI_AttributeItem content = {.string = contentStr.c_str()};
nodeAPI->setAttribute(text, NODE_TEXT_CONTENT, &content);
ArkUI_NumberValue width[] = { 300 };
ArkUI_AttributeItem widthItem = { width, 1 };
nodeAPI->setAttribute(text, NODE_WIDTH, &widthItem);
ArkUI_NumberValue borderWidth[] = { 1.0f };
ArkUI_AttributeItem borderWidthItem = { borderWidth, 1 };
nodeAPI->setAttribute(text, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColor[] = {{ .i32 = static_cast<int32_t>(0xFF888888) }};
ArkUI_AttributeItem borderColorItem = { borderColor, 1 };
nodeAPI->setAttribute(text, NODE_BORDER_COLOR, &borderColorItem);
// 设置内边距为 10(上下左右统一)
ArkUI_NumberValue padding[] = { 10, 10, 10, 10 }; // left, top, right, bottom
ArkUI_AttributeItem paddingItem = { padding, 4 };
nodeAPI->setAttribute(text, NODE_PADDING, &paddingItem);
nodeAPI->addChild(column, text);
}
// 将Column添加到Scroll中
nodeAPI->addChild(scroll, column);
return scroll;
}
ArkUI_NodeHandle createImageViewExample(const char *imagePath, int32_t iteration) {
ArkUI_NodeHandle scroll = nodeAPI->createNode(ARKUI_NODE_SCROLL);
// 设置Scroll尺寸
ArkUI_NumberValue value[] = {480};
ArkUI_AttributeItem item = {value, 1};
nodeAPI->setAttribute(scroll, NODE_WIDTH, &item);
value[0].f32 = 1920;
nodeAPI->setAttribute(scroll, NODE_HEIGHT, &item);
// 创建纵向布局容器(Column)
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
// 注册滚动事件
nodeAPI->registerNodeEvent(scroll, NODE_SCROLL_EVENT_ON_SCROLL, 1, nullptr);
auto onScroll = [](ArkUI_NodeEvent *event) {
if (OH_ArkUI_NodeEvent_GetTargetId(event) == 1) {
}
};
nodeAPI->registerNodeEventReceiver(onScroll);
// 创建并添加1500个Stack到Column中
// 创建并添加1500个Image到Column中
for (int i = 0; i < iteration; i++) {
// 创建Image节点
ArkUI_NodeHandle imageNode = nodeAPI->createNode(ARKUI_NODE_IMAGE);
// 设置图片源
ArkUI_AttributeItem srcItem = {.string = imagePath};
nodeAPI->setAttribute(imageNode, NODE_IMAGE_SRC, &srcItem);
// 设置图片尺寸
ArkUI_NumberValue widthValue[] = {200.0f};
ArkUI_AttributeItem widthItem = {widthValue, 1};
nodeAPI->setAttribute(imageNode, NODE_WIDTH, &widthItem);
ArkUI_NumberValue heightValue[] = {200.0f};
ArkUI_AttributeItem heightItem = {heightValue, 1};
nodeAPI->setAttribute(imageNode, NODE_HEIGHT, &heightItem);
// 设置图片边距(使图片之间有间距)
ArkUI_NumberValue marginValue[] = {5.0f, 5.0f, 5.0f, 5.0f}; // 上、右、下、左
ArkUI_AttributeItem marginItem = {marginValue, 4};
nodeAPI->setAttribute(imageNode, NODE_MARGIN, &marginItem);
// 设置圆角效果
ArkUI_NumberValue radiusValue[] = {10.0f};
ArkUI_AttributeItem radiusItem = {radiusValue, 1};
nodeAPI->setAttribute(imageNode, NODE_BORDER_RADIUS, &radiusItem);
// 设置边框
ArkUI_NumberValue borderWidthValue[] = {1.0f};
ArkUI_AttributeItem borderWidthItem = {borderWidthValue, 1};
nodeAPI->setAttribute(imageNode, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColorValue[] = {0.5f, 0.5f, 0.5f, 1.0f}; // RGBA
ArkUI_AttributeItem borderColorItem = {borderColorValue, 4};
nodeAPI->setAttribute(imageNode, NODE_BORDER_COLOR, &borderColorItem);
// 将Image添加到Column
nodeAPI->addChild(column, imageNode);
}
// 将Column添加到Scroll中
nodeAPI->addChild(scroll, column);
return scroll;
}
ArkUI_NodeHandle createImageSingleViewExample(const char *imagePath) {
// 创建Image节点
ArkUI_NodeHandle imageNode = nodeAPI->createNode(ARKUI_NODE_IMAGE);
// 设置图片源
ArkUI_AttributeItem srcItem = {.string = imagePath};
nodeAPI->setAttribute(imageNode, NODE_IMAGE_SRC, &srcItem);
// 设置图片尺寸
ArkUI_NumberValue widthValue[] = {200.0f};
ArkUI_AttributeItem widthItem = {widthValue, 1};
nodeAPI->setAttribute(imageNode, NODE_WIDTH, &widthItem);
ArkUI_NumberValue heightValue[] = {200.0f};
ArkUI_AttributeItem heightItem = {heightValue, 1};
nodeAPI->setAttribute(imageNode, NODE_HEIGHT, &heightItem);
// 设置图片边距(使图片之间有间距)
ArkUI_NumberValue marginValue[] = {5.0f, 5.0f, 5.0f, 5.0f}; // 上、右、下、左
ArkUI_AttributeItem marginItem = {marginValue, 4};
nodeAPI->setAttribute(imageNode, NODE_MARGIN, &marginItem);
// 设置圆角效果
ArkUI_NumberValue radiusValue[] = {10.0f};
ArkUI_AttributeItem radiusItem = {radiusValue, 1};
nodeAPI->setAttribute(imageNode, NODE_BORDER_RADIUS, &radiusItem);
// 设置边框
ArkUI_NumberValue borderWidthValue[] = {1.0f};
ArkUI_AttributeItem borderWidthItem = {borderWidthValue, 1};
nodeAPI->setAttribute(imageNode, NODE_BORDER_WIDTH, &borderWidthItem);
ArkUI_NumberValue borderColorValue[] = {0.5f, 0.5f, 0.5f, 1.0f}; // RGBA
ArkUI_AttributeItem borderColorItem = {borderColorValue, 4};
nodeAPI->setAttribute(imageNode, NODE_BORDER_COLOR, &borderColorItem);
return imageNode;
}
napi_value Manager::NativeCallKotlin(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "before CallKotlin");
int num = kotlin_function2(10, env, info);
return nullptr;
}
napi_value Manager::CreateNativeNode(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
return nullptr;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 1");
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode napi_get_cb_info failed");
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 2");
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 3");
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_GetBasicNodeAPI after");
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp C-API节点挂载到XComponent");
ArkUI_NodeHandle testNode;
testNode = createStackExample();
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp 获得第一个参数NodeContent,以供C-API节点挂载");
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_NodeContent_AddNode C-API节点挂载到NodeContent");
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 555");
return nullptr;
}
napi_value Manager::CreateNativeNodeStackSingleView(napi_env env, napi_callback_info info) {
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
return nullptr;
}
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode napi_get_cb_info failed");
}
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
ArkUI_NodeHandle testNode;
testNode = createSimpleStackOnly();
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
return nullptr;
}
napi_value Manager::CreateNativeNodeStackView(napi_env env, napi_callback_info info) {
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
return nullptr;
}
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 1");
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode napi_get_cb_info failed");
}
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 2");
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 3");
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_GetBasicNodeAPI after");
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp C-API节点挂载到XComponent");
ArkUI_NodeHandle testNode;
// testNode = createStackViewExample();
testNode = createScrollWithContainersEachWithStack();
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp 获得第一个参数NodeContent,以供C-API节点挂载");
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_NodeContent_AddNode C-API节点挂载到NodeContent");
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 555");
return nullptr;
}
napi_value Manager::CreateNativeNodeTextSingleView(napi_env env, napi_callback_info info) {
if ((env == nullptr) || (info == nullptr)) {
return nullptr;
}
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNodeTextView napi_get_cb_info failed");
}
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
ArkUI_NodeHandle testNode;
testNode = createTextSingleViewExample();
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
return nullptr;
}
napi_value Manager::CreateNativeNodeTextView(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNodeTextView");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNodeTextView env or info is null");
return nullptr;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNodeTextView 1");
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNodeTextView napi_get_cb_info failed");
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNodeTextView 2");
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNodeTextView 3");
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_GetBasicNodeAPI after");
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp C-API节点挂载到XComponent");
ArkUI_NodeHandle testNode;
testNode = createTextViewExample();
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp 获得第一个参数NodeContent,以供C-API节点挂载");
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_NodeContent_AddNode C-API节点挂载到NodeContent");
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 555");
return nullptr;
}
//napi_value Manager::CreateNativeNodeImageView(napi_env env, napi_callback_info info) {
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode");
// if ((env == nullptr) || (info == nullptr)) {
// OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
// return nullptr;
// }
//
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 1");
// size_t argCnt = 1;
// napi_value args[1] = {nullptr};
// if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
// OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode napi_get_cb_info failed");
// }
//
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 2");
// if (argCnt != 1) {
// napi_throw_type_error(env, NULL, "Wrong number of arguments");
// return nullptr;
// }
//
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 3");
// nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
// OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
//
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_GetBasicNodeAPI after");
// if (nodeAPI != nullptr) {
// if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp C-API节点挂载到XComponent");
// ArkUI_NodeHandle testNode;
// testNode = createTextViewExample();
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp 获得第一个参数NodeContent,以供C-API节点挂载");
// OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
//
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp OH_ArkUI_NodeContent_AddNode C-API节点挂载到NodeContent");
// OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
// }
// }
// OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp CreateNativeNode 555");
// return nullptr;
//}
napi_value Manager::CreateNativeNodeImageView(napi_env env, napi_callback_info info) {
// 参数检查
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
return nullptr;
}
// 获取参数信息
size_t argCnt = 2; // 现在需要两个参数
napi_value args[2] = {nullptr, nullptr};
napi_value thisArg = nullptr;
void* data = nullptr;
napi_status status = napi_get_cb_info(env, info, &argCnt, args, &thisArg, &data);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"CreateNativeNode napi_get_cb_info failed: %{public}d", status);
return nullptr;
}
if (argCnt < 2) { // 现在需要两个参数
napi_throw_type_error(env, nullptr, "Wrong number of arguments. Expected 2 arguments.");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"Incorrect argument count: %{public}zu", argCnt);
return nullptr;
}
// 解析新的字符串参数
std::string imagePath;
napi_valuetype valueType;
status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok || valueType != napi_string) {
napi_throw_type_error(env, nullptr, "Second argument must be a string");
return nullptr;
}
// 获取字符串长度
size_t strLength = 0;
status = napi_get_value_string_utf8(env, args[1], nullptr, 0, &strLength);
if (status != napi_ok) {
return nullptr;
}
// 分配缓冲区并获取字符串内容
std::vector<char> buffer(strLength + 1);
size_t resultLength = 0;
status = napi_get_value_string_utf8(env, args[1], buffer.data(), buffer.size(), &resultLength);
if (status != napi_ok) {
return nullptr;
}
imagePath.assign(buffer.data(), resultLength);
// 原有的节点创建逻辑
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
ArkUI_NodeHandle testNode;
testNode = createImageViewExample(imagePath.c_str(),1500);
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
return nullptr;
}
napi_value Manager::CreateImageSingleViewExample(napi_env env, napi_callback_info info) {
// 参数检查
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager", "CreateNativeNode env or info is null");
return nullptr;
}
// 获取参数信息
size_t argCnt = 2; // 现在需要两个参数
napi_value args[2] = {nullptr, nullptr};
napi_value thisArg = nullptr;
void* data = nullptr;
napi_status status = napi_get_cb_info(env, info, &argCnt, args, &thisArg, &data);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"CreateNativeNode napi_get_cb_info failed: %{public}d", status);
return nullptr;
}
if (argCnt < 2) { // 现在需要两个参数
napi_throw_type_error(env, nullptr, "Wrong number of arguments. Expected 2 arguments.");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"Incorrect argument count: %{public}zu", argCnt);
return nullptr;
}
// 解析新的字符串参数
std::string imagePath;
napi_valuetype valueType;
status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok || valueType != napi_string) {
napi_throw_type_error(env, nullptr, "Second argument must be a string");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"Second argument is not a string");
return nullptr;
}
// 获取字符串长度
size_t strLength = 0;
status = napi_get_value_string_utf8(env, args[1], nullptr, 0, &strLength);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"Failed to get string length: %{public}d", status);
return nullptr;
}
// 分配缓冲区并获取字符串内容
std::vector<char> buffer(strLength + 1);
size_t resultLength = 0;
status = napi_get_value_string_utf8(env, args[1], buffer.data(), buffer.size(), &resultLength);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Manager",
"Failed to get string value: %{public}d", status);
return nullptr;
}
imagePath.assign(buffer.data(), resultLength);
// 原有的节点创建逻辑
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1 *>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"));
if (nodeAPI != nullptr) {
if (nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
ArkUI_NodeHandle testNode;
testNode = createImageSingleViewExample(imagePath.c_str());
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
OH_ArkUI_NodeContent_AddNode(nodeContentHandle_, testNode);
}
}
return nullptr;
}
napi_value Manager::UpdateNativeNode(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp UpdateNativeNode");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "UpdateNativeNode env or info is null");
return nullptr;
}
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "UpdateNativeNode napi_get_cb_info failed");
}
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
if (napi_typeof(env, args[0], &valuetype) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_typeof failed");
return nullptr;
}
if (valuetype != napi_string) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {'\0'};
constexpr uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
size_t length;
if (napi_get_value_string_utf8(env, args[0], idStr, idSize, &length) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_get_value_string_utf8 failed");
return nullptr;
}
return nullptr;
}
napi_value Manager::GetContext(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp GetContext");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "GetContext env or info is null");
return nullptr;
}
size_t argCnt = 1;
napi_value args[1] = {nullptr};
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "GetContext napi_get_cb_info failed");
}
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
if (napi_typeof(env, args[0], &valuetype) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_typeof failed");
return nullptr;
}
if (valuetype != napi_number) {
napi_throw_type_error(env, NULL, "valuetype err");
return nullptr;
}
int64_t value;
if (napi_get_value_int64(env, args[0], &value) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_get_value_int64 failed");
return nullptr;
}
napi_value exports;
if (napi_create_object(env, &exports) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_create_object failed");
return nullptr;
}
return exports;
}
void Manager::SetNativeXComponent(std::string &id, OH_NativeXComponent *nativeXComponent) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp SetNativeXComponent");
if (nativeXComponent == nullptr) {
return;
}
if (nativeXComponentMap_.find(id) == nativeXComponentMap_.end()) {
nativeXComponentMap_[id] = nativeXComponent;
return;
}
if (nativeXComponentMap_[id] != nativeXComponent) {
OH_NativeXComponent *tmp = nativeXComponentMap_[id];
delete tmp;
tmp = nullptr;
nativeXComponentMap_[id] = nativeXComponent;
}
}
void Manager::SetNativeNode(std::string &id, ArkUI_NodeHandle node) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp SetNativeNode");
if (node == nullptr) {
return;
}
if (nativeNodeMap_.find(id) == nativeNodeMap_.end()) {
nativeNodeMap_[id] = node;
return;
}
if (nativeNodeMap_[id] != node) {
ArkUI_NodeHandle tmp = nativeNodeMap_[id];
delete tmp;
tmp = nullptr;
nativeNodeMap_[id] = node;
}
}
OH_NativeXComponent *Manager::GetNativeXComponent(const std::string &id) {
return nativeXComponentMap_[id];
}
ArkUI_NodeHandle Manager::GetNativeNode(const std::string &id) {
return nativeNodeMap_[id];
}
Container *Manager::GetContainer(std::string &id) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Manager", "TestXXX manager.cpp GetContainer");
if (containerMap_.find(id) == containerMap_.end()) {
Container *instance = Container::GetInstance(id);
containerMap_[id] = instance;
return instance;
}
return containerMap_[id];
}
} | 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/manager.cpp | C++ | apache-2.0 | 41,131 |
//
// Created on 2025/7/21.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".
#ifndef HARMONYAPP_MANAGER_H
#define HARMONYAPP_MANAGER_H
#include <string>
#include <unordered_map>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include <arkui/native_node.h>
#include "container.h"
namespace NativeXComponentSample {
class Manager {
public:
~Manager();
static Manager *GetInstance() {
return &Manager::manager_;
}
static napi_value NativeCallKotlin(napi_env env, napi_callback_info info);
static napi_value GetContext(napi_env env, napi_callback_info info);
static napi_value CreateNativeNode(napi_env env, napi_callback_info info);
static napi_value CreateNativeNodeStackView(napi_env env, napi_callback_info info);
static napi_value CreateNativeNodeStackSingleView(napi_env env, napi_callback_info info);
static napi_value CreateNativeNodeTextView(napi_env env, napi_callback_info info);
static napi_value CreateNativeNodeTextSingleView(napi_env env, napi_callback_info info);
static napi_value CreateNativeNodeImageView(napi_env env, napi_callback_info info);
static napi_value CreateImageSingleViewExample(napi_env env, napi_callback_info info);
static napi_value UpdateNativeNode(napi_env env, napi_callback_info info);
void SetNativeXComponent(std::string &id, OH_NativeXComponent *nativeXComponent);
OH_NativeXComponent *GetNativeXComponent(const std::string &id);
void SetNativeNode(std::string &id, ArkUI_NodeHandle node);
ArkUI_NodeHandle GetNativeNode(const std::string &id);
Container *GetContainer(std::string &id);
private:
static Manager manager_;
std:: unordered_map<std::string, OH_NativeXComponent *> nativeXComponentMap_;
std:: unordered_map<std::string, ArkUI_NodeHandle> nativeNodeMap_;
std:: unordered_map<std::string, Container *> containerMap_;
};
}
#endif //HARMONYAPP_MANAGER_H
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/manager.h | C++ | apache-2.0 | 2,129 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "libkn_api.h"
#include "napi/native_api.h"
#include <rawfile/raw_file_manager.h>
#include <hilog/log.h>
#include "manager.h"
namespace NativeXComponentSample {
void callKotlinMethodTest() {
OH_LOG_Print(LOG_APP, LOG_INFO, 0, "xxx", "KN: callKotlinMethodTest: start");
int num = kotlin_function(10);
OH_LOG_Print(LOG_APP, LOG_INFO, 0, "xxx", "KN: callKotlinMethodTest: end num=%{public}d", num);
}
void print_result(int x) {
OH_LOG_Print(LOG_APP, LOG_INFO, 0, "xxx", "KN: print_result: num=%{public}d", x);
}
void callKotlinCallbackTest() {
kotlin_callback(21, (void *)print_result); // 输出: "Result: 42"
}
static napi_value Add(napi_env env, napi_callback_info info)
{
size_t argc = 2;
napi_value args[2] = {nullptr};
napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
napi_valuetype valuetype0;
napi_typeof(env, args[0], &valuetype0);
napi_valuetype valuetype1;
napi_typeof(env, args[1], &valuetype1);
double value0;
napi_get_value_double(env, args[0], &value0);
double value1;
napi_get_value_double(env, args[1], &value1);
napi_value sum;
napi_create_double(env, value0 + value1, &sum);
return sum;
}
static napi_value ArktsCallNative(napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, 0, "xxx", "KN: Count: 0909");
int *a = nullptr;
*a = 10;
return nullptr;
}
static napi_value MainArkUIViewController(napi_env env, napi_callback_info info) {
return reinterpret_cast<napi_value>(MainArkUIViewController(env));
}
static napi_value InitResourceManager(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
auto manager = OH_ResourceManager_InitNativeResourceManager(env, args[0]);
auto kt = libkn_symbols();
kt->kotlin.root.com.tencent.compose.initResourceManager(manager);
callKotlinMethodTest();
callKotlinCallbackTest();
napi_value result;
napi_create_int32(env, 0, &result);
return result;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
androidx_compose_ui_arkui_init(env, exports);
napi_property_descriptor desc[] = {
{"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr},
{"arktsCallNative", nullptr, ArktsCallNative, nullptr, nullptr, nullptr, napi_default, nullptr},
{"initResourceManager", nullptr, InitResourceManager, nullptr, nullptr, nullptr, napi_default, nullptr},
{"MainArkUIViewController", nullptr, MainArkUIViewController, nullptr, nullptr, nullptr, napi_default, nullptr},
{"getContext", nullptr, Manager::GetContext, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNode", nullptr, Manager::CreateNativeNode, nullptr, nullptr, nullptr, napi_default, nullptr},
{"updateNativeNode", nullptr, Manager::UpdateNativeNode, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeStackView", nullptr, Manager::CreateNativeNodeStackView, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeStackSingleView", nullptr, Manager::CreateNativeNodeStackSingleView, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeTextView", nullptr, Manager::CreateNativeNodeTextView, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeTextSingleView", nullptr, Manager::CreateNativeNodeTextSingleView, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeImageView", nullptr, Manager::CreateNativeNodeImageView, nullptr, nullptr, nullptr, napi_default, nullptr},
{"createNativeNodeImageSingleView", nullptr, Manager::CreateImageSingleViewExample, nullptr, nullptr, nullptr, napi_default, nullptr},
{"kotlinNativeArktsPage", nullptr, Manager::NativeCallKotlin, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
define_string_function(env, exports);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "entry",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
napi_module_register(&demoModule);
}
}
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/napi_init.cpp | C++ | apache-2.0 | 5,202 |
#include "container.h"
#include "test_0725.h"
#include "hilog/log.h"
#include "HiTraceSystraceSection.h"
#include <string>
#include <arkui/native_node.h>
#include <arkui/native_node_napi.h>
#define LOG_TAG "MY_TAG" // 全局tag宏,标识模块日志tag
// force no inline to clearly see call stack
__attribute__((noinline))
void actual_crash() {
int* p = nullptr;
*p = 42;
}
void crash_in_c() {
actual_crash();
}
napi_value loadModule(napi_env env, napi_callback_info info) {
napi_value result;
// 1. 使用napi_load_module加载Test文件中的模块
napi_status status = napi_load_module(env, "ets/test/NativeCallArkts", &result);
napi_value testFn;
// 2. 使用napi_get_named_property获取test函数
napi_get_named_property(env, result, "nativeCallArkts", &testFn);
// 3. 使用napi_call_function调用函数test
napi_call_function(env, result, testFn, 0, nullptr, nullptr);
napi_value value;
napi_value key;
std::string keyStr = "value";
napi_create_string_utf8(env, keyStr.c_str(), keyStr.size(), &key);
// 4. 使用napi_get_property获取变量value
napi_get_property(env, result, key, &value);
return result;
}
int KotlinCallNative(int num, napi_env env, napi_callback_info info) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "native_register", "before KotlinCallNative");
loadModule(env, info);
return num + 1;
}
int testNum(int num) {
return num + 1;
}
void OH_LOG(const char *msg) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "native_register", "dzy %{public}s",msg);
}
void print_string(char* msg) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "xxx", "KN: print_string: num=%{public}s", msg);
}
void print_const_string(const char* msg) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "printString", "lww str:%{public}s", msg);
HiTraceSystraceSection s("#Compose::printString::KeyToCPPFast");
}
static HiTraceSystraceSection* g_trace = nullptr;
void trace_tag_begin() {
// HiTraceSystraceSection s("trace_tag_begin");
if (!g_trace) {
g_trace = new HiTraceSystraceSection("trace_tag_compose_block");
}
}
void trace_tag_cnt(int num) {
std::string tag = std::string("trace_tag_") + std::to_string(num);
const char * tag_char = tag.c_str();
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "trace_tag_cnt", "%{public}",tag_char);
HiTraceSystraceSection s(tag_char);
}
void trace_tag_end() {
// HiTraceSystraceSection s("trace_tag_end");
delete g_trace;
g_trace = nullptr;
}
static void* g_kotlin_obj = NULL;
static register_callback_holder g_callback = NULL;
static int counter = 0;
void native_register(void* kotlin_obj, register_callback_holder callback, bool holdRef) {
if (holdRef == true) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "native_register", "dzy C: register Kotlin callback...");
g_kotlin_obj = kotlin_obj;
g_callback = callback;
}
}
void native_trigger() {
if (g_callback && g_kotlin_obj) {
counter = counter + 1;
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "native_register", "dzy C: Triggering Kotlin callback...");
g_callback(counter, g_kotlin_obj);
}
}
typedef struct {
char id[64];
void* stable_ref;
void (*callback)(void*);
bool is_active;
} SimpleCallbackEntry;
#define MAX_CALLBACKS 100
static SimpleCallbackEntry g_callbacks[MAX_CALLBACKS];
static int g_callback_count = 0;
static SimpleCallbackEntry* find_simple_callback_by_id(const char* id) {
for (int i = 0; i < g_callback_count; i++) {
if (g_callbacks[i].is_active && strcmp(g_callbacks[i].id, id) == 0) {
return &g_callbacks[i];
}
}
return nullptr;
}
void native_register_simple_callback(const char* id, void* stable_ref, void (*callback)(void*)) {
if (g_callback_count < MAX_CALLBACKS) {
SimpleCallbackEntry* entry = &g_callbacks[g_callback_count];
strncpy(entry->id, id, sizeof(entry->id) - 1);
entry->id[sizeof(entry->id) - 1] = '\0';
entry->stable_ref = stable_ref;
entry->callback = callback;
entry->is_active = true;
g_callback_count++;
std::string msg1 = "[C] 注册简化回调: " + std::string(id) +
", StableRef: " + std::to_string(reinterpret_cast<uintptr_t>(stable_ref));
OH_LOG(msg1.c_str());
std::string msg2 = "[C] 当前活跃回调数量: " + std::to_string(g_callback_count);
OH_LOG(msg2.c_str());
}
}
void native_trigger_simple_callback(const char* id) {
SimpleCallbackEntry* entry = find_simple_callback_by_id(id);
if (entry && entry->callback && entry->stable_ref) {
std::string msg = "[C] 触发简化回调: " + std::string(id);
OH_LOG(msg.c_str());
entry->callback(entry->stable_ref);
} else {
std::string msg = "[C] 未找到回调: " + std::string(id);
OH_LOG(msg.c_str());
}
}
void native_cleanup_simple_callback(const char* id) {
SimpleCallbackEntry* entry = find_simple_callback_by_id(id);
if (entry) {
std::string msg = "[C] 清理简化回调: " + std::string(id);
OH_LOG(msg.c_str());
entry->stable_ref = nullptr;
entry->callback = nullptr;
entry->is_active = false;
memset(entry->id, 0, sizeof(entry->id));
}
}
void native_cleanup_all_simple_callbacks() {
std::string msg = "[C] 清理前有 " + std::to_string(g_callback_count) + " 个活跃回调";
OH_LOG(msg.c_str());
for (int i = 0; i < g_callback_count; i++) {
SimpleCallbackEntry* entry = &g_callbacks[i];
if (entry->is_active) {
std::string clearMsg = "[C] 清理回调: " + std::string(entry->id);
OH_LOG(clearMsg.c_str());
}
entry->stable_ref = nullptr;
entry->callback = nullptr;
entry->is_active = false;
memset(entry->id, 0, sizeof(entry->id));
}
g_callback_count = 0;
}
int native_get_simple_callback_count() {
int count = 0;
for (int i = 0; i < g_callback_count; i++) {
if (g_callbacks[i].is_active) {
count++;
}
}
return count;
}
void native_print_simple_callback_status() {
std::string msg = "[C] 活跃回调数量: " + std::to_string(native_get_simple_callback_count());
OH_LOG(msg.c_str());
for (int i = 0; i < g_callback_count; i++) {
if (g_callbacks[i].is_active) {
std::string entryMsg = "[C] - ID: " + std::string(g_callbacks[i].id) +
", StableRef: " + std::to_string(reinterpret_cast<uintptr_t>(g_callbacks[i].stable_ref));
OH_LOG(entryMsg.c_str());
}
}
} | 2201_76010299/Compose_huawei_benchmark | harmonyApp/entry/src/main/cpp/test725.cpp | C++ | apache-2.0 | 6,779 |
import { harTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/features/adaptive_video_component/hvigorfile.ts | TypeScript | apache-2.0 | 234 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
| 2201_76010299/Compose_huawei_benchmark | harmonyApp/hvigorfile.ts | TypeScript | apache-2.0 | 970 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import SwiftUI
import ComposeApp
struct ComposeView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
MainViewControllerKt.MainViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
struct ComposeSkiaView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
MainViewControllerKt.SkiaRenderViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
struct ContentView: View {
var body: some View {
TabView {
// UIKit 渲染
ComposeView()
.ignoresSafeArea(.keyboard)
.tabItem {
Label("Compose", systemImage: "rectangle.3.group.fill")
}
// Skia 渲染
ComposeSkiaView()
.ignoresSafeArea(.keyboard)
.tabItem {
Label("Skia", systemImage: "s.circle.fill")
}
}
}
}
| 2201_76010299/Compose_huawei_benchmark | iosApp/iosApp/ContentView.swift | Swift | apache-2.0 | 1,872 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
@objc class ImagesScrollView: UIScrollView {
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
// MARK: - Setup
private func commonInit() {
configureAppearance()
addImageViews()
}
private func configureAppearance() {
backgroundColor = .systemGray5
showsVerticalScrollIndicator = true
showsHorizontalScrollIndicator = true
}
private func addImageViews() {
let imageViews = (1...6).map { index -> UIImageView in
let imageName = "img-type-\(index)"
let image = UIImage(named: imageName)
let imageView = UIImageView(frame: CGRect(
x: index * 80 + 20,
y: index * 80 + 20,
width: 80,
height: 80
))
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
return imageView
}
imageViews.forEach { addSubview($0) }
let maxX = imageViews.map { $0.frame.maxX }.max() ?? 0
let maxY = imageViews.map { $0.frame.maxY }.max() ?? 0
contentSize = CGSize(
width: maxX + 20,
height: maxY + 20
)
}
}
| 2201_76010299/Compose_huawei_benchmark | iosApp/iosApp/Views/ImagesScrollView.swift | Swift | apache-2.0 | 2,223 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftUI
@main
struct iOSApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 2201_76010299/Compose_huawei_benchmark | iosApp/iosApp/iOSApp.swift | Swift | apache-2.0 | 872 |
//欢迎
void welcome();
//经理功能界面
void mfunctionalinterface();
//业务员功能界面
void sfunctionalinterface();
//经理基本信息管理界面
void mfunctionalinterface1();
//经理客户分配界面
void mfunctionalinterface2();
//经理客户分组管理界面
void mfunctionalinterface3();
//经理信息查询界面
void mfunctionalinterface4();
//经理信息排序界面
void mfunctionalinterface5();
//经理信息统计界面
void mfunctionalinterface6();
//经理通信记录分析界面
void mfunctionalinterface7();
//经理系统维护界面
void mfunctionalinterface8();
//业务员基本信息查询界面
void sfunctionalinterface1();
//业务员基本信息排序界面
void sfunctionalinterface2();
//业务员基本信息统计界面
void sfunctionalinterface3();
//业务员通信记录管理界面
void sfunctionalinterface4();
//业务员通讯记录分析界面
void sfunctionalinterface5();
//刘瑞鑫的函数声明
//创建部分
struct Node1* creat_note_customer(struct Node1* end_);//创建客户信息
struct Node2* creat_note_cliaison(struct Node2* end_);//创建客户联络员信息
struct Node3* creat_note_salesman(struct Node3* end_);//模糊查询
//查询部分
//1.客户
void search_customer(struct Node1* head);
void search_customer_num(struct Node1* head,int n);//编号查找
void search_customer_name(struct Node1* head,char* a);//名称查找
void fuzzyquery_client(struct Node1* head1);//模糊查询
//2.客户联络员
void search_cliaison(struct Node2* head);
void search_cliaison_num(struct Node2 * head,int n);//编号查找
void search_cliaison_name(struct Node2 * head,char* a);//名称查找
void fuzzyquery_cliaison(struct Node2* head1);//模糊查询
//3.业务员部分
void search_salesman(struct Node3* head);
void search_salesman_num(struct Node3 * head,int n);//编号查找
void search_salesman_name(struct Node3 * head,char* a);//名称查找
void fuzzyquery_salesman(struct Node3* head1);//模糊查询
//修改部分
void exchange_customer(struct Node1* t);//修改客户信息
void exchange_cliaison(struct Node2* t);//修改客户联络员信息
void exchange_salesman(struct Node3* t);//修改业务员信息
//删除部分
struct Node3* delete_salesman(struct Node3 *head);
struct Node2* delete_cliaison(struct Node2 *head);
struct Node1* delete_customer(struct Node1* head);
//简单展示(用作提醒简单的成员名称和编号)
void show_customer(struct Node1* head);
void show_cliasion(struct Node2* head);
void show_salesman(struct Node3* head);
//分配部分
//1.给业务员分配客户
void allocation(struct Node1* head,struct Node3* head_);//分配1
void give_salesman_customer(struct Node1* head,struct Node3* head_);//分配2
void show_salesman_clients(struct Node3* head_) ;//展示分配情况
void modify_salesman_customer(struct Node1* head, struct Node3* head_);//修改业务员所负责的客户
//2.给客户分配客户联络员
void allocation_customer_cliasion(struct Node1* head,struct Node2* head_);//分配1
void give_customer_cliaison(struct Node1* head,struct Node2* head_);//分配2
void show_clients_cliaison(struct Node1* head_);//显示给客户分配的客户联络员的部分
void modify_client_cliaison(struct Node2* head, struct Node1* head_);//修改客户的客户联络员
//分组部分
struct Node4* creat_group(struct Node4* end_,struct Node1* head_);//创建分组的链表
void show_group(struct Node4* head,struct Node1* head_);//简单展示分组信息
void search_Node4(struct Node4* head,struct Node1* head_);//查询分组的具体信息
void delete_group(struct Node4* head,struct Node1* head_);//删除分组链表的节点
void modify_group_content(struct Node4* head, struct Node1* customer_head);
void add_member_to_group(struct Node4* group, struct Node1* customer_head);
void remove_member_from_group(struct Node4* group);
//赵鸿轩的函数声明
//排序部分
void clisort(struct Node1 *head1);//对客户信息进行排序
void insertClient(struct Node1 **head, struct client newClient);// 插入客户节点
void swap(struct Node1 *a, struct Node1 *b);// 交换两个客户节点
void sortByClientCount(struct Node1 *head);// 根据客户编号进行排序
void sortByClientArea(struct Node1 *head);// 根据客户所在区域进行排序
void sortByClientScale(struct Node1 *head);// 根据客户规模进行排序
void clsort(struct Node2* head2); //对客户联络员信息排序
void salsort(struct Node3* head3);//对业务员信息排序
//统计部分
void cliareasinglestatistic(struct Node1* head);//按区域对客户进行统计
void cliscalesinglestatistic(struct Node1* head);//按规模对客户进行统计
void clilevelsinglestatistic(struct Node1* head);//按联系程度对客户进行统计
void climultistatistic(struct Node1* head1);//按规模和联系程度对客户进行统计
void cliconditionquery(struct Node1* head1);//条件统计查找客户的联络员数量
void displaygroupclientcount(struct Node4* head);//对指定分组下客户数量进行统计
void clistatistics(struct Node1 *head,struct Node4* head_cusgroup);//统计客户信息
void clstatistics(struct Node2 *head);//统计客户联络员数量
void salstatistics(struct Node3 *head);//统计业务员数量
//计林敏的函数声明
//密码维护
void pwmaintenance(char mpw[],char spw[]);
//数据备份;
void datebackup(struct Node1* np1,struct Node2* np2,struct Node3* np3);
//数据恢复
void recoverydata(struct Node1* p1,struct Node2* p2,struct Node3* p3);
//简单查找
void simplequery(struct Node1* head1);
//组合查找
void combinedquery(struct Node1* head1);
//模糊查找
void fuzzyquery(struct Node1* head1);
//条件查找
void conditionquery(struct Node1* head1);
//单一排序
void singlesort(struct Node1* head1);
//多属性排序
void combinsort(struct Node1* head1);
//单一统计
void singlestatistic(struct Node1* head1);
//多属性统计
void multistatistic(struct Node1* head1);
//预设统计
void defaultstatistic(struct Node1* head1);//预设条件统计高规模客户数
//条件统计
void conditionquery(struct Node1* head1);//条件统计查找客户的联络员数量
//王兴家的函数声明
int verify(char *kk);//验证
void Set_Salesman_passsword(char *password);//设置
| 2303_806435pww/tongxin_moved | declaration.h | C | unknown | 6,340 |
#include"tool.h"
#include"declaration.h"
void welcome()//欢迎
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择您的身份:\t\t\t*\n");
printf("*\t\t1.公司经理\t\t\t*\n");
printf("*\t\t2.公司业务员\t\t\t*\n");
printf("*\t\t0.退出系统\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface()//经理功能界面函数
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.基本信息管理\t\t\t*\n");
printf("*\t\t2.客户分配管理\t\t\t*\n");
printf("*\t\t3.客户分组管理\t\t\t*\n");
printf("*\t\t4.基本信息排序\t\t\t*\n");
printf("*\t\t5.基本信息统计\t\t\t*\n");
printf("*\t\t6.通信记录分析\t\t\t*\n");
printf("*\t\t7.系统维护\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface1()//经理基本信息管理界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息管理功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.录入业务员信息\t\t*\n");
printf("*\t\t2.录入客户基本信息\t\t*\n");
printf("*\t\t3.录入客户联络员信息\t\t*\n");
printf("*\t\t4.修改和查找业务员信息\t\t*\n");
printf("*\t\t5.修改和查找客户基本信息\t*\n");
printf("*\t\t6.修改和查找客户联络员信息\t*\n");
printf("*\t\t7.删除业务员信息\t\t*\n");
printf("*\t\t8.删除客户基本信息\t\t*\n");
printf("*\t\t9.删除客户联络员信息\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface2()//经理客户分配界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用客户分配功能\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.业务员分配客户\t\t*\n");
printf("*\t\t2.显示业务员客户\t\t*\n");
printf("*\t\t3.修改业务员客户\t\t*\n");
printf("*\t\t4.客户分配客户联络员\t\t*\n");
printf("*\t\t5.显示客户的客户联络员\t\t*\n");
printf("*\t\t6.修改客户客户联络员\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface3()//经理客户分组管理界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用客户分组管理功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.新建客户分组\t\t\t*\n");
printf("*\t\t2.查找分组\t\t\t*\n");
printf("*\t\t3.修改分组\t\t\t*\n");
printf("*\t\t4.删除分组\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface5()//经理信息排序界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息排序功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.排序业务员信息\t\t*\n");
printf("*\t\t2.排序客户信息\t\t\t*\n");
printf("*\t\t3.排序客户联络员信息\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface6()//经理信息统计界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息统计功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.统计业务员数量\t\t*\n");
printf("*\t\t2.统计客户数量\t\t\t*\n");
printf("*\t\t3.统计客户联络员数量\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface7()//经理通信记录分析界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信记录分析功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.查询通信情况\t\t\t*\n");
printf("*\t\t2.排序通信情况\t\t\t*\n");
printf("*\t\t3.统计通信情况\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface8()//经理系统维护界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用系统维护功能\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.密码维护\t\t\t*\n");
printf("*\t\t2.数据备份\t\t\t*\n");
printf("*\t\t3.数据恢复\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface()//业务员功能界面函数
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\ | 2303_806435pww/tongxin_moved | f.c | C | unknown | 6,168 |
#include"tool.h"
#include"declaration.h"
void welcome()//欢迎
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择您的身份:\t\t\t*\n");
printf("*\t\t1.公司经理\t\t\t*\n");
printf("*\t\t2.公司业务员\t\t\t*\n");
printf("*\t\t0.退出系统\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface()//经理功能界面函数
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.基本信息管理\t\t\t*\n");
printf("*\t\t2.客户分配管理\t\t\t*\n");
printf("*\t\t3.客户分组管理\t\t\t*\n");
printf("*\t\t4.基本信息排序\t\t\t*\n");
printf("*\t\t5.基本信息统计\t\t\t*\n");
printf("*\t\t6.通信记录分析\t\t\t*\n");
printf("*\t\t7.系统维护\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface1()//经理基本信息管理界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息管理功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.录入业务员信息\t\t*\n");
printf("*\t\t2.录入客户基本信息\t\t*\n");
printf("*\t\t3.录入客户联络员信息\t\t*\n");
printf("*\t\t4.修改和查找业务员信息\t\t*\n");
printf("*\t\t5.修改和查找客户基本信息\t*\n");
printf("*\t\t6.修改和查找客户联络员信息\t*\n");
printf("*\t\t7.删除业务员信息\t\t*\n");
printf("*\t\t8.删除客户基本信息\t\t*\n");
printf("*\t\t9.删除客户联络员信息\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface2()//经理客户分配界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用客户分配功能\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.业务员分配客户\t\t*\n");
printf("*\t\t2.显示业务员客户\t\t*\n");
printf("*\t\t3.修改业务员客户\t\t*\n");
printf("*\t\t4.客户分配客户联络员\t\t*\n");
printf("*\t\t5.显示客户的客户联络员\t\t*\n");
printf("*\t\t6.修改客户客户联络员\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface3()//经理客户分组管理界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用客户分组管理功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.新建客户分组\t\t\t*\n");
printf("*\t\t2.查找分组\t\t\t*\n");
printf("*\t\t3.修改分组\t\t\t*\n");
printf("*\t\t4.删除分组\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface5()//经理信息排序界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息排序功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.排序业务员信息\t\t*\n");
printf("*\t\t2.排序客户信息\t\t\t*\n");
printf("*\t\t3.排序客户联络员信息\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface6()//经理信息统计界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息统计功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.统计业务员数量\t\t*\n");
printf("*\t\t2.统计客户数量\t\t\t*\n");
printf("*\t\t3.统计客户联络员数量\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface7()//经理通信记录分析界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信记录分析功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.查询通信情况\t\t\t*\n");
printf("*\t\t2.排序通信情况\t\t\t*\n");
printf("*\t\t3.统计通信情况\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void mfunctionalinterface8()//经理系统维护界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用系统维护功能\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.密码维护\t\t\t*\n");
printf("*\t\t2.数据备份\t\t\t*\n");
printf("*\t\t3.数据恢复\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface()//业务员功能界面函数
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信管理系统\t\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.基本信息查询\t\t\t*\n");
printf("*\t\t2.基本信息排序\t\t\t*\n");
printf("*\t\t3.基本信息统计\t\t\t*\n");
printf("*\t\t4.通信记录管理\t\t\t*\n");
printf("*\t\t5.通信记录分析\t\t\t*\n");
printf("*\t\t6.系统维护\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface1()//业务员基本信息查询界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息查询功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.简单查询\t\t\t*\n");
printf("*\t\t2.组合查询\t\t\t*\n");
printf("*\t\t3.模糊查询\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface2()//业务员基本信息排序界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息排序功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.简单排序\t\t\t*\n");
printf("*\t\t2.组合排序\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface3()//业务员基本信息统计界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用基本信息统计功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.单属性统计\t\t\t*\n");
printf("*\t\t2.多属性统计\t\t\t*\n");
printf("*\t\t3.预设统计\t\t\t*\n");
printf("*\t\t4.条件统计\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface4()//业务员通信记录管理界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信记录管理功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.增加通信情况\t\t\t*\n");
printf("*\t\t2.修改通信情况\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
void sfunctionalinterface5()//业务员通讯记录分析界面
{
printf("*************************************************\n");
printf("*\t\t欢迎使用通信记录分析功能\t*\n");
printf("*************************************************\n");
printf("*\t\t请选择功能列表:\t\t\t*\n");
printf("*\t\t1.查询通信情况\t\t\t*\n");
printf("*\t\t2.排序通信情况\t\t\t*\n");
printf("*\t\t3.统计通信情况\t\t\t*\n");
printf("*\t\t0.返回上一界面\t\t\t*\n");
printf("*************************************************\n");
}
//刘瑞鑫的函数定义
struct Node1* creat_note_customer(struct Node1* end_)//创建客户的链表节点
{
struct Node1* fresh = (struct Node1*)malloc(sizeof(struct Node1));
fresh->pnext1 = NULL;
end_->pnext1 = fresh;
for(int i = 0 ; i < 20 ; i++)
{
fresh->headcliaison[i] = NULL;
}
printf("请输入客户编号(数字):");
while (1)
{
if(scanf("%d",&fresh->cli.clicount)!=1||fresh->cli.clicount<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
printf("请输入客户姓名:");
while(1)
{
scanf("%12s",fresh->cli.cliname);
if(strlen(fresh->cli.cliname)>10)
{
printf("您输入的客户姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户所在区域:");
while(1)
{
scanf("%10s",fresh->cli.cliarea);
if(strlen(fresh->cli.cliarea)>8)
{
printf("您输入的客户所在区域过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户所在地址:");
while(1)
{
scanf("%30s",fresh->cli.cliaddress);
if(strlen(fresh->cli.cliaddress)>28)
{
printf("您输入的客户所在地址过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户法人姓名:");
while(1)
{
scanf("%12s",fresh->cli.clilegalman);
if(strlen(fresh->cli.clilegalman)>10)
{
printf("您输入的客户法人姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户规模(大,中,小):");
while(1)
{
scanf("%3s",fresh->cli.cliscale);
if(strcmp(fresh->cli.cliscale,"大")==0||strcmp(fresh->cli.cliscale,"中")==0||strcmp(fresh->cli.cliscale,"小")==0)
{
break;
}
else if(strlen(fresh->cli.cliscale)>1)
{
printf("您输入的客户规模过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
printf("请输入客户联系程度(高,中,低):");
while(1)
{
scanf("%3s",fresh->cli.cliconlevel);
if(strcmp(fresh->cli.cliconlevel,"高")==0||strcmp(fresh->cli.cliconlevel,"中")==0||strcmp(fresh->cli.cliconlevel,"低")==0)
{
break;
}
else if(strlen(fresh->cli.cliconlevel)>1)
{
printf("您输入的客户联系程度过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
printf("请输入客户邮箱:");
while(1)
{
scanf("%15s",fresh->cli.climailbox);
if(strlen(fresh->cli.climailbox)>13)
{
printf("您输入的客户邮箱过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户电话号码个数:");
while (1)
{
if(scanf("%d",&fresh->cli.clitelcount)!=1||fresh->cli.clitelcount<0||fresh->cli.clitelcount>10)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
for(int i = 0 ; i < fresh->cli.clitelcount ; i++)
{
printf("%d:",i + 1);
while(1)
{
scanf("%13s",fresh->cli.clitel[i]);
if(strlen(fresh->cli.clitel[i])>11)
{
printf("您输入的客户电话号码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
}
end_ = fresh;
return end_;
}
struct Node2* creat_note_cliaison(struct Node2* end_)//创建客户联络员的链表节点
{
struct Node2* fresh = (struct Node2*)malloc(sizeof(struct Node2));
fresh->pnext2 = NULL;
end_-> pnext2 = fresh;
printf("请输入客户联络员编号(数字):");
while (1)
{
if(scanf("%d",&fresh->cli.clcount)!=1||fresh->cli.clcount<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
printf("请输入客户联络员姓名:");
while(1)
{
scanf("%12s",fresh->cli.clname);
if(strlen(fresh->cli.clname)>10)
{
printf("您输入的客户联络员姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户联络性别(男,女):");
while(1)
{
scanf("%s",fresh->cli.clsex);
if(strcmp(fresh->cli.clsex,"女")==0||strcmp(fresh->cli.clsex,"男")==0)
{
break;
}
else if(strlen(fresh->cli.clsex)>1)
{
printf("您输入的客户联络员性别过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请重新输入:\n");
}
}
printf("请输入客户联络员生日:");
while(1)
{
scanf("%12s",fresh->cli.clbirthday);
if(strlen(fresh->cli.clbirthday)>10)
{
printf("您输入的客户联络员生日过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入客户联络员邮箱:");
while(1)
{
scanf("%15s",fresh->cli.clmailbox);
if(strlen(fresh->cli.clmailbox)>13)
{
printf("您输入的客户联络员邮箱过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("客户联络员电话号码个数:");
while (1)
{
if(scanf("%d",&fresh->cli.cltelcount)!=1||fresh->cli.cltelcount<0||fresh->cli.cltelcount>10)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
for(int i = 0 ; i < fresh->cli.cltelcount ; i++)
{
printf("%d:",i + 1);
while(1)
{
scanf("%13s",fresh->cli.cltel[i]);
if(strlen(fresh->cli.cltel[i])>11)
{
printf("您输入的客户电话号码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
}
end_ = fresh;
return end_;
}
struct Node3* creat_note_salesman(struct Node3* end_)//创建业务员的链表节点
{
struct Node3* fresh = (struct Node3*)malloc(sizeof(struct Node3));
fresh->pnext3 = NULL;
end_->pnext3 = fresh;
int num = 0;
printf("请输入业务员编号(数字):");
while (1)
{
if(scanf("%d",&fresh->sal.scount)!=1||fresh->sal.scount<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
printf("请输入业务员姓名:");
while(1)
{
scanf("%12s",fresh->sal.sname);
if(strlen(fresh->sal.sname)>10)
{
printf("您输入的业务员姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入业务员性别(男,女):");
while(1)
{
scanf("%s",fresh->sal.ssex);
if(strcmp(fresh->sal.ssex,"女")==0||strcmp(fresh->sal.ssex,"男")==0)
{
break;
}
else if(strlen(fresh->sal.ssex)>1)
{
printf("您输入的客户联络员性别过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请重新输入:\n");
}
}
printf("请输入业务员生日:");
while(1)
{
scanf("%12s",fresh->sal.sbirthday);
if(strlen(fresh->sal.sbirthday)>10)
{
printf("您输入的业务员员生日过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入业务员邮箱:");
while(1)
{
scanf("%15s",fresh->sal.smailbocx);
if(strlen(fresh->sal.smailbocx)>13)
{
printf("您输入的业务员邮箱过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("业务员电话号码个数:");
while (1)
{
if(scanf("%d",&fresh->sal.stelcount)!=1||fresh->sal.stelcount<0||fresh->sal.stelcount>10)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
for(int i = 0 ; i < fresh->sal.stelcount ; i++)
{
printf("%d:",i + 1);
while(1)
{
scanf("%13s",fresh->sal.stel[i]);
if(strlen(fresh->sal.stel[i])>11)
{
printf("您输入的业务员电话号码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
}
fresh->sal.saleclient_size = 0;
end_ = fresh;
return end_;
}
void show_cliasion(struct Node2* head)//简单显示客户联络员的姓名编号
{
while(head->pnext2 != NULL)
{
printf("编号:%d 名字:",head->pnext2->cli.clcount);
puts(head->pnext2->cli.clname);
head = head->pnext2;
}
}
void show_customer(struct Node1* head)//简单显示客户的姓名编号
{
struct Node1* current = head->pnext1;
while(current!=NULL)
{
printf("编号:%d 名字:",current->cli.clicount);
puts(current->cli.cliname);
current = current->pnext1;
}
}
void show_salesman(struct Node3* head)//简单显示业务员的姓名编号
{
while(head->pnext3!= NULL)
{
printf("编号:%d 名字:%s\n",head->pnext3->sal.scount,head->pnext3->sal.sname);
head = head->pnext3;
}
}
void search_customer(struct Node1* head)//查询具体基本信息的函数
{
char name[12];
char n[3];
int m = 0;
show_customer(head);
printf("1.姓名查找\n");
printf("2.编号查找\n");
printf("3.模糊查询\n");
printf("输入其他数字退出");
printf("请输入客户编号(数字):");
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
system("cls");
if(n[0] == '1')
{
printf("请输入要查询的客户姓名:");
while(1)
{
scanf("%12s",name);
if(strlen(name)>10)
{
printf("您输入的客户姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
search_customer_name(head,name);
}
if(n[0] =='2')
{
printf("请输入要查询的客户的编号:");
while (1)
{
if(scanf("%d",&m)!=1||m<0)
{
printf("输入错误,请重新输入客户编号:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
search_customer_num(head,m);
}
if(n[0]=='3')
{
fuzzyquery_client(head->pnext1);
}
}
void search_customer_num(struct Node1* head,int n)//通过编号来查询
{
struct Node1 *t = head->pnext1;
int time = 0;
while (t!=NULL)
{
if(t->cli.clicount == n)
{
printf("客户编号:%d\n",t->cli.clicount);
printf("客户姓名:");
puts(t->cli.cliname);
printf("客户所在区域:");
puts(t->cli.cliarea);
printf("客户所在地址:");
puts(t->cli.cliaddress);
printf("客户法人:");
puts(t->cli.clilegalman);
printf("客户规模:");
puts(t->cli.cliscale);
printf("客户联系程度:");
puts(t->cli.cliconlevel);
printf("客户邮箱:");
puts(t->cli.climailbox);
time = 1;
exchange_customer(t);
}
t = t->pnext1;
}
if(time == 0)
{
printf("没有此用户");
}
system("pause");
}
void search_customer_name(struct Node1* head,char* a)//通过姓名来查询
{
struct Node1 *t = head->pnext1;
int time = 0;
while (t!=NULL)
{
if(strcmp(t->cli.cliname,a) == 0)
{
printf("客户编号:%d\n",t->cli.clicount);
printf("客户姓名:");
puts(t->cli.cliname);
printf("客户所在区域:");
puts(t->cli.cliarea);
printf("客户所在地址:");
puts(t->cli.cliaddress);
printf("客户法人:");
puts(t->cli.clilegalman);
printf("客户规模:");
puts(t->cli.cliscale);
printf("客户联系程度:");
puts(t->cli.cliconlevel);
printf("客户邮箱:");
puts(t->cli.climailbox);
time = 1;
exchange_customer(t);
}
t = t->pnext1;
}
if(time == 0)
{
printf("没有此用户");
}
system("pause");
}
void search_cliaison(struct Node2* head)//查询具体基本信息的函数
{
char name[10];
char n[3];
int m = 0;
show_cliasion(head);
printf("1.姓名查找\n");
printf("2.编号查找\n");
printf("3.模糊查询\n");
printf("输入其他数字退出\n");
printf("请输入客户编号(数字):");
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(n[0] == '1')
{
system("cls");
printf("请输入要查询的客户联络员姓名:");
while(1)
{
scanf("%12s",name);
if(strlen(name)>10)
{
printf("您输入的客户联络员姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
search_customer_name(head,name);
search_cliaison_name(head,name);
}
if(n[0] == '2')
{
system("cls");
printf("请输入要查询的客户联络员的编号:");
while (1)
{
if(scanf("%d",&m)!=1||m<0)
{
printf("输入错误,请重新输入客户联络员编号:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
scanf("%d",&m);
search_cliaison_num(head,m);
}
if(n[0]=='3')
{
fuzzyquery_cliaison(head->pnext2);
}
}
void search_cliaison_num(struct Node2 * head,int n)//通过编号来查询
{
struct Node2* t = head->pnext2;
int time = 0;
while (t!=NULL)
{
if(t->cli.clcount == n)
{
printf("客户联络员编号:%d\n",t->cli.clcount);
printf("客户联络员姓名:");
puts(t->cli.clname);
printf("客户联络员性别:");
puts(t->cli.clsex);
printf("客户联络员生日:");
puts(t->cli.clbirthday);
printf("客户联络员邮箱:");
puts(t->cli.clmailbox);
time = 1;
exchange_cliaison(t);
}
t = t->pnext2;
}
if(time == 0)
{
printf("没有此业务联络员");
}
system("pause");
}
void search_cliaison_name(struct Node2 * head,char* a)//通过姓名来查询
{
struct Node2* t = head->pnext2;
int time = 0;
while (t!=NULL)
{
if(strcmp(t->cli.clname,a) == 0)
{
printf("客户联络员编号:%d\n",t->cli.clcount);
printf("客户联络员姓名:");
puts(t->cli.clname);
printf("客户联络员性别:");
puts(t->cli.clsex);
printf("客户联络员生日:");
puts(t->cli.clbirthday);
printf("客户联络员邮箱:");
puts(t->cli.clmailbox);
time = 1;
exchange_cliaison(t);
}
t = t->pnext2;
}
if(time == 0)
{
printf("没有此业务联络员");
}
system("pause");
}
void search_salesman(struct Node3* head)//查询具体基本信息的函数
{
char name[10];
char n[3];
int m = 0;
show_salesman(head);
printf("1.姓名查找\n");
printf("2.编号查找\n");
printf("3.模糊查询\n");
printf("输入其他数字退出");
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(n[0] == '1')
{
system("cls");
printf("请输入要查询的业务员姓名:");
while(1)
{
scanf("%12s",name);
if(strlen(name)>10)
{
printf("您输入的业务员姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
search_salesman_name(head,name);
}
if(n[0] == '2')
{
system("cls");
printf("请输入要查询业务员的编号:");
while (1)
{
if(scanf("%d",&m)!=1||m<0)
{
printf("输入错误,请重新输入客户联络员编号:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
search_salesman_num(head,m);
}
if(n[0]=='3')
{
fuzzyquery_salesman(head->pnext3);
}
}
void search_salesman_num(struct Node3 * head,int n)//通过编号来查询
{
struct Node3* t = head->pnext3;
int time = 0;
while (t!=NULL)
{
if(t->sal.scount == n)
{
printf("业务员编号:%d\n",t->sal.scount);
printf("业务员姓名:");
puts(t->sal.sname);
printf("业务员性别:");
puts(t->sal.ssex);
printf("业务员生日:");
puts(t->sal.sbirthday);
printf("业务员邮箱:");
puts(t->sal.smailbocx);
time = 1;
exchange_salesman(t);
}
t = t->pnext3;
}
if(time == 0)
{
printf("没有此业务员!\n");
}
system("pause");
}
void search_salesman_name(struct Node3 * head,char* a)//通过姓名来查询
{
struct Node3* t = head->pnext3;
int time = 0;
while (t!=NULL)
{
if(strcmp(t->sal.sname,a) == 0)
{
printf("业务员编号:%d\n",t->sal.scount);
printf("业务员姓名:");
puts(t->sal.sname);
printf("业务员性别:");
puts(t->sal.ssex);
printf("业务员生日:");
puts(t->sal.sbirthday);
printf("业务员邮箱:");
puts(t->sal.smailbocx);
time = 1;
exchange_salesman(t);
}
t = t->pnext3;
}
if(time == 0)
{
printf("没有此业务员!\n");
}
system("pause");
}
void fuzzyquery_client(struct Node1* head1)//模糊查询客户
{
char ncliname[12];
int i;
printf("请输入要查找的客户姓名的关键字:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名关键字过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node1*p=head1;
if(p==NULL)
{
printf("未查询到该顾客信息!\n");
}
while(p!=NULL)
{
if(strstr (p->cli.cliname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL
{
printf("客户编号:%d\n",p->cli.clicount);
printf("客户姓名:");
puts(p->cli.cliname);
printf("客户所在区域:");
puts(p->cli.cliarea);
printf("客户所在地址:");
puts(p->cli.cliaddress);
printf("客户法人:");
puts(p->cli.clilegalman);
printf("客户规模:");
puts(p->cli.cliscale);
printf("客户联系程度:");
puts(p->cli.cliconlevel);
printf("客户邮箱:");
puts(p->cli.climailbox);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
exchange_customer(p);
}
p=p->pnext1;
}
system("pause");
system("cls");
}
void fuzzyquery_cliaison(struct Node2* head1)//模糊查询客户联络员
{
char ncliname[12];
int i;
printf("请输入要查找的客户联络员姓名的关键字:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户联络员姓名关键字过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node2*p=head1;
if(p==NULL)
{
printf("未查询到该顾客信息!\n");
}
while(p!=NULL)
{
if(strstr (p->cli.clname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL
{
printf("客户联络员编号:%d\n",p->cli.clcount);
printf("客户联络员姓名:");
puts(p->cli.clname);
printf("客户联络员性别:");
puts(p->cli.clsex);
printf("客户联络员生日:");
puts(p->cli.clbirthday);
printf("客户联络员邮箱:");
puts(p->cli.clmailbox);
for(i=0;i<p->cli.cltelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.cltel[i]);
}
printf("\n");
exchange_cliaison(p);
}
p=p->pnext2;
}
system("pause");
system("cls");
}
void fuzzyquery_salesman(struct Node3* head1)//模糊查询业务员
{
char ncliname[12];
int i;
printf("请输入要查找的业务员姓名的关键字:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名关键字过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node3*p=head1;
if(p==NULL)
{
printf("未查询到该顾客信息!\n");
}
while(p!=NULL)
{
printf("业务员编号:%d\n",p->sal.scount);
printf("业务员姓名:");
puts(p->sal.sname);
printf("业务员性别:");
puts(p->sal.ssex);
printf("业务员生日:");
puts(p->sal.sbirthday);
printf("业务员邮箱:");
puts(p->sal.smailbocx);
for(i=0;i<p->sal.stelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->sal.stel[i]);
}
printf("\n");
exchange_salesman(p);
p=p->pnext3;
}
system("pause");
system("cls");
}
void exchange_customer(struct Node1* t)//在查询后进行修改(客户)
{
printf("是否进行修改 1-是,2-否");
char n[3],m[3];
int end_ = 0;
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(n[0] == '1')
{
printf("1.客户编号 ");
printf("2.客户姓名 ");
printf("3.客户所在区域 ");
printf("4.客户所在地址 ");
printf("5.客户法人 ");
printf("6.客户规模 ");
printf("7.客户联系程度 ");
printf("8.客户邮箱 ");
printf("0.退出\n");
while(end_ == 0)
{
printf("请输入修改的项: ");
while(1)
{
scanf("%2s",m);
m[2]='\0';
if(strlen(m)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
switch(m[0])
{
case '1' :
printf("请输入更改后结果: ");
scanf("%d",&t->cli.clicount);
printf("客户修改成功!\n");
break;
case '2' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.cliname);
printf("客户姓名修改成功!\n");
break;
case '3' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.cliarea);
printf("客户所在区域修改成功!\n");
break;
case '4' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.cliaddress);
printf("客户所在地址修改成功!\n");
break;
case '5' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.clilegalman);
printf("客户法人修改成功!\n");
break;
case '6' :
printf("请输入更改后结果: ");
scanf("%d",&t->cli.cliscale);
printf("客户规模修改成功!\n");
break;
case '7' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.cliconlevel);
printf("客户联系程度修改成功!\n");
break;
case '8' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.climailbox);
printf("客户邮箱修改成功!\n");
break;
case '0' :
end_ = 1;
break;
default : break;
}
}
}
}
void exchange_cliaison(struct Node2* t)//在查询后进行修改(客户联络员)
{
printf("是否进行修改 1-是,2-否");
char n[3];
char m[3];
int end_;
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(n[0] == '1')
{
printf("1.客户联络员编号");
printf("2.客户联络员姓名");
printf("3.客户联络员性别");
printf("4.客户联络员生日");
printf("5.客户联络员邮箱");
printf("0.退出");
while(end_ == 0)
{
printf("请输入要更改的项: ");
while(1)
{
scanf("%2s",m);
m[2]='\0';
if(strlen(m)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
switch(m[0])
{
case '1' :
printf("请输入更改后结果: ");
scanf("%d",&t->cli.clcount);
printf("客户联络员编号修改成功!\n");
break;
case '2' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.clname);
printf("客户联络员姓名修改成功!\n");
break;
case '3' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.clsex);
printf("客户联络员性别修改成功!\n");
break;
case '4' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.clbirthday);
printf("客户联络员生日修改成功!\n");
break;
case '5' :
printf("请输入更改后结果: ");
scanf("%s",&t->cli.clmailbox);
printf("客户联络员邮箱修改成功!\n");
break;
case '0' :
end_ = 1;
break;
default:
break;
}
}
}
}
void exchange_salesman(struct Node3* t)//在查询后进行修改(业务员)
{
printf("是否进行修改 1-是,2-否");
char n[3];
char m[3];
int end_ = 0;
while(1)
{
scanf("%2s",n);
n[2]='\0';
if(strlen(n)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(n[0]== '1')
{
printf("1.业务员编号");
printf("2.业务员姓名");
printf("3.业务员性别");
printf("4.业务员生日");
printf("5.业务员邮箱");
printf("0.退出");
while(end_ == 0)
{
printf("请输入要更改的项: ");
while(1)
{
scanf("%2s",m);
m[2]='\0';
if(strlen(m)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
switch(m[0])
{
case '1' :
printf("请输入更改后结果: ");
scanf("%d",&t->sal.scount);
printf("业务员编号修改成功!\n");
break;
case '2' :
printf("请输入更改后结果: ");
scanf("%s",&t->sal.sname);
printf("业务员姓名修改成功!\n");
break;
case '3' :
printf("请输入更改后结果: ");
scanf("%s",&t->sal.ssex);
printf("业务员性别修改成功!\n");
break;
case '4' :
printf("请输入更改后结果: ");
scanf("%s",&t->sal.sbirthday);
printf("业务员生日修改成功!\n");
break;
case '5' :
printf("请输入更改后结果: ");
scanf("%s",&t->sal.smailbocx);
printf("业务员邮箱修改成功!\n");
break;
case '0' :
end_ = 1;
break;
default:
break;
}
}
}
}
struct Node1* delete_customer(struct Node1 *head)//删除客户节点
{
show_customer(head);
printf("请输入要删除的节点的编号:");
int cli_count = 0;
while (1)
{
if(scanf("%d",&cli_count)!=1||cli_count<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
struct Node1 *current = head;
struct Node1 *prev = NULL;
int found = 0;
// 遍历链表查找要删除的节点
while (current != NULL) {
if (current->cli.clicount == cli_count) {
found = 1;
break;
}
prev = current;
current = current->pnext1;
}
if (found) {
// 如果找到了要删除的节点
if (prev == NULL) {
// 删除的是头节点
head = current->pnext1;
} else {
// 删除的不是头节点
prev->pnext1 = current->pnext1;
}
// 释放被删除节点的内存
free(current);
} else {
printf("没有找到编号为 %d 的客户\n", cli_count);
}
return head; // 返回更新后的头节点
}
struct Node2* delete_cliaison(struct Node2 *head)//删除客户联络员节点
{
show_cliasion(head);
printf("请输入要删除的节点的编号:");
int cl_count = 0;
while (1)
{
if(scanf("%d",&cl_count)!=1||cl_count<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
struct Node2 *current = head;
struct Node2 *prev = NULL;
int found = 0;
// 遍历链表查找要删除的节点
while (current != NULL) {
if (current->cli.clcount == cl_count) {
found = 1;
break;
}
prev = current;
current = current->pnext2;
}
if (found) {
// 如果找到了要删除的节点
if (prev == NULL) {
// 删除的是头节点
head = current->pnext2;
} else {
// 删除的不是头节点
prev->pnext2 = current->pnext2;
}
// 释放被删除节点的内存
free(current);
} else {
printf("没有找到编号为 %d 的业务联络员\n", cl_count);
}
return head; // 返回更新后的头节点
}
struct Node3* delete_salesman(struct Node3 *head)//删除业务员节点
{
show_salesman(head);
printf("请输入要删除的节点的编号:");
int scount = 0;
while (1)
{
if(scanf("%d",&scount)!=1||scount<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
struct Node3 *current = head;
struct Node3 *prev = NULL;
int found = 0;
// 遍历链表查找要删除的节点
while (current != NULL) {
if (current->sal.scount == scount) {
found = 1;
break;
}
prev = current;
current = current->pnext3;
}
if (found) {
// 如果找到了要删除的节点
if (prev == NULL) {
// 删除的是头节点
head = current->pnext3;
} else {
// 删除的不是头节点
prev->pnext3 = current->pnext3;
}
// 释放被删除节点的内存
free(current);
} else {
printf("没有找到编号为 %d 的业务员\n", scount);
}
return head; // 返回更新后的头节点
}
//赵鸿轩的函数定义
void clsort(struct Node2* head2) //对客户联络员信息排序
{
if (head2 == NULL) {
printf("输入链表为空!\n");
return;
}
struct Node2* p = head2;
struct Node2* t = NULL;
struct Node2* cur = p->pnext2;
struct Node2* prev = head2;
struct Node2* end = NULL;
int i;
int swap = 0;
p = head2;
printf("请选择排序方式\n");
printf("1-按联络员姓名进行排序\n");
printf("2-按联络员编号进行排序\n");
char sortType = getch();
printf("请选择升降序:\n");
printf("1-升序 2-降序\n");
char sortorder = getch();
while (cur != end) {
swap = 0;
while (cur->pnext2 != end) {
if (sortType == '1') {
if ((sortorder == '1' && strcmp(cur->cli.clname, cur->pnext2->cli.clname) > 0) ||
(sortorder == '2' && strcmp(cur->cli.clname, cur->pnext2->cli.clname) < 0)) {
t = cur->pnext2->pnext2;
prev->pnext2 = cur->pnext2;
cur->pnext2->pnext2 = cur;
cur->pnext2 = t;
prev = prev->pnext2;
swap = 1;
} else {
prev = cur;
cur = cur->pnext2;
}
} else if (sortType == '2') {
if ((sortorder == '1' && cur->cli.clcount > cur->pnext2->cli.clcount) ||
(sortorder == '2' && cur->cli.clcount < cur->pnext2->cli.clcount)) {
t = cur->pnext2->pnext2;
prev->pnext2 = cur->pnext2;
cur->pnext2->pnext2 = cur;
cur->pnext2 = t;
prev = prev->pnext2;
swap = 1;
} else {
prev = cur;
cur = cur->pnext2;
}
}
}
if (swap == 0) {
break;
}
end = cur;
prev = p;
cur = p->pnext2;
}
p = head2->pnext2;
while (p != NULL) {
printf("联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 电话号码数量:%d ",
p->cli.clcount, p->cli.clname, p->cli.clsex, p->cli.clbirthday, p->cli.clmailbox, p->cli.cltelcount);
for (i = 0; i < p->cli.cltelcount; i++) {
printf("电话号码%d:%s ", i + 1, p->cli.cltel[i]);
}
printf("\n");
p = p->pnext2;
}
system("pause");
}
void salsort(struct Node3* head3)//对业务员信息排序
{
if (head3 == NULL) {
printf("输入链表为空!\n");
return;
}
struct Node3* p = head3;
struct Node3* t = NULL;
struct Node3* cur = p->pnext3;
struct Node3* prev = head3;
struct Node3* end = NULL;
int i;
int swap = 0;
p = head3;
printf("请选择排序方式\n");
printf("1-按业务员姓名进行排序\n");
printf("2-按业务员编号进行排序\n");
char sortType = getch();
printf("请选择升降序:\n");
printf("1-升序 2-降序\n");
char sortorder = getch();
while (cur != end) {
swap = 0;
while (cur->pnext3 != end) {
if (sortType == '1') {
if ((sortorder == '1' && strcmp(cur->sal.sname, cur->pnext3->sal.sname) > 0) ||
(sortorder == '2' && strcmp(cur->sal.sname, cur->pnext3->sal.sname) < 0)) {
t = cur->pnext3->pnext3;
prev->pnext3 = cur->pnext3;
cur->pnext3->pnext3 = cur;
cur->pnext3 = t;
prev = prev->pnext3;
swap = 1;
} else {
prev = cur;
cur = cur->pnext3;
}
} else if (sortType == '2') {
if ((sortorder == '1' && cur->sal.scount > cur->pnext3->sal.scount) ||
(sortorder == '2' && cur->sal.scount < cur->pnext3->sal.scount)) {
t = cur->pnext3->pnext3;
prev->pnext3 = cur->pnext3;
cur->pnext3->pnext3 = cur;
cur->pnext3 = t;
prev = prev->pnext3;
swap = 1;
} else {
prev = cur;
cur = cur->pnext3;
}
}
}
if (swap == 0) {
break;
}
end = cur;
prev = p;
cur = p->pnext3;
}
p = head3->pnext3;
while (p != NULL) {
printf("业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 电话号码数量:%d ",
p->sal.scount, p->sal.sname, p->sal.ssex, p->sal.sbirthday, p->sal.smailbocx, p->sal.stelcount);
for (i = 0; i < p->sal.stelcount; i++) {
printf("电话号码%d:%s ", i + 1, p->sal.stel[i]);
}
printf("\n");
p = p->pnext3;
}
system("pause");
}
void cliareasinglestatistic(struct Node1* head)//按区域对客户进行统计
{
struct Node1*p=head;
char narea[10];
int count=0;
printf("请输入要统计的区域:\n");
while(1)
{
scanf("%10s",narea);
//检测输入区域
if(strlen(narea)>9)
{
printf("您输入的客户所在区域过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliarea,narea)==0)
{
count+=1;
}
p=p->pnext1;
}
printf("%s区域的客户人数为:%d\n",narea,count);
system("pause");
}
void cliscalesinglestatistic(struct Node1* head)//按规模对客户进行统计
{
struct Node1*p=head;
char nscale[3];
int count=0;
int i;
printf("请输入客户规模(大,中,小):");
while(1)
{
scanf("%3s",nscale);
//检测输入规模
if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0)
{
break;
}
else if(strlen(nscale)>2)
{
printf("您输入的客户规模过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,nscale)==0)
{
count+=1;
}
p=p->pnext1;
}
printf("%s规模的客户人数为:%d\n",nscale,count);
system("pause");
}
void clilevelsinglestatistic(struct Node1* head)//按联系程度对客户进行统计
{
struct Node1*p=head;
char nlevel[3];
int count=0;
int i;
printf("请输入客户联系程度(高,中,低):");
while(1)
{
scanf("%3s",nlevel);
//检测输入联系程度
if(strcmp(nlevel,"高")==0||strcmp(nlevel,"中")==0||strcmp(nlevel,"低")==0)
{
break;
}
else if(strlen(nlevel)>2)
{
printf("您输入的客户联系程度过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliconlevel,nlevel)==0)
{
count+=1;
}
p=p->pnext1;
}
printf("%s联系程度的客户人数为:%d\n",nlevel,count);
system("pause");
}
void climultistatistic(struct Node1* head1)//按规模和联系程度对客户进行统计
{
struct Node1*p=head1;
int count=0;
int i;
char nscale[3];
char nlevel[3];
printf("请输入客户规模(大,中,小):");
while(1)
{
scanf("%3s",nscale);
if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0)
{
break;
}
else if(strlen(nscale)>2)
{
printf("您输入的客户规模过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
printf("请输入客户联系程度(高,中,低):");
while(1)
{
scanf("%3s", nlevel);
if(strcmp( nlevel,"高")==0||strcmp( nlevel,"中")==0||strcmp( nlevel,"低")==0)
{
break;
}
else if(strlen( nlevel)>2)
{
printf("您输入的客户联系程度过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,nscale)==0&&strcmp(p->cli.cliconlevel,nlevel)==0)
{
count+=1;
}
p=p->pnext1;
}
printf("客户规模为%s和客户联系程度为%s的人数为:%d\n",nscale,nlevel,count);
system("pause");
}
void cliconditionquery(struct Node1* head1)//条件统计查找客户的联络员数量
{
char ncliname[14];
printf("请输入客户姓名:\n");
scanf("%s",ncliname);
struct Node1*p1=head1;
int n = 0;
while(p1!=NULL)
{
if(strcmp (p1->cli.cliname,ncliname)==0)
{
n = 1;
break;
}
p1=p1->pnext1;
}
if(n == 0)
{
printf("无此客户信息!\n");
system("pause");
}
else
{
int count = 0;
for (int i = 0; i < p1->cliaison_size; i++)
{
struct Node2* p2 = p1->headcliaison[i];
while (p2 != NULL)
{
count += 1;
p2 = p2->pnext2;
}
}
printf("该客户的联络员数量为%d\n", count);
system("pause");
}
}
void displaygroupclientcount(struct Node4* head)//对指定分组下客户数量进行统计
{
struct Node4* current = head->pnext4;
int found = 0;//添加一个标志表示是否找到分组
char groupName[12];
printf("请输入组名\n");
scanf("%s",groupName);
if(strlen(groupName)>12)
{
printf("组名过长!请重新输入\n");
while((getchar())!='\n');
}
while (current != NULL)
{
if (strcmp(current->crgroup.cusname,groupName) == 0)
{
printf("分组名称: %s\n", current->crgroup.cusname);
printf("客户数量: %d\n", current->crgroup.size_);
found = 1;
return;
}
current = current->pnext4;
}
if (!found) // 如果未找到匹配的分组
{
printf("未找到分组 '%s'\n", groupName);
}
system("pause");
}
void clistatistics(struct Node1 *head,struct Node4* head_cusgroup)//统计客户信息
{
int clicount = 0;
int targetcliaison =0;
int targetclient = 0;
struct Node1 *current = head->pnext1;
struct Node4* headgroup = NULL;
if (head == NULL)
{
printf("无法进行统计\n");
system("pause");
system("cls");
return;
}
printf("请选择统计方式\n");
printf("1-统计客户数量\n");
printf("2-统计指定区域客户数量\n");
printf("3-统计指定规模客户数量\n");
printf("4-统计指定联系程度客户数量\n");
printf("5-统计指定规模及联系程度的客户数量\n");
printf("6-统计指定客户所有联络员数量\n");
printf("7-统计指定分组下客户数量\n");
printf("0-返回上一界面\n");
while (1)
{
char sortType=getch();
switch(sortType)
{
case '1':
while (current != NULL)
{
clicount++;
current = current->pnext1;
}
printf("客户有%d位\n",clicount);
system("pause");
break;
case '2':
{
cliareasinglestatistic(head);
break;
}
case '3':
{
cliscalesinglestatistic(head);
break;
}
case '4':
{
clilevelsinglestatistic(head);
break;
}
case '5':
{
climultistatistic(head);
break;
}
case '6':
{
cliconditionquery(head);
break;
}
case '7':
{
displaygroupclientcount(head_cusgroup);
break;
}
case '0':
{
break;
}
default:
{
printf("输入错误,请重新输入!\n");
system("pause");
break;
}
}
if(sortType=='0')
{
system("cls");
break;
}
}
}
void clstatistics(struct Node2 *head)//统计客户联络员数量
{
int clcount = 0;
struct Node2 *current2 = head->pnext2;
if (head == NULL)
{
printf("无法进行统计\n");
return;
}
while (current2 != NULL)
{
clcount++;
current2 = current2->pnext2;
}
printf("客户联络员有%d位\n",clcount);
system("pause");
}
void salstatistics(struct Node3 *head)//统计业务员数量
{
int salcount = 0;
struct Node3 *current = head->pnext3;
if (head == NULL)
{
printf("无法进行统计\n");
system("pause");
return;
}
while (current != NULL)
{
salcount++;
current = current->pnext3;
}
printf("业务员有%d位\n",salcount);
system("pause");
}
void clisort(struct Node1 *head1)
{
struct Node1*p=head1->pnext1;
int i;
printf("请选择排序方式\n");
printf("1-根据客户编号进行排序\n");
printf("2-根据客户所在区域进行排序\n");
printf("3-根据客户规模进行排序\n");
printf("4-先根据客户所在区域进行排序,后根据客户编号进行排序\n");
printf("5-先根据客户规模进行排序,后根据客户编号进行排序\n");
char sortType=getch();
switch(sortType)
{
case '1':
sortByClientCount(head1->pnext1);
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
break;
case '2':
sortByClientArea(head1->pnext1);
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
break;
case '3':
sortByClientScale(head1->pnext1);
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
break;
case '4':
sortByClientArea(head1->pnext1);
sortByClientCount(head1->pnext1);
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
break;
case '5':
sortByClientScale(head1->pnext1);
sortByClientCount(head1->pnext1);
while(p != NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p = p->pnext1;
}
system("pause");
system("cls");
break;
}
}
// 插入客户节点
void insertClient(struct Node1 **head, struct client newClient)
{
struct Node1 *newNode = (struct Node1 *)malloc(sizeof(struct Node1));
newNode->cli = newClient;
newNode->pnext1 = *head;
*head = newNode;
}
// 交换两个客户节点
void swap(struct Node1 *a, struct Node1 *b)
{
struct client temp = a->cli;
a->cli = b->cli;
b->cli = temp;
}
// 根据客户编号进行排序
void sortByClientCount(struct Node1 *head)
{
int swapped;
struct Node1 *ptr1 = NULL;
struct Node1 *lptr = NULL;
/* 检查链表是否为空 */
if (head == NULL) return;
do
{
swapped = 0;
ptr1 = head;
while (ptr1->pnext1 != lptr)
{
if (ptr1->cli.clicount > ptr1->pnext1->cli.clicount)
{
swap(ptr1, ptr1->pnext1);
swapped = 1;
}
ptr1 = ptr1->pnext1;
}
lptr = ptr1;
} while (swapped);
}
// 根据客户所在区域进行排序
void sortByClientArea(struct Node1 *head)
{
int swapped;
struct Node1 *ptr1;
struct Node1 *lptr = NULL;
/* 检查链表是否为空 */
if (head == NULL)
return;
do
{
swapped = 0;
ptr1 = head;
while (ptr1->pnext1 != lptr)
{
if (strcmp(ptr1->cli.cliarea, ptr1->pnext1->cli.cliarea) > 0)
{
swap(ptr1, ptr1->pnext1);
swapped = 1;
}
ptr1 = ptr1->pnext1;
}
lptr = ptr1;
} while (swapped);
}
// 根据客户规模进行排序
void sortByClientScale(struct Node1 *head)
{
int swapped;
struct Node1 *ptr1;
struct Node1 *lptr = NULL;
/* 检查链表是否为空 */
if (head == NULL)
return;
do
{
swapped = 0;
ptr1 = head;
while (ptr1->pnext1 != lptr)
{
if (ptr1->cli.cliscale > ptr1->pnext1->cli.cliscale)
{
swap(ptr1, ptr1->pnext1);
swapped = 1;
}
ptr1 = ptr1->pnext1;
}
lptr = ptr1;
} while (swapped);
}
//计林敏的函数定义
void pwmaintenance(char mpw[],char spw[])//密码维护
{
char nmpw[14],nnmpw[14],nspw[14],nnspw[14];
char i[3];
printf("1.修改经理密码 2.修改业务员密码 3.重置经理密码 4.重置业务员密码 0.退出密码维护功能\n请输入您要执行的操作:");
while(1)
{
while(1)
{
scanf("%2s",i);
i[2]='\0';
if(strlen(i)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(i[0]=='1')
{
printf("请输入您的12位以内的新密码:\n");
while(1)
{
while(1)
{
scanf("%13s",nmpw);
nmpw[13]='\0';
if(strlen(nmpw)>12)
{
printf("您输入的密码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请再次输入您的12位以内新密码:\n");
while(1)
{
scanf("%13s",nnmpw);
nnmpw[13]='\0';
if(strlen(nnmpw)>12)
{
printf("您输入的密码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(strcmp(nmpw,nnmpw)==0)
{
strcpy(mpw,nmpw);
printf("您的密码修改成功!\n");
break;
}
else
{
printf("两次输入的密码不一致,请重新输入您的12位以内的新密码:\n");
}
}
system("pause");
break;
}
else if(i[0]=='2')
{
printf("请输入业务员的12位以内的新密码:\n");
while(1)
{
while(1)
{
scanf("%13s",nspw);
nmpw[13]='\0';
if(strlen(nspw)>12)
{
printf("您输入的密码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请再次输入您的12位以内新密码:\n");
while(1)
{
scanf("%13s",nnspw);
nnmpw[13]='\0';
if(strlen(nnspw)>12)
{
printf("您输入的密码过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(strcmp(nspw,nnspw)==0)
{
strcpy(spw,nspw);
printf("您的密码修改成功!\n");
break;
}
else
{
printf("两次输入的密码不一致,请重新输入您的12位以内的新密码:\n");
}
}
system("pause");
break;
}
else if(i[0]=='3')
{
strcpy(mpw,"123456");
printf("您的密码重置成功!\n");
system("pause");
break;
}
else if(i[0]=='4')
{
strcpy(spw,"123456");
printf("业务员的密码重置成功!\n");
system("pause");
break;
}
else if(i[0]=='0')
{
break;
}
else
{
printf("您的输入有误,请重新输入:\n");
}
}
}
void datebackup(struct Node1* np1,struct Node2* np2,struct Node3* np3)//数据备份
{
struct Node1* p1=np1->pnext1;
struct Node2* p2=np2->pnext2;
struct Node3* p3=np3->pnext3;
char i[3];
int j;
printf("1.备份客户数据 2.备份客户联络员数据 3.备份业务员数据 0.退出数据备份功能\n请选择要执行的操作:");
while(1)
{
while(1)
{
scanf("%2s",i);
i[2]='\0';
if(strlen(i)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(i[0]=='1')
{
//打开文件
FILE *fp= fopen("C:\\customer.data","w");//写入,如果文件不存在创建文件,文件存在清空内容再写入
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
if(p1==NULL)
{
printf("您没有客户数据可备份!\n");
system("pause");
break;
}
while(p1!=NULL)
{
fprintf(fp,"客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d ",
p1->cli.clicount,p1->cli.cliname,p1->cli.cliarea,p1->cli.cliaddress,
p1->cli.clilegalman,p1->cli.cliscale,p1->cli.cliconlevel,p1->cli.climailbox,
p1->cli.clitelcount);
for(j=0;j<p1->cli.clitelcount;j++)
{
fprintf(fp,"客户电话号码%d:%s ",j+1,p1->cli.clitel[j]);
}
fprintf(fp,"\n");
p1=p1->pnext1;
}
fclose(fp);//释放对该文件的占用,避免数据丢失
printf("客户数据备份成功!\n");
system("pause");
break;
}
else if(i[0]=='2')
{
//打开文件
FILE *fp= fopen("C:\\cliaison.data","w");
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
if(p2==NULL)
{
printf("您没有客户联络员数据可备份!\n");
system("pause");
break;
}
while(p2!=NULL)
{
fprintf(fp,"联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 联络员电话号码数量:%d ",
p2->cli.clcount,p2->cli.clname,p2->cli.clsex,p2->cli.clbirthday,p2->cli.clmailbox,p2->cli.cltelcount);
for(j=0;j<p2->cli.cltelcount;j++)
{
fprintf(fp,"联络员电话号码%d:%s ",j+1,p2->cli.cltel[j]);
}
fprintf(fp,"\n");
p2=p2->pnext2;
}
fclose(fp);
printf("客户联络员数据备份成功!\n");
system("pause");
break;
}
else if(i[0]=='3')
{
//打开文件
FILE *fp= fopen("C:\\salesman.data","w");
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
if(p3==NULL)
{
printf("您没有业务员数据可备份!\n");
system("pause");
break;
}
while(p3!=NULL)
{
fprintf(fp,"业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 业务员电话号码数量:%d ",
p3->sal.scount,p3->sal.sname,p3->sal.ssex,p3->sal.sbirthday,p3->sal.smailbocx,p3->sal.stelcount
);
for(j=0;j<p3->sal.stelcount;j++)
{
fprintf(fp,"业务员电话号码%d:%s ",j+1,p3->sal.stel[j]);
}
fprintf(fp,"\n");
p3=p3->pnext3;
}
fclose(fp);
printf("业务员数据备份成功!\n");
system("pause");
break;
}
else if(i[0]=='0')
{
break;
}
else
{
printf("您的输入有误,请重新输入:\n");
}
}
}
void recoverydata(struct Node1* p1,struct Node2* p2,struct Node3* p3)//数据恢复
{
char i[3];
int j;
printf("1.恢复客户数据 2.恢复客户联络员数据 3.恢复业务员数据 0.退出数据恢复功能\n请选择要执行的操作:");
while(1)
{
while(1)
{
scanf("%2s",i);
i[2]='\0';
if(strlen(i)>1)
{
printf("您的输入有误,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
if(i[0]=='1')
{
//打开文件
FILE *fp= fopen("C:\\customer.data","r");//只读,不能进行修改
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
//feof(fp) 只有在尝试从文件中读取数据,并且读取操作到达文件末尾时,才会返回非零值(通常是 true)。
//所以循环不退出是因为feof()这个函数只有读到文件末尾才会返回true,而我是用feof()判断的,然后再读,
//在循环中读到最后之后还要判断一次feof()但是循环中已经读不了数据了,此时feof()返回false,然后就会造成无限循环
while(!feof(fp))
{
struct Node1 *np1=(struct Node1*)malloc(sizeof(struct Node1));
if(fscanf(fp,"客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d ",
&np1->cli.clicount,np1->cli.cliname,np1->cli.cliarea,np1->cli.cliaddress,
np1->cli.clilegalman,np1->cli.cliscale,np1->cli.cliconlevel,np1->cli.climailbox,
&np1->cli.clitelcount)==EOF)
{
free(np1);
break;
}
for(j=1;j<(np1->cli.clitelcount+1);j++)
{
fscanf(fp,"客户电话号码%d:%s ",&j,np1->cli.clitel[j-1]);
}
np1->pnext1=NULL;
if(p1==NULL)
{
p1=np1;
}
else
{
while(p1->pnext1!=NULL)
{
p1=p1->pnext1;
}
p1->pnext1=np1;
}
}
fclose(fp);
printf("客户数据恢复成功!\n");
system("pause");
break;
}
else if(i[0]=='2')
{
//打开文件
FILE *fp= fopen("C:\\cliaison.data","r");
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
while(!feof(fp))
{
struct Node2 *np2=(struct Node2*)malloc(sizeof(struct Node2));
if(fscanf(fp,"联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 联络员电话号码数量:%d ",
&np2->cli.clcount, np2->cli.clname, np2->cli.clsex, np2->cli.clbirthday, np2->cli.clmailbox, &np2->cli.cltelcount)==EOF)
{
free(np2);
break;
}
for(j=1;j<(np2->cli.cltelcount+1);j++)
{
fscanf(fp,"联络员电话号码%d:%s ",&j,np2->cli.cltel[j-1]);
}
np2->pnext2=NULL;
if(p2==NULL)
{
p2=np2;
}
else
{
while(p2->pnext2!=NULL)
{
p2=p2->pnext2;
}
p2->pnext2=np2;
}
}
fclose(fp);
printf("客户联络员数据恢复成功!\n");
system("pause");
break;
}
else if(i[0]=='3')
{
//打开文件
FILE *fp= fopen("C:\\salesman.data","r");
if(fp==NULL)
{
printf("打开文件失败!\n");
perror("错误原因:");//显示错误原因
system("pause");
break;
}
while(!feof(fp))
{
struct Node3 *np3=(struct Node3*)malloc(sizeof(struct Node3));
if(fscanf(fp,"业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 业务员电话号码数量:%d ",
&np3->sal.scount,np3->sal.sname,np3->sal.ssex,np3->sal.sbirthday,np3->sal.smailbocx,&np3->sal.stelcount
)==EOF)
{
free(np3);
break;
}
for(j=1;j<(np3->sal.stelcount+1);j++)
{
fscanf(fp,"业务员电话号码%d:%s ",&j,np3->sal.stel[j-1]);
}
np3->pnext3=NULL;
if(p3==NULL)
{
p3=np3;
}
else
{
while(p3->pnext3!=NULL)
{
p3=p3->pnext3;
}
p3->pnext3=np3;
}
}
fclose(fp);
printf("业务员数据恢复成功!\n");
system("pause");
break;
}
else if(i[0]=='0')
{
break;
}
else
{
printf("您的输入有误,请重新输入:\n");
}
}
}
void simplequery(struct Node1* head1)//简单查询
{
char ncliname[12];
int i;
printf("请输入要查找的客户姓名:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node1*p=head1;
while(p!=NULL)
{
if(strcmp (p->cli.cliname,ncliname)==0)
{
break;
}
p=p->pnext1;
}
if(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
else
{
printf("未查询到该顾客信息!\n");
}
system("pause");
system("cls");
}
void combinedquery(struct Node1* head1)//组合查询
{
char ncliname[12];//客户姓名
char ncliarea[10];//客户所在区域
char ncliaddress[30];//客户所在地址
int i;
printf("请输入要查找的客户姓名:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入要查找的客户所在区域:\n");
while(1)
{
scanf("%10s",ncliarea);
if(strlen(ncliname)>8)
{
printf("您输入的客户所在区域过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
printf("请输入要查找的客户所在地址:\n");
while(1)
{
scanf("%30s",ncliaddress);
if(strlen(ncliaddress)>28)
{
printf("您输入的客户所在地址过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node1*p=head1;
while(p!=NULL)
{
if(strcmp (p->cli.cliname,ncliname)==0&&strcmp(p->cli.cliarea,ncliarea)==0&&strcmp (p->cli.cliaddress,ncliaddress)==0)
{
break;
}
p=p->pnext1;
}
if(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
else
{
printf("未查询到该顾客信息!\n");
}
system("pause");
system("cls");
}
void fuzzyquery(struct Node1* head1)//模糊查询
{
char ncliname[12];
int i;
printf("请输入要查找的客户姓名的关键字:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名关键字过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node1*p=head1;
if(p==NULL)
{
printf("未查询到该顾客信息!\n");
}
while(p!=NULL)
{
if(strstr (p->cli.cliname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
p=p->pnext1;
}
system("pause");
system("cls");
}
void slightsort(struct Node1* head1)//单一排序
{
if (head1 == NULL)
{
printf("输入链表为空!\n");
return;
}
struct Node1*p=head1;
struct Node1*t=NULL;//避免野指针
struct Node1*cur=p->pnext1;
struct Node1*prev=head1;
struct Node1*end=NULL;//避免野指针
int i;
int swap=0;
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,"大")==0)
{
p->cli.cliordernumber=3;
}
else if(strcmp(p->cli.cliscale,"中")==0)
{
p->cli.cliordernumber=2;
}
else
{
p->cli.cliordernumber=1;
}
p=p->pnext1;
}
//排序
p=head1;
while(cur!=end)
{
swap=0;
while(cur->pnext1!=end)
{
if(cur->cli.cliordernumber<cur->pnext1->cli.cliordernumber)
{
t=cur->pnext1->pnext1;
prev->pnext1=cur->pnext1;
cur->pnext1->pnext1=cur;
cur->pnext1=t;
prev=prev->pnext1;
swap=1;
}
else
{
prev=cur;
cur=cur->pnext1;
}
}
if(swap==0)
{
break;
}
end=cur;
prev=p;
cur=p->pnext1;
}
p=head1->pnext1;
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
}
void combinsort(struct Node1* head1)//组合排序
{
if (head1 == NULL)
{
printf("输入链表为空!\n");
return;
}
struct Node1*p=head1;
struct Node1*t=NULL;//避免野指针
struct Node1*cur=p->pnext1;
struct Node1*prev=head1;//避免野指针
struct Node1*end=NULL;//避免野指针
int i;
int swap=0;
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"高")==0)
{
p->cli.cliordernumber=9;
}
else if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"中")==0)
{
p->cli.cliordernumber=8;
}
else if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"低")==0)
{
p->cli.cliordernumber=7;
}
else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"高")==0)
{
p->cli.cliordernumber=6;
}
else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"中")==0)
{
p->cli.cliordernumber=5;
}
else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"低")==0)
{
p->cli.cliordernumber=4;
}
else if(strcmp(p->cli.cliscale,"小")==0&&strcmp(p->cli.cliconlevel,"高")==0)
{
p->cli.cliordernumber=3;
}
else if(strcmp(p->cli.cliscale,"小")==0&&strcmp(p->cli.cliconlevel,"中")==0)
{
p->cli.cliordernumber=2;
}
else
{
p->cli.cliordernumber=1;
}
p=p->pnext1;
}
//排序
p=head1;
while(cur!=end)
{
swap=0;
while(cur->pnext1!=end)
{
if(cur->cli.cliordernumber<cur->pnext1->cli.cliordernumber)
{
t=cur->pnext1->pnext1;
prev->pnext1=cur->pnext1;
cur->pnext1->pnext1=cur;
cur->pnext1=t;
prev=prev->pnext1;
swap=1;
}
else
{
prev=cur;
cur=cur->pnext1;
}
}
if(swap==0)
{
break;
}
end=cur;
prev=p;
cur=p->pnext1;
}
p=head1->pnext1;
while(p!=NULL)
{
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
p=p->pnext1;
}
system("pause");
system("cls");
}
void singlestatistic(struct Node1* head1)//单一统计
{
struct Node1*p=head1;
char narea[10];
int count=0;
int i;
printf("请输入要统计的区域:\n");
while(1)
{
scanf("%10s",narea);
if(strlen(narea)>8)
{
printf("您输入的客户所在区域过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliarea,narea)==0)
{
count+=1;
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
p=p->pnext1;
}
printf("%s区域的客户人数为:%d\n",narea,count);
system("pause");
system("cls");
}
void multistatistic(struct Node1* head1)//多属性统计
{
struct Node1*p=head1;
int count=0;
int i;
char nscale[3];
char nlevel[3];
printf("请输入客户规模(大,中,小):");
while(1)
{
scanf("%3s",nscale);
if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0)
{
break;
}
else if(strlen(nscale)>1)
{
printf("您输入的客户规模过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
printf("请输入客户联系程度(高,中,低):");
while(1)
{
scanf("%3s", nlevel);
if(strcmp( nlevel,"高")==0||strcmp( nlevel,"中")==0||strcmp( nlevel,"低")==0)
{
break;
}
else if(strlen( nlevel)>1)
{
printf("您输入的客户联系程度过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
printf("您的输入有误,请按规定重新输入:\n");
}
}
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,nscale)==0&&strcmp(p->cli.cliconlevel,nlevel)==0)
{
count+=1;
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
p=p->pnext1;
}
printf("客户规模为%s和客户联系程度为%s的人数为:%d\n",nscale,nlevel,count);
system("pause");
system("cls");
}
void defaultstatistic(struct Node1* head1)//预设条件统计高规模客户数
{
struct Node1*p=head1;
int count=0;
int i;
while(p!=NULL)
{
if(strcmp(p->cli.cliscale,"大")==0)
{
count+=1;
printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d "
,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress,
p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount);
for(i=0;i<p->cli.clitelcount;i++)
{
printf("电话号码%d:%s ",i+1,p->cli.clitel[i]);
}
printf("\n");
}
p=p->pnext1;
}
printf("高规模的客户人数为%d\n",count);
system("pause");
system("cls");
}
void conditionquery(struct Node1* head1)//条件统计查找客户的联络员数量
{
char ncliname[12];
int i,j,count;
printf("请输入您要查找某一客户的联络员数量的客户姓名:\n");
while(1)
{
scanf("%12s",ncliname);
if(strlen(ncliname)>10)
{
printf("您输入的客户姓名过长,请重新输入:\n");
while((getchar())!='\n');
}
else
{
break;
}
}
struct Node1*p1=head1;
while(p1!=NULL)
{
if(strcmp (p1->cli.cliname,ncliname)==0)
{
break;
}
p1=p1->pnext1;
}
if(p1==NULL)
{
printf("无此客户信息!\n");
system("pause");
system("cls");
}
else
{
for(i=0;p1->headcliaison[i]!=NULL;i++)
{
count+=1;
printf(" 客户联络员编号:%d 客户联络员姓名:%s 客户联络员性别:%s 客户联络员生日:%s 客户联络员邮箱:%s 客户联络员电话号码数量",
p1->headcliaison[i]->cli.clcount,p1->headcliaison[i]->cli.clname,p1->headcliaison[i]->cli.clsex,p1->headcliaison[i]->cli.clbirthday
,p1->headcliaison[i]->cli.clmailbox,p1->headcliaison[i]->cli.cltelcount);
for(j=0;j<p1->headcliaison[i]->cli.cltelcount;j++)
{
printf("电话号码数%d:%s",j+1,p1->headcliaison[i]->cli.cltel[j]);
}
printf("\n");
}
printf("该客户的联络员数量为%d\n",count);
system("pause");
system("cls");
}
}
//王兴家的函数定义
int verify(char *kk)//验证
{
char sss[20];
scanf("%s", sss);
if (strcmp(sss, kk) == 0)
return 1;
else
return 0;
}
void Set_Salesman_passsword(char *password)//设置
{
char new_password[20];
char confirm_password[20];
printf("请输入新的销售人员密码:\n");
scanf("%s", new_password);
printf("请再次输入新的销售人员密码以确认:\n");
scanf("%s", confirm_password);
if (strcmp(new_password, confirm_password) == 0)
{
strcpy(password, new_password);
printf("销售人员密码设置成功!\n");
}
else
{
printf("两次输入的密码不匹配,请重新设置销售人员密码!\n");
}
}
//清空输入缓冲区
void clearInputBuffer() {
while (getchar() != '\n')
;
}
//安全读取字符串
void safeReadString(char *str, int size) {
int success = 0;
while (!success) {
if (scanf("%19s", str) == 1) { // 假设字符串大小为20
success = 1;
} else {
printf("输入错误,请重新输入:");
clearInputBuffer();
}
}
clearInputBuffer(); // 清除字符串后的换行符
}
//安全读取整数
int safeReadInt() {
int success = 0;
char input[20];
while (!success) {
if (scanf("%19s", input) == 1) { // 假设数字字符串大小为20
int valid = 1;
for (int i = 0; i < strlen(input); i++) {
if (!isdigit(input[i])) {
valid = 0;
break;
}
}
if (valid) {
success = 1;
return atoi(input);
} else {
printf("输入错误,请重新输入:");
clearInputBuffer();
}
} else {
printf("输入错误,请重新输入:");
clearInputBuffer();
}
}
}
//添加新记录
void addNewRecord(struct comcontent **head)
{
struct comcontent *newRecord = (struct comcontent *)malloc(sizeof(struct comcontent));
if (newRecord == NULL)
{
printf("内存分配失败!\n");
return;
}
printf("输入客户公司名称:");
safeReadString(newRecord->ccompny, 20);
printf("输入客户联络员名称:");
safeReadString(newRecord->cclname, 20);
printf("输入通信发生的年份:");
newRecord->year = safeReadInt();
printf("输入通信发生的月份:");
newRecord->month = safeReadInt();
printf("输入通信发生的日期:");
newRecord->day = safeReadInt();
printf("输入通信发生的小时:");
newRecord->hour = safeReadInt();
printf("输入通信持续时间(分钟):");
newRecord->duration = safeReadInt();
printf("输入通信内容:");
safeReadString(newRecord->contnt, 100);
printf("输入通信类型:");
safeReadString(newRecord->comtype, 20);
printf("输入通信次数:");
newRecord->comcount = safeReadInt();
// 写入文件
FILE *file = fopen("records.txt", "a");
if (file == NULL)
{
printf("无法打开文件!\n");
free(newRecord);
return;
}
fprintf(file, "客户公司名称: %s\n", newRecord->ccompny);
fprintf(file, "客户联络员名称: %s\n", newRecord->cclname);
fprintf(file, "通信发生的时间: %d-%02d-%02d %02d:00\n", newRecord->year, newRecord->month, newRecord->day, newRecord->hour);
fprintf(file, "通信持续时间(分钟): %d\n", newRecord->duration);
fprintf(file, "通信内容: %s\n", newRecord->contnt);
fprintf(file, "通信类型: %s\n", newRecord->comtype);
fprintf(file, "通信次数: %d\n", newRecord->comcount);
fprintf(file, "\n"); // 分隔每条记录
fclose(file);
// 将记录添加到链表头部
newRecord->next = *head;
*head = newRecord;
printf("记录添加成功\n");
system("pause");
system("cls");
}
//修改记录
void modifyRecord(struct comcontent **head)
{
char targetCompany[20];
printf("输入要修改通信记录的客户公司名称:");
safeReadString(targetCompany, 20);
struct comcontent *current = *head;
int found = 0;
while (current != NULL) {
if (strcmp(current->ccompny, targetCompany) == 0) {
// 找到匹配的记录
found = 1;
printf("找到匹配的通信记录!\n");
// 在这里编写修改信息的代码,例如:
printf("请输入新的通信内容:");
safeReadString(current->contnt, 100);
printf("通信内容已修改!\n");
}
current = current->next;
}
if (!found) {
// 若未找到匹配的记录
printf("未找到匹配的通信记录。\n");
}
system("pause");
system("cls");
}
//打印记录
void printAllRecords(struct comcontent **head) {
if (*head == NULL) {
printf("没有任何通信记录。\n");
}
struct comcontent *current = *head;
printf("所有通信记录:\n");
printf("------------------------------------------------------------------------\n");
printf("| %-20s | %-20s | %4s | %2s | %2s | %2s | %3s | %-20s | %-20s | %6s |\n", "客户公司名称", "客户联络员名称", "年份", "月份", "日期", "小时", "时长", "通信内容", "通信类型", "通信次数");
printf("------------------------------------------------------------------------\n");
while (current != NULL) {
if(current->ccompny == NULL || current->cclname == NULL || current->contnt == NULL || current->comtype == NULL) {
printf("错误:通信记录中存在空指针。\n");
break; // 直接终止函数
}
printf("| %-20s | %-20s | %4d | %2d | %2d | %2d | %3d | %-20s | %-20s | %6d |\n",
current->ccompny, current->cclname, current->year, current->month, current->day,
current->hour, current->duration, current->contnt, current->comtype,
current->comcount);
current = current->next;
}
printf("-------------------------------------------------------------------------\n");
system("pause");
system("cls");
}
//释放内存
void freeMemory(struct comcontent *head) {
struct comcontent *current = head;
while (current != NULL) {
struct comcontent *next = current->next;
free(current);
current = next;
}
}
//读文件
void addNewRecordFromFile(struct comcontent **head) {
FILE *file = fopen("records.txt", "r");
if (file == NULL) {
printf("无法打开文件!\n");
return;
}
while (!feof(file)) {
struct comcontent *newRecord = (struct comcontent *)malloc(sizeof(struct comcontent));
if (newRecord == NULL) {
printf("内存分配失败!\n");
fclose(file);
return;
}
// 逐行读取文件中的记录
fscanf(file, "客户公司名称: %s\n", newRecord->ccompny);
fscanf(file, "客户联络员名称: %s\n", newRecord->cclname);
fscanf(file, "通信发生的时间: %d-%d-%d %d:00\n", &newRecord->year, &newRecord->month, &newRecord->day, &newRecord->hour);
fscanf(file, "通信持续时间(分钟): %d\n", &newRecord->duration);
// 读取通信内容,包括空格,直到遇到换行符
fscanf(file, "通信内容: ");
fgets(newRecord->contnt, sizeof(newRecord->contnt), file);
strtok(newRecord->contnt, "\n"); // 去除fgets末尾的换行符
// 读取通信类型,包括空格,直到遇到换行符
fscanf(file, "通信类型: ");
fgets(newRecord->comtype, sizeof(newRecord->comtype), file);
strtok(newRecord->comtype, "\n"); // 去除fgets末尾的换行符
fscanf(file, "通信次数: %d\n", &newRecord->comcount);
newRecord->next = *head;
*head = newRecord;
}
fclose(file);
printf("文件录入成功\n");
system("pause");
system("cls");
}
//按时间排序
void sortByTime(struct comcontent **head)
{
// 如果链表为空或只有一个节点,无需排序
if (*head == NULL || (*head)->next == NULL) {
}
// 创建一个新的空链表,用于存放已排序的节点
struct comcontent* sorted = NULL;
struct comcontent* current = *head;
// 遍历原链表的每个节点
while (current != NULL) {
// 先将当前节点从原链表中取出
struct comcontent* next = current->next;
current->next = NULL;
// 将当前节点插入已排序的链表中
if (sorted == NULL || current->year > sorted->year ||
(current->year == sorted->year && current->month > sorted->month) ||
(current->year == sorted->year && current->month == sorted->month && current->day > sorted->day) ||
(current->year == sorted->year && current->month == sorted->month && current->day == sorted->day && current->hour > sorted->hour)) {
// 如果当前节点时间比已排序节点的时间更晚,将其作为新的头部节点
current->next = sorted;
sorted = current;
} else {
// 否则,在已排序链表中找到合适的位置插入当前节点
struct comcontent* temp = sorted;
while (temp->next != NULL &&
(current->year < temp->next->year ||
(current->year == temp->next->year && current->month < temp->next->month) ||
(current->year == temp->next->year && current->month == temp->next->month && current->day < temp->next->day) ||
(current->year == temp->next->year && current->month == temp->next->month && current->day == temp->next->day && current->hour < temp->next->hour))) {
temp = temp->next;
}
// 将当前节点插入temp节点后面
current->next = temp->next;
temp->next = current;
}
// 继续处理下一个节点
current = next;
}
// 更新原链表的头指针
*head = sorted;
system("pause");
system("cls");
}
//统计链表中的信息函数
void countTotalStats(struct comcontent *head) {
int totalCommunicationCount = 0; // 总通信次数
int totalYearCount = 0; // 总年份数量
int totalMonthCount = 0; // 总月份数量
int totalDateCount = 0; // 总日期数量
int totalHourCount = 0; // 总小时数量
// 遍历链表,累加统计信息
struct comcontent *current = head;
while (current != NULL) {
totalCommunicationCount += current->comcount;
totalYearCount += current->year;
totalMonthCount += current->month;
totalDateCount += current->day;
totalHourCount += current->hour;
// 继续处理下一个节点
current = current->next;
}
// 打印统计信息(中文)
printf("总通信次数: %d\n", totalCommunicationCount);
printf("总年份数量: %d\n", totalYearCount);
printf("总月份数量: %d\n", totalMonthCount);
printf("总日期数量: %d\n", totalDateCount);
printf("总小时数量: %d\n", totalHourCount);
system("pause");
system("cls");
}
| 2303_806435pww/tongxin_moved | function.c | C | unknown | 108,524 |
#include"tool.h"
#include"declaration.h"
void allocation(struct Node1* head,struct Node3* head_)//给业务员分配客户的显示部分
{
printf("客户简要信息\n");
show_customer(head);
printf("业务员\n");
show_salesman(head_);
give_salesman_customer(head,head_);
}
void give_salesman_customer(struct Node1* head,struct Node3* head_)//分配的修改部分
{
struct Node3* t = head_->pnext3;
int num = 0, time = 0;
printf("请输入业务员编号:");
int n = 0;
while (1)
{
if(scanf("%d",&n)!=1||n<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
while (t != NULL)
{
if (n == t->sal.scount)
{
do
{
printf("请输入所选客户的编号:");
printf("(输入0退出)");
scanf("%d", &num);
if (num == 0) break; // 用户输入0时退出循环
struct Node1* p = head->pnext1;
while (p != NULL)
{
if (p->cli.clicount == num)
{
if (time < 20)
{ // 确保不超出数组界限
t->sal.saleclient[time] = p;
time++;
t->sal.saleclient_size = time;
break; // 找到匹配项后跳出内层循环
}
else
{
printf("销售人员的客户列表已满。\n");
break;
}
}
p = p->pnext1;
}
} while (num != 0);
}
t = t->pnext3;
}
}
void show_salesman_clients(struct Node3* head_)//显示给业务员分配的客户的部分
{
struct Node3* t = head_->pnext3;
while (t != NULL) {
printf("业务员编号: %d\n", t->sal.scount);
for (int i = 0; i < t->sal.saleclient_size; i++)
{
printf("分配的客户编号,名字:");
if (t->sal.saleclient[i] != NULL) {
printf("%d %s", t->sal.saleclient[i]->cli.clicount,t->sal.saleclient[i]->cli.cliname);
}
}
printf("\n");
t = t->pnext3;
}
system("pause");
}
void modify_salesman_customer(struct Node1* head, struct Node3* head_)
{
// 显示客户信息和业务员信息
printf("客户简要信息\n");
show_customer(head);
printf("业务员\n");
show_salesman(head_);
// 输入业务员编号
int salesman_num;
printf("请输入要修改客户分配的业务员编号:");
scanf("%d", &salesman_num);
// 查找对应业务员节点
struct Node3* current_salesman = head_->pnext3;
while (current_salesman != NULL) {
if (current_salesman->sal.scount == salesman_num) {
// 输入要分配的客户编号
int client_num, time = 0;
do {
printf("请输入要分配给该业务员的客户编号:(输入0退出)");
scanf("%d", &client_num);
if (client_num == 0) break; // 输入0退出循环
// 在客户链表中查找对应客户编号的客户节点
struct Node1* current_client = head->pnext1;
while (current_client != NULL) {
if (current_client->cli.clicount == client_num) {
if (time < 20) {
// 将客户添加到业务员的客户数组中
current_salesman->sal.saleclient[time] = current_client;
time++;
current_salesman->sal.saleclient_size = time;
printf("客户编号为 %d 的客户分配给业务员编号为 %d 的业务员成功。\n", client_num, salesman_num);
break; // 找到匹配项后跳出内层循环
} else {
printf("业务员的客户列表已满。\n");
break;
}
}
current_client = current_client->pnext1;
}
if (current_client == NULL) {
printf("未找到编号为 %d 的客户。\n", client_num);
}
} while (client_num != 0);
// 已找到对应业务员,不需要继续循环
break;
}
current_salesman = current_salesman->pnext3;
}
// 如果未找到对应业务员,输出提示信息
if (current_salesman == NULL) {
printf("未找到编号为 %d 的业务员。\n", salesman_num);
}
}
void allocation_customer_cliasion(struct Node1* head,struct Node2* head_)//给客户与联络员的链接的显示部分
{
printf("客户简要信息\n");
show_customer(head);
printf("业务联络员\n");
show_cliasion(head_);
give_customer_cliaison(head,head_);
}
void give_customer_cliaison(struct Node1* head,struct Node2* head_)//分配的修改部分
{
struct Node1* t = head->pnext1;
int num = 0, time = 0;
printf("请输入客户编号:");
int n = 0;
while (1)
{
if(scanf("%d",&n)!=1||n<0)
{
printf("输入错误,请重新输入:\n");
while((getchar())!='\n');
continue;
}
else
{
break;
}
}
while (t != NULL)
{
if (n == t->cli.clicount)
{
| 2303_806435pww/tongxin_moved | function2.c | C | unknown | 5,824 |
#include"tool.h"
#include "declaration.h"
int main()
{ //初始密码
char pwman[14],pwslman[14];
char mpassward[14];
char spassward[14];
strcpy(pwman,"123456");
strcpy(pwslman,"123456");
struct Node1* head_customer = (struct Node1 *)malloc(sizeof(struct Node1));//创建表头
head_customer->pnext1 = NULL;
struct Node1* end_customer = head_customer;
struct Node2* head_cliaison = (struct Node2 *)malloc(sizeof(struct Node2));//创建表头
head_cliaison->pnext2 = NULL;
struct Node2* end_cliaison = head_cliaison;
struct Node3* head_salesman = (struct Node3 *)malloc(sizeof(struct Node3));//创建表头
head_salesman->pnext3 = NULL;
struct Node3* end_salesman = head_salesman;
struct Node4* head_group = (struct Node4 *)malloc(sizeof(struct Node4));//创建表头
head_group->pnext4 = NULL;
struct Node4* end_group = head_group;
struct comcontent *head = NULL;//声明一个指向通信内容的指针变量
while(1)
{
welcome();//欢迎界面函数
char ch=getch();//读取一个字符可以不按回车执行
if(ch=='1')
{
printf("请输入您的密码:\n");
scanf("%14s",mpassward);
if(strcmp(mpassward,pwman)==0)
{
printf("密码正确,欢迎使用通信管理系统!\n");
system("pause");
system("cls");//清屏
while(1)
{
mfunctionalinterface();//经理界面函数
char mh=getch();//读取一个字符可以不按回车执行
switch (mh)
{
case '1':
while(1)
{
system("cls");
mfunctionalinterface1();//经理基本信息管理界面
char mh1=getch();
switch(mh1)
{
case '1':
end_salesman = creat_note_salesman(end_salesman);
break;
case '2':
end_customer = creat_note_customer(end_customer);
break;
case '3':
end_cliaison = creat_note_cliaison(end_cliaison);
break;
case '4':
search_salesman(head_salesman);
break;
case '5':
search_customer(head_customer);
break;
case '6':
search_cliaison(head_cliaison);
break;
case '7':
head_salesman = delete_salesman(head_salesman);
break;
case '8':
head_customer = delete_customer(head_customer);
break;
case '9':
head_cliaison = delete_cliaison(head_cliaison);
break;
case '0':break;
default:
{
printf("您的输入有误,请重新输入!\n");
system("pause");
system("cls");
}
}
if(mh1=='0')
{
system("cls");
break;
}
}
break;
case '2':
while(1)
{
system("cls");
mfunctionalinterface2();//经理客户分配界面
char mh2=getch();
switch(mh2)
{
case '1':
allocation(head_customer,head_salesman);
break;
| 2303_806435pww/tongxin_moved | main.c | C | unknown | 5,262 |
#ifndef COMMANSYSTEM_H_INCLUDED
#define COMMANSYSTEM_H_INCLUDED
#endif // COMMANSYSTEM_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#include<string.h>
#include<malloc.h>
//客户联络员
struct cliaison
{
int clcount;//联络员编号
char clname[12];//客户联络员姓名
char clsex[3];//客户联络员性别
char clbirthday[12];//客户联络员生日
char clmailbox[15];//客户联络员邮箱
int cltelcount;//电话号码数量
char cltel[10][13];//客户联络员电话号码(定义一个二维数组考虑到一个客户联络员的电话有多个)
};
struct cliaison saleclient[20];//定义一个结构数组用来表示客户联络员所负责的客户
//节点2
struct Node2
{
struct cliaison cli;//联络员
struct Node2 *pnext2;//指向下一节点的指针
};
//客户
struct client
{
int clicount;//客户编号
char cliname[12];//客户姓名
char cliarea[10];//客户所在区域
char cliaddress[30];//客户所在地址
char clilegalman[12];//客户法人
char cliscale[3];//客户规模
char cliconlevel[3];//客户联系程度
char climailbox[15];//客户邮箱
int clitelcount;//电话号码数量
char clitel[10][13];//客户电话号码(定义一个二维数组考虑到一个客户的电话有多个)
int cliordernumber;//排序数靠他来进行单一规模排序
};
//节点1
struct Node1
{
struct client cli;//客户
struct Node1* pnext1;//指向下一节点的指针
struct Node2* headcliaison[20];//联络员的头指针
int cliaison_size;//客户联络员的数量
};
//业务员
struct salesman
{
int scount;//业务员编号
char sname[12];//业务员姓名
char ssex[3];//业务员性别
char sbirthday[12];//业务员生日
char smailbocx[15];//业务员邮箱
int stelcount;//电话号码数量
char stel[10][13];//业务员电话号码
struct Node1* saleclient[20];//定义一个结构数组用来表示业务员所负责的客户
int saleclient_size; //负责的客户数量
};
//节点3
struct Node3
{
struct salesman sal;//业务员
struct Node3* pnext3;//指向下一节点的指针
};
//通信内容
struct comcontent
{
char ccompny[12];//客户公司名称
char cclname[12];//客户联络员名称
int year;
int month;
int day;
int hour;
int duration;//持续时间
char contnt[100];//通信内容文字记录
char comtype[20];//表示按什么类型排序和统计
int comcount;//统计数据
struct comcontent *next;//指向下一通信内容
};
//客户分组
struct cusgroup
{
char cusname[12];//分组名称
int size_;//表示客户数量
int _count;//分组编号
struct Node1* people[50];//组内成员
};
struct Node4
{
struct cusgroup crgroup;
struct Node4* pnext4;//客户分组链表指向下一个节点的指针
}; | 2303_806435pww/tongxin_moved | tool.h | C | unknown | 2,924 |
#include "GameArea.h"
#include <QTimerEvent>
#include <QMessageBox>
#include <QKeyEvent>
#include <QTime>
//默认游戏区域为15*20的单元格,每个单元格尺寸40*40像素
#define MAX_COLUME 15
#define MAX_ROW 20
#define RECT_WIDTH 40
#define RECT_HEIGHT 40
//默认出生点水平中心处
#define DEFAULT_X_POS (MAX_COLUME / 2 - 1)
GameArea::GameArea(QWidget *parent) : QWidget(parent)
{
mScore = 0;
mLevel = 1;
mPaused = false;
setMinimumSize(MAX_COLUME*RECT_WIDTH, MAX_ROW*RECT_HEIGHT);
}
void GameArea::NewGame()
{
mFixItems.ClearPoints();
//mCurItem 和 mNextItem 使用不同随机因子,避免初始一样
mCurItem.New(QTime::currentTime().msec());
mCurItem.MoveTo(DEFAULT_X_POS, 1);
mNextItem.New(QTime::currentTime().second());
emit sigUpdateNextItem(mNextItem.Type(), mNextItem.Direction());
mScore = 0;
mLevel = 1;
mTimerID = startTimer(GetLevelTime(mLevel));
}
void GameArea::KeyPressed(int key)
{
int x = 0;
int y = 0;
switch (key)
{
case Qt::Key_Left:
{
x = -1;
break;
}
case Qt::Key_Up:
{
mCurItem.ChangeDirection(1);
if (HitSide() || HitBottom())
{
mCurItem.ChangeDirection(-1);
}
return;
}
case Qt::Key_Right:
{
x = 1;
break;
}
case Qt::Key_Down:
{
y = 1;
break;
}
case Qt::Key_Space:
{
//空格键直接移到底部
while (1)
{
mCurItem.Move(0, 1);
if (HitSide() || HitBottom())
{
mCurItem.Move(0, -1);
break;
}
}
return;
}
case Qt::Key_Return:
case Qt::Key_Enter:
{
//暂停
mPaused = !mPaused;
break;
}
}
mCurItem.Move(x, y);
if (HitSide() || HitBottom())
{
mCurItem.Move(-x, -y);
}
}
void GameArea::paintEvent(QPaintEvent *)
{
//绘制左侧游戏区域
DrawBKRects();
DrawFixedRects();
DrawCurItem();
//如果暂停了,游戏区中间显示"暂停"大字
if(mPaused)
{
QFont font;
font.setPixelSize(100);
QPainter painter(this);
painter.setFont(font);
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen(QColor("#FF3333"), 1));
painter.drawText(rect(), Qt::AlignCenter, "暂停");
}
update();
}
void GameArea::DrawBKRects()
{
//画背景边框
QPainter painter(this);
painter.setBrush(QColor("#696969"));
painter.setPen(Qt::NoPen);
for (int i = 0; i < MAX_COLUME; i++)
{
for (int j = 0; j < MAX_ROW; j++)
{
if (i == 0 || i == MAX_COLUME - 1 || j == 0 || j == MAX_ROW - 1)
{
painter.drawRect(i*RECT_WIDTH, j*RECT_HEIGHT, RECT_WIDTH, RECT_HEIGHT);
}
}
}
}
void GameArea::DrawFixedRects()
{
QPainter painter(this);
painter.setBrush(QColor("#D3D3D3"));
painter.setPen(QPen(QColor(Qt::black), 1));
mFixItems.Draw(painter, 0, 0, RECT_WIDTH, RECT_HEIGHT);
}
void GameArea::DrawCurItem()
{
QPainter painter(this);
painter.setBrush(QColor("#FFDEAD"));
painter.setPen(QPen(QColor(Qt::black), 1));
mCurItem.Draw(painter, 0, 0, RECT_WIDTH, RECT_HEIGHT);
}
void GameArea::timerEvent(QTimerEvent* e)
{
if(mPaused)
{
return;
}
if (e->timerId() == mTimerID)
{
mCurItem.Move(0, 1);
if (HitBottom())
{
mCurItem.Move(0, -1);
AddToFixedRects();
DeleteFullRows();
if (HitTop())
{
killTimer(mTimerID);
QMessageBox::information(NULL, "GAME OVER", "GAME OVER", QMessageBox::Yes, QMessageBox::Yes);
NewGame();
return;
}
mCurItem = mNextItem;
mCurItem.MoveTo(DEFAULT_X_POS, 1);
mNextItem.New(QTime::currentTime().msec());
emit sigUpdateNextItem(mNextItem.Type(), mNextItem.Direction());
}
}
}
bool GameArea::HitSide()
{
for (QPoint p : mCurItem.Points())
{
if (p.x() <= 0 || p.x() >= MAX_COLUME - 1)
{
return true;
}
}
return false;
}
bool GameArea::HitBottom()
{
for (QPoint p : mCurItem.Points())
{
if (p.y() >= MAX_ROW - 1)
{
return true;
}
if (mFixItems.Contains(p))
{
return true;
}
}
return false;
}
bool GameArea::HitTop()
{
for (QPoint p : mFixItems.Points())
{
if (p.y() <= 1)
{
return true;
}
}
return false;
}
void GameArea::AddToFixedRects()
{
PointList points = mCurItem.Points();
mFixItems.AddPoints(points);
}
void GameArea::DeleteFullRows()
{
int nRowsDeleted = 0;
for (int i = 1; i < MAX_ROW - 1; i++)
{
int nCount = 0;
for (int j = 1; j < MAX_COLUME - 1; j++)
{
if (mFixItems.Contains(j, i))
{
nCount++;
}
}
if (nCount >= MAX_COLUME - 2)
{
mFixItems.DeleteRow(i);
mFixItems.MoveDown(i, 1); //消除行之上的内容下移一个单位
nRowsDeleted++;
}
}
//一次元素落下,最多可能消4行
//一次消除的越多,得分越多
if (nRowsDeleted == 1)
{
mScore += 100;
}
else if (nRowsDeleted == 2)
{
mScore += 300;
}
else if (nRowsDeleted == 3)
{
mScore += 500;
}
else if (nRowsDeleted == 4)
{
mScore += 700;
}
emit sigUpdateScore(mScore); //更新MainWindow界面得分
//粗略使用每1000分一关
if (mScore >= 1000 * mLevel)
{
mLevel++;
//随关卡增加下落速度,即把定时器加快
killTimer(mTimerID);
mTimerID = startTimer(GetLevelTime(mLevel));
emit sigUpdateLevel(mLevel); //更新MainWindow界面关卡
}
}
int GameArea::GetLevelTime(int level)
{
//第1关=1000ms,第2关=900ms 越来越快 第8关=300ms
//关卡>8后,速度不再增加,保持200ms
if (level > 8)
{
return 200;
}
if (level > 0)
{
return (11 - level) * 100;
}
}
| 2303_806435pww/Tetris | untitled5/GameArea.cpp | C++ | unknown | 6,690 |
#ifndef GAMEAREA_H
#define GAMEAREA_H
#include "Item.h"
#include <QWidget>
class GameArea : public QWidget
{
Q_OBJECT
public:
explicit GameArea(QWidget *parent = nullptr);
void DrawBKRects(); //背景的方块
void DrawFixedRects(); //下落后已固定不动的方块
void DrawCurItem(); //下落中的方块
void NewGame();
void KeyPressed(int key);
bool HitSide(); //判断下落方块是否超左右边界
bool HitBottom(); //判断下落方块是否达到底部
bool HitTop(); //判断下落方块是否达到顶部
void AddToFixedRects(); //把方块加入到 固定方块
void DeleteFullRows(); //删除完整的行
int GetLevelTime(int level); //获取不同等级关卡对应的定时器时间,关卡越高,时间越快(短)。比如1关=1s,2关=900ms,3关=800ms
signals:
void sigUpdateNextItem(ItemType type, ItemDirection direction);
void sigUpdateScore(int nScore);
void sigUpdateLevel(int nSpeed);
void sigPause(bool bPaused);
protected:
void paintEvent(QPaintEvent *);
void timerEvent(QTimerEvent*);
private:
Item mFixItems; //已落下、固定住了的方块们
Item mCurItem; //当前移动中的方块
Item mNextItem; //下一个方块
int mTimerID; //定时器ID
int mScore; //得分
int mLevel; //关卡
bool mPaused; //是否暂停
};
#endif
| 2303_806435pww/Tetris | untitled5/GameArea.h | C++ | unknown | 1,539 |
#include "NextArea.h"
NextArea::NextArea(QWidget *parent) : QWidget(parent)
{
}
void NextArea::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setBrush(QColor("#FFDEAD"));
painter.setPen(QPen(QColor(Qt::black), 1));
int xStart = 80; //为了绘制在显示下一个方块区域的中部
int yStart = 10;
int w = 20;
int h = 20;
for(QPoint pt : mItem.Points())
{
int x = xStart + pt.x() * w;
int y = yStart + pt.y() * h;
painter.drawRect(x, y, w, h);
}
update();
}
void NextArea::slotUpdateNextItem(ItemType type, ItemDirection direction)
{
mItem.InitPoints(type, direction);
}
| 2303_806435pww/Tetris | untitled5/NextArea.cpp | C++ | unknown | 699 |
#ifndef NEXTAREA_H
#define NEXTAREA_H
#include "item.h"
#include <QWidget>
//右侧显示下一个元素的自绘widget
class NextArea : public QWidget
{
Q_OBJECT
public:
explicit NextArea(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *);
public slots:
void slotUpdateNextItem(ItemType t, ItemDirection direction);
private:
Item mItem;
};
#endif // NEXTAREA_H
| 2303_806435pww/Tetris | untitled5/NextArea.h | C++ | unknown | 433 |
#include "about.h"
#include "ui_about.h"
about::about(QWidget *parent) :
QWidget(parent),
ui(new Ui::about)
{
ui->setupUi(this);
// 设置窗口标志,禁用最小化按钮
setWindowFlags(windowFlags() & ~Qt::WindowMinimizeButtonHint);
setFixedSize(400, 300);
}
about::~about()
{
delete ui;
}
| 2303_806435pww/Tetris | untitled5/about.cpp | C++ | unknown | 344 |
#ifndef ABOUT_H
#define ABOUT_H
#include <QWidget>
namespace Ui {
class about;
}
class about : public QWidget
{
Q_OBJECT
public:
explicit about(QWidget *parent = nullptr);
~about();
private:
Ui::about *ui;
};
#endif // ABOUT_H
| 2303_806435pww/Tetris | untitled5/about.h | C++ | unknown | 271 |
#include "gamestart.h"
#include "ui_gamestart.h"
gamestart::gamestart(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::gamestart)
{
ui->setupUi(this);
setFixedSize(1000, 800);
//widgetGameArea 和 widgetNextArea 已在界面设计器内由普通QWidget分别提升成GameArea和NextArea
//GameArea: 左侧游戏区域,自绘widget
//NextArea: 右侧显示下个item的widget,也是自绘widget
//游戏主运行逻辑在GameArea内,不过按键消息因为是MainWindow接受,通过ui->widgetGameArea->KeyPressed()函数调用传递下去
//GameArea通过信号sigUpdateScore、sigUpdateLevel 通知MainWindow更新界面的得分和关卡
//GameArea通过信号sigUpdateNextItem 通知 NextArea 刷新下一个元素
connect(ui->widgetGameArea, &GameArea::sigUpdateScore, this, &gamestart::slotUpdateScore);
connect(ui->widgetGameArea, &GameArea::sigUpdateLevel, this, &gamestart::slotUpdateLevel);
connect(ui->widgetGameArea, &GameArea::sigUpdateNextItem, ui->widgetNextArea, &NextArea::slotUpdateNextItem);
ui->widgetGameArea->NewGame();
}
gamestart::~gamestart()
{
delete ui;
}
void gamestart::keyPressEvent(QKeyEvent *e)
{
ui->widgetGameArea->KeyPressed(e->key());
QMainWindow::keyPressEvent(e);
}
void gamestart::slotUpdateScore(int nScore)
{
ui->labelScore->setText(QString::number(nScore));
}
void gamestart::slotUpdateLevel(int nSpeed)
{
ui->labelSpeed->setText(QString::number(nSpeed));
}
void gamestart::openWindow()
{
gamestart *startWindow = new gamestart;
startWindow->show();
}
| 2303_806435pww/Tetris | untitled5/gamestart.cpp | C++ | unknown | 1,630 |
#ifndef GAMESTART_H
#define GAMESTART_H
#include <QKeyEvent>
#include <QMainWindow>
namespace Ui {
class gamestart;
}
class gamestart : public QMainWindow
{
Q_OBJECT
public:
explicit gamestart(QWidget *parent = nullptr);
~gamestart();
protected:
void keyPressEvent(QKeyEvent *e);
public slots:
void slotUpdateScore(int nScore);
void slotUpdateLevel(int nSpeed);
void openWindow();
private:
Ui::gamestart *ui;
};
#endif
| 2303_806435pww/Tetris | untitled5/gamestart.h | C++ | unknown | 496 |
#include "Item.h"
#include <QTime>
Item::Item(ItemType type, ItemDirection directon)
{
mPosition = QPoint(0, 0);
InitPoints(type, directon);
}
Item::~Item()
{
}
ItemType Item::Type()
{
return mType;
}
ItemDirection Item::Direction()
{
return mDirection;
}
PointList Item::Points()
{
return mPoints;
}
void Item::New(int nRandomFactor)
{
//设置随机因子
qsrand(nRandomFactor);
//随机初始化元素类型、方向
ItemType type = (ItemType)(qrand() % ItemType_MAX);
ItemDirection direction = (ItemDirection)(qrand() % ItemDirection_MAX);
InitPoints(type, direction);
}
void Item::InitPoints(ItemType type, ItemDirection direction)
{
//根据元素的类型、方向,初始化对应形状的4个坐标点(在4*4的矩阵中)
//这里先以4行文本描述坐标点位置,然后再翻译成QPoint列表
QString text = GetPointPostionText(type, direction);
PointList points = TextToPointList(text);
mPoints.clear();
for (QPoint pt : points)
{
//真实坐标需要加上起始位置mPos
mPoints.append(mPosition + pt);
}
mType = type;
mDirection = direction;
}
QString Item::GetPointPostionText(ItemType type, ItemDirection direction)
{
QString text;
switch (type)
{
case ItemType_Line:
{
if (direction == ItemDirection_Up || direction == ItemDirection_Down)
{
//直线型元素第1、3种方向(横向)的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 0 0 0/") +
QString("1 1 1 1/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Left || direction == ItemDirection_Right)
{
//直线型元素第2、4种方向(竖向)的坐标点位如下:
text =
QString("0 0 1 0/") +
QString("0 0 1 0/") +
QString("0 0 1 0/") +
QString("0 0 1 0/");
}
break;
}
case ItemType_T:
{
if (direction == ItemDirection_Up)
{
//T型元素第1种方向的坐标点位如下:
text =
QString("0 1 0 0/") +
QString("1 1 1 0/") +
QString("0 0 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Right)
{
//T型元素第2种方向的坐标点位如下:
text =
QString("0 1 0 0/") +
QString("0 1 1 0/") +
QString("0 1 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Down)
{
//T型元素第3种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("1 1 1 0/") +
QString("0 1 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Left)
{
//T型元素第4种方向的坐标点位如下:
text =
QString("0 1 0 0/") +
QString("1 1 0 0/") +
QString("0 1 0 0/") +
QString("0 0 0 0/");
}
break;
}
case ItemType_L1:
{
if (direction == ItemDirection_Up)
{
//L1型元素第1种方向的坐标点位如下:
text =
QString("0 1 0 0/") +
QString("0 1 0 0/") +
QString("0 1 1 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Right)
{
//L1型元素第2种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 1 1 1/") +
QString("0 1 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Down)
{
//L1型元素第3种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 1 1 0/") +
QString("0 0 1 0/") +
QString("0 0 1 0/");
}
else if (direction == ItemDirection_Left)
{
//L1型元素第4种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 0 1 0/") +
QString("1 1 1 0/") +
QString("0 0 0 0/");
}
break;
}
case ItemType_L2:
{
if (direction == ItemDirection_Up)
{
//L2型元素第1种方向的坐标点位如下:
text =
QString("0 0 1 0/") +
QString("0 0 1 0/") +
QString("0 1 1 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Right)
{
//L2型元素第2种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 1 0 0/") +
QString("0 1 1 1/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Down)
{
//L2型元素第3种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 1 1 0/") +
QString("0 1 0 0/") +
QString("0 1 0 0/");
}
else if (direction == ItemDirection_Left)
{
//L2型元素第4种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("1 1 1 0/") +
QString("0 0 1 0/") +
QString("0 0 0 0/");
}
break;
}
case ItemType_Square:
{
//田字型元素只有一种坐标:
text =
QString("1 1 0 0/") +
QString("1 1 0 0/") +
QString("0 0 0 0/") +
QString("0 0 0 0/");
break;
}
case ItemType_Z:
{
if (direction == ItemDirection_Up)
{
//Z型元素第1种方向的坐标点位如下:
text =
QString("0 1 0 0/") +
QString("0 1 1 0/") +
QString("0 0 1 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Right)
{
//Z型元素第2种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("0 1 1 0/") +
QString("1 1 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Down)
{
//Z型元素第3种方向的坐标点位如下:
text =
QString("0 0 1 0/") +
QString("0 1 1 0/") +
QString("0 1 0 0/") +
QString("0 0 0 0/");
}
else if (direction == ItemDirection_Left)
{
//Z型元素第4种方向的坐标点位如下:
text =
QString("0 0 0 0/") +
QString("1 1 0 0/") +
QString("0 1 1 0/") +
QString("0 0 0 0/");
}
break;
}
default:
break;
}
return text;
}
void Item::ClearPoints()
{
mPoints.clear();
}
void Item::ChangeDirection(int nDirection)
{
ItemDirection newDirection = (ItemDirection)((mDirection + nDirection) % ItemDirection_MAX);
InitPoints(mType, newDirection);
}
void Item::Draw(QPainter& painter, int nStartX, int nStartY, int nWidth, int nHeight)
{
for (int i = 0; i < mPoints.size(); i++)
{
QPoint pt = mPoints[i];
painter.drawRect(QRect(nStartX + pt.x() * nWidth, nStartY + pt.y() * nHeight, nWidth, nHeight));
}
}
void Item::AddPoints(const PointList& points)
{
for (int i = 0; i < points.size(); i++)
{
if (!mPoints.contains(points[i]))
{
mPoints.append(points[i]);
}
}
}
bool Item::Contains(QPoint& point)
{
return mPoints.contains(point);
}
bool Item::Contains(int x, int y)
{
QPoint point(x, y);
return mPoints.contains(point);
}
void Item::Move(int x, int y)
{
for (int i = 0; i < mPoints.size(); i++)
{
int x1 = mPoints[i].x() + x;
int y1 = mPoints[i].y() + y;
mPoints[i].setX(x1);
mPoints[i].setY(y1);
}
mPosition += QPoint(x, y);
}
void Item::MoveTo(int x, int y)
{
for (int i = 0; i < mPoints.size(); i++)
{
int x1 = mPoints[i].x() - mPosition.x() + x;
int y1 = mPoints[i].y() - mPosition.y() + y;
mPoints[i].setX(x1);
mPoints[i].setY(y1);
}
mPosition = QPoint(x, y);
}
void Item::DeleteRow(int y)
{
PointList newPoints;
for (int i = 0; i < mPoints.size(); i++)
{
if (mPoints[i].y() != y)
{
newPoints.append(mPoints[i]);
}
}
mPoints = newPoints;
}
PointList Item::TextToPointList(QString strFormat)
{
PointList points;
QStringList rows = strFormat.split('/'); //先以斜杠拆分为4行
for (int i = 0; i < rows.size(); i++)
{
QString strRowText = rows.at(i);
QStringList columns = strRowText.split(' '); //每行内容又以空格拆分为4列
for (int j = 0; j < columns.size(); j++)
{
if (columns.at(j) == "1")
{
points.append(QPoint(i, j));
}
}
}
return points;
}
void Item::MoveDown(int nRow, int y)
{
for (int i = 0; i < mPoints.size(); i++)
{
if (mPoints[i].y() < nRow)
{
mPoints[i].setY(mPoints[i].y() + y);
}
}
}
| 2303_806435pww/Tetris | untitled5/item.cpp | C++ | unknown | 10,163 |
#pragma once
#include <QList>
#include <QPoint>
#include <QMap>
#include <QPainter>
#include <QString>
//元素有6种类型
enum ItemType {
ItemType_Line = 0, //直线形
ItemType_T, //T形
ItemType_L1, //L形1
ItemType_L2, //L形2
ItemType_Square, //正方形、田字形
ItemType_Z, //Z形
ItemType_MAX,
};
//每种类型的元素都有上下左右4种朝向,一般每种朝向是一个不同形状
//长条元素一共只有2个形状
//田字元素一共只有1个形状
enum ItemDirection {
ItemDirection_Up = 0,
ItemDirection_Right,
ItemDirection_Down,
ItemDirection_Left,
ItemDirection_MAX, //方向总数4
};
typedef QList<QPoint> PointList;
class Item
{
public:
Item() {}
Item(ItemType type, ItemDirection direction);
~Item();
ItemType Type();
ItemDirection Direction();
PointList Points();
void New(int nRandomFactor); //随机生成新元素,nRandomFactor随机因子
void InitPoints(ItemType type, ItemDirection direction); //根据元素类型、方向,初始化4个坐标点
void ClearPoints();
void AddPoints(const PointList& points);
bool Contains(QPoint& point);
bool Contains(int x, int y);
void ChangeDirection(int nDirection); //传1就把方向状态+1,代表旋转90度
void Move(int x, int y); //横向移动x格,竖向移动y格
void MoveTo(int x, int y); //移动到位置(x,y)格
void MoveDown(int nRow, int y); //第nRow行以上的部分下移y个单位,用在消除之后
void DeleteRow(int y);
void Draw(QPainter& painter, int nStartX, int nStartY, int nWidth, int nHeight);
private:
QString GetPointPostionText(ItemType type, ItemDirection direction);
//将坐标位置的描述文本,转换为坐标点
PointList TextToPointList(QString strFormat);
private:
ItemType mType; //元素类型(6种)
ItemDirection mDirection; //每种类型又有4种方向
QPoint mPosition; //元素当前的位置
PointList mPoints; //元素内4个坐标点,每个点代表一个格子坐标
};
| 2303_806435pww/Tetris | untitled5/item.h | C++ | unknown | 2,188 |
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationName("俄罗斯方块");//设置应用程序名
a.setWindowIcon(QIcon("qrc:/PNG/buttonSquare_beige_pressed.png"));//设置应用程序图标
MainWindow w;
w.show();
return a.exec();
}
| 2303_806435pww/Tetris | untitled5/main.cpp | C++ | unknown | 352 |
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "about.h"
#include "option.h"
#include "gamestart.h"
#include <QDesktopWidget>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setFixedSize(1000, 800);
about=new class about();
option=new class option();
//gamestart=new class gamestart();
connect(ui->pushButton_3, &QPushButton::clicked, this, [this](){ openWindow(about); });
connect(ui->pushButton_2, &QPushButton::clicked, this, [this](){ openWindow(option); });
connect(ui->pushButton, &QPushButton::clicked, this, [this]() {
class gamestart *startWindow = new class gamestart;
startWindow->show();
});
}
void MainWindow::openWindow(QWidget *window)
{
window->setWindowModality(Qt::ApplicationModal);
QRect screenGeometry = QApplication::desktop()->screenGeometry();
int x = (screenGeometry.width() - window->width()) / 2;
int y = (screenGeometry.height() - window->height()) / 2;
window->setGeometry(x, y, window->width(), window->height());
window->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
| 2303_806435pww/Tetris | untitled5/mainwindow.cpp | C++ | unknown | 1,190 |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <about.h>
#include <option.h>
#include <gamestart.h>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void openWindow(QWidget *window);
private:
Ui::MainWindow *ui;
class about *about;
class option *option;
class gamestart *gamestart;
};
#endif // MAINWINDOW_H
| 2303_806435pww/Tetris | untitled5/mainwindow.h | C++ | unknown | 548 |
#include "option.h"
#include "ui_option.h"
#include <QMediaPlayer>
option::option(QWidget *parent) :
QWidget(parent),
ui(new Ui::option)
{
ui->setupUi(this);
player = new QMediaPlayer(this);
player->setMedia(QUrl("qrc:/rescoures/ssb.mp3"));
// 设置窗口标志,禁用最小化按钮
setWindowFlags(windowFlags() & ~Qt::WindowMinimizeButtonHint);
setFixedSize(400, 300);
// 初始状态:水平滑块不启用
//ui->horizontalSlider->setEnabled(false);
// 连接复选框的状态更改信号到 music 函数
connect(ui->checkBox, &QCheckBox::stateChanged, this, &option::music);
// 连接水平滑块的值更改信号到 music_volume 函数
connect(ui->horizontalSlider, &QSlider::valueChanged, this, &option::music_volume);
}
void option::music(int state)
{
if(state == Qt::Checked)
{
// 播放音乐
player->play();
// 当复选框被选中时启用option类中的水平滑块
ui->horizontalSlider->setEnabled(true);
}
else
{
if(player)
{
// 当复选框未被选中时禁用option类中的水平滑块
ui->horizontalSlider->setEnabled(false);
// 暂停音乐播放
player->pause();
}
}
}
void option::music_volume(int volume)
{
ui->horizontalSlider->setMinimum(0);
ui->horizontalSlider->setMaximum(100);
ui->label_4->setText(QString::number(volume) + "%");
if (player != nullptr) {
player->setVolume(volume);
}
}
option::~option()
{
delete ui;
}
| 2303_806435pww/Tetris | untitled5/option.cpp | C++ | unknown | 1,640 |
#ifndef OPTION_H
#define OPTION_H
#include <QWidget>
#include <QSlider>
#include <QLabel>
#include <QMediaPlayer>
#include <QCheckBox>
namespace Ui {
class option;
}
class option : public QWidget
{
Q_OBJECT
public:
explicit option(QWidget *parent = nullptr);
~option();
QSlider *horizontalSlider;
QLabel *label_4;
private slots:
void music(int state);
void music_volume(int volume);
private:
Ui::option *ui;
QMediaPlayer *player;
//QCheckBox *checkbox;
};
#endif // OPTION_H
| 2303_806435pww/Tetris | untitled5/option.h | C++ | unknown | 550 |
QT += core gui \
quick
QT += multimedia
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
GameArea.cpp \
Item.cpp \
NextArea.cpp \
about.cpp \
gamestart.cpp \
main.cpp \
mainwindow.cpp \
option.cpp
HEADERS += \
GameArea.h \
Item.h \
NextArea.h \
about.h \
gamestart.h \
mainwindow.h \
option.h
FORMS += \
about.ui \
gamestart.ui \
mainwindow.ui \
option.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
RESOURCES += \
re.qrc
| 2303_806435pww/Tetris | untitled5/untitled5.pro | QMake | unknown | 1,347 |
package fun.xingwangzhe.tryfishport.client;
import com.google.gson.Gson;
import net.minidev.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CaptchaService {
public static class CaptchaResult {
private final String captcha;
private final String captchaToken;
public CaptchaResult(String captcha, String captchaToken) {
this.captcha = captcha;
this.captchaToken = captchaToken;
}
// 添加关闭方法以正确关闭线程池
public static void shutdown() {
executorService.shutdown();
}
public String getCaptcha() {
return captcha;
}
public String getCaptchaToken() {
return captchaToken;
}
}
// 创建一个固定大小的线程池,避免创建过多线程
private static final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
public CompletableFuture<CaptchaResult> calculateCaptchaAsync() {
return CompletableFuture.supplyAsync(() -> {
try {
return calculateCaptcha();
} catch (Exception e) {
throw new RuntimeException(e);
}
}, executorService);
}
public CaptchaResult calculateCaptcha() throws Exception {
// 直接GET
URL url = new URI("https://ip-unban.fishport.net/captcha-challenge").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
Gson gson = new Gson();
JSONObject jsonObject = gson.fromJson(response.toString().trim(), JSONObject.class);
String captchaText = (String) jsonObject.get("captcha_token");
// 尝试解析验证码
try {
// hash计算
if (captchaText == null || captchaText.isEmpty()) {
throw new NumberFormatException("Captcha token is empty or null");
}
// 解析JWT格式的token
String[] parts = captchaText.split("\\.");
if (parts.length != 3) {
throw new NumberFormatException("Invalid JWT format");
}
String payload = parts[1];
// Base64解码
byte[] decodedBytes = java.util.Base64.getUrlDecoder().decode(payload);
String decodedPayload = new String(decodedBytes, StandardCharsets.UTF_8);
// 解析JSON
Gson gson2 = new Gson();
JSONObject payloadJson = gson2.fromJson(decodedPayload, JSONObject.class);
String prefix = (String) payloadJson.get("prefix");
String target = (String) payloadJson.get("target");
if (prefix == null || target == null) {
throw new NumberFormatException("Prefix or target is null");
}
// 计算验证码
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int matchLength = target.length();
int suffixLength = matchLength <= 4 ? 3 : (matchLength <= 6 ? 4 : 5);
long total = (long) Math.pow(letters.length(), suffixLength);
long count = 0;
boolean[] found = {false};
java.util.concurrent.atomic.AtomicReference<String> result = new java.util.concurrent.atomic.AtomicReference<>("");
// 使用CompletableFuture和线程池替代直接创建线程
final int batchSize = 1000;
for (long batchStart = 0; batchStart < total && !found[0]; batchStart += batchSize) {
List<CompletableFuture<Void>> tasks = new ArrayList<>();
for (long i = batchStart; i < Math.min(batchStart + batchSize, total) && !found[0]; i++) {
long index = i;
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> {
StringBuilder suffix = new StringBuilder();
long num = index;
for (int p = 0; p < suffixLength; p++) {
suffix.insert(0, letters.charAt((int) (num % letters.length())));
num /= letters.length();
}
String candidate = prefix + suffix;
String hash = utilsSha256(candidate);
if (hash.substring(0, matchLength).equals(target)) {
result.set(suffix.toString());
found[0] = true;
}
}, executorService);
tasks.add(task);
count++;
}
// 等待批次完成
CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
}
if (!found[0]) {
throw new NumberFormatException("Captcha calculation failed, no match found");
}
if (result.get() != null && !result.get().isEmpty()) {
return new CaptchaResult(result.get(), captchaText);
} else {
throw new NumberFormatException("Captcha result is empty");
}
} catch (NumberFormatException e) {
throw new Exception("Captcha calculation failed: " + e.getMessage(), e);
}
} else {
throw new Exception("Failed to fetch captcha with code: " + responseCode);
}
}
private String utilsSha256(String input) {
try {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (java.security.NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/CaptchaService.java | Java | mit | 7,404 |
package fun.xingwangzhe.tryfishport.client;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;
public class DNSResolver {
/**
* 解析主机名到IP地址
*
* @param host 主机名
* @return 解析后的IP地址或原始主机名
*/
public static String resolveToIp(String host) {
try {
String targetHost = host;
// 尝试 SRV 查询
try {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns:");
Attributes attrs = new InitialDirContext(env)
.getAttributes("_minecraft._tcp." + host, new String[]{"SRV"});
Attribute attr = attrs.get("SRV");
if (attr != null && attr.size() > 0) {
String[] parts = attr.get(0).toString().split(" ", 4);
targetHost = parts[3].endsWith(".") ? parts[3].substring(0, parts[3].length() - 1) : parts[3];
}
} catch (Exception ignored) {
}
// 查 A/AAAA 记录
return targetHost;
} catch (Exception e) {
return host; // 出错返回原 host
}
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/DNSResolver.java | Java | mit | 1,438 |
package fun.xingwangzhe.tryfishport.client;
import com.google.gson.Gson;
import net.minidev.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class IPAddressService {
private String ipAddress = "";
private boolean isIPv6 = false;
private String ipv4Token = "";
public void fetchIPAddress() throws Exception {
tryGetIPFromService();
}
private void tryGetIPFromService() throws Exception {
try {
URL url = new URI("https://ip-unban.fishport.net/check").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String ip = response.toString().trim();
// 对于返回JSON格式的API (如httpbin.org)
if (ip.startsWith("{")) {
// 解析JSON格式到HashMap
Gson gson = new Gson();
JSONObject jsonObject = gson.fromJson(ip, JSONObject.class);
if ((boolean) jsonObject.get("ipv6only")) {
// check pp.ua
String jws = fetchIPv4Token();
if (jws != null && !jws.isEmpty()) {
// 报错
throw new Exception("Failed to get IPv4 token");
}
Gson jwtGson = new Gson();
JSONObject jwtObject = jwtGson.fromJson(jws, JSONObject.class);
// 获取IP地址
if (jwtObject == null || !jwtObject.containsKey("ip")) {
throw new Exception("Invalid JWT token");
}
ip = (String) jwtObject.get("ip");
isIPv6 = false;
ipv4Token = (String) jwtObject.get("jws");
} else {
// 获取IP地址
ip = (String) jsonObject.get("ip");
}
}
// 验证IP地址格式
if (isValidIPAddress(ip)) {
ipAddress = ip;
isIPv6 = ip.contains(":") && !ip.contains(".");
}
}
} catch (Exception e) {
// 忽略单个服务的错误,继续尝试其他服务
System.out.println("Failed to get IP from https://ip-unban.fishport.net/check: " + e.getMessage());
throw e;
}
}
private String fetchIPv4Token() {
try {
URL tokenUrl = URI.create("https://ip.fishport.pp.ua/").toURL();
HttpURLConnection tokenConn = (HttpURLConnection) tokenUrl.openConnection();
tokenConn.setRequestMethod("GET");
tokenConn.setConnectTimeout(5000);
tokenConn.setReadTimeout(5000);
int tokenCode = tokenConn.getResponseCode();
if (tokenCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(tokenConn.getInputStream()));
StringBuilder resp = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
resp.append(line);
}
reader.close();
return resp.toString();
}
} catch (Exception e) {
System.out.println("IPv6 token/jwt处理失败: " + e.getMessage());
}
return null;
}
private boolean isValidIPAddress(String ip) {
if (ip == null || ip.isEmpty()) return false;
// 更严格的IPv6校验:8组16进制数,每组1-4位,用:分隔,允许::简写
if (ip.contains(":")) {
String ipv6Pattern = "^(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^:(:[0-9a-fA-F]{1,4}){1,7}$|^(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}$|^(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}$|^(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}$|^[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}$|^::$";
return ip.matches(ipv6Pattern);
}
// IPv4校验
String ipv4Pattern = "^((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)$";
return ip.matches(ipv4Pattern);
}
// Getters
public String getIpAddress() {
return ipAddress;
}
public boolean isIPv6() {
return isIPv6;
}
public String getIpv4Token() {
return ipv4Token;
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/IPAddressService.java | Java | mit | 5,331 |
package fun.xingwangzhe.tryfishport.client;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.network.ServerAddress;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class PingUI extends Screen {
private final ServerInfo serverInfo;
private final MultiplayerScreen parent; // 添加父级屏幕引用
private volatile String pingResult = Text.translatable("tryfishport.ui.ping.status.getting_route_info").getString();
private final AtomicBoolean isPinging = new AtomicBoolean(false);
private final StringBuilder traceOutputBuffer = new StringBuilder();
// 创建专用的线程池用于traceroute操作
private static final ExecutorService traceExecutor = Executors.newFixedThreadPool(2);
public PingUI(MultiplayerScreen parent, ServerInfo serverInfo) {
super(Text.translatable("tryfishport.ui.ping.title"));
this.parent = parent;
this.serverInfo = serverInfo;
System.out.println(Text.translatable("tryfishport.log.pingui.init").getString() + serverInfo.name);
System.out.println(Text.translatable("tryfishport.log.serverinfo.details").getString() + serverInfo.name + Text.translatable("tryfishport.log.serverinfo.address").getString() + serverInfo.address + Text.translatable("tryfishport.log.serverinfo.version").getString() + (serverInfo.version != null ? serverInfo.version.getString() : "null"));
}
@Override
protected void init() {
System.out.println(Text.translatable("tryfishport.log.pingui.init").getString() + serverInfo.name);
System.out.println(Text.translatable("tryfishport.log.serverinfo.details").getString() + serverInfo.name + Text.translatable("tryfishport.log.serverinfo.address").getString() + serverInfo.address + Text.translatable("tryfishport.log.serverinfo.version").getString() + (serverInfo.version != null ? serverInfo.version.getString() : "null"));
// 添加重试按钮
this.addDrawableChild(ButtonWidget.builder(Text.translatable("tryfishport.ui.ping.button.retry"), button -> {
System.out.println(Text.translatable("tryfishport.log.button.retry").getString() + serverInfo.name);
System.out.println(Text.translatable("tryfishport.log.serverinfo.details").getString() + serverInfo.name + Text.translatable("tryfishport.log.serverinfo.address").getString() + serverInfo.address + Text.translatable("tryfishport.log.serverinfo.version").getString() + (serverInfo.version != null ? serverInfo.version.getString() : "null"));
traceRoute();
})
.dimensions(this.width / 2 - 105, this.height - 30, 100, 20)
.build());
this.addDrawableChild(ButtonWidget.builder(Text.translatable("tryfishport.ui.ping.button.copy_result"), button -> {
System.out.println(Text.translatable("tryfishport.log.button.copy").getString() + serverInfo.name);
System.out.println(Text.translatable("tryfishport.log.copying.result").getString() + pingResult);
MinecraftClient.getInstance().keyboard.setClipboard(pingResult);
})
.dimensions(this.width / 2 + 5, this.height - 30, 100, 20)
.build());
// 添加关闭按钮
this.addDrawableChild(ButtonWidget.builder(Text.translatable("tryfishport.ui.ping.button.close"), button -> close())
.dimensions(this.width / 2 - 50, this.height - 60, 100, 20)
.build());
// 初始traceroute
traceRoute();
}
@Override
public boolean shouldPause() {
return false; // 不暂停游戏
}
@Override
public void close() {
// 关闭时直接返回到服务器列表页面
MinecraftClient.getInstance().setScreen(parent);
}
@Override
public void resize(MinecraftClient client, int width, int height) {
super.resize(client, width, height);
}
private void traceRoute() {
if (isPinging.get()) {
System.out.println(Text.translatable("tryfishport.log.tracing.ignored").getString());
return;
}
isPinging.set(true);
pingResult = Text.translatable("tryfishport.ui.ping.status.getting_route_info").getString();
var serverHost = DNSResolver.resolveToIp(serverInfo.address);
if (serverHost.contains(":")) {
// 如果地址包含端口号,分离出主机名和端口
String[] parts = serverHost.split(":");
serverHost = parts[0];
}
System.out.println(Text.translatable("tryfishport.log.tracing.start").getString() + serverInfo.address);
System.out.println(Text.translatable("tryfishport.log.serverinfo.details").getString() + serverInfo.name + Text.translatable("tryfishport.log.serverinfo.address").getString() + serverInfo.address + Text.translatable("tryfishport.log.serverinfo.version").getString() + (serverInfo.version != null ? serverInfo.version.getString() : "null"));
traceOutputBuffer.setLength(0); // 清空缓冲区
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.status.getting_route_info").getString()).append("\n");
updatePingResult();
System.out.println(Text.translatable("tryfishport.log.parsing.address").getString() + serverInfo.address);
ServerAddress address = ServerAddress.parse(serverInfo.address);
String host = address.getAddress();
System.out.println(Text.translatable("tryfishport.log.parsed.host").getString() + host);
// 执行traceroute命令
System.out.println(Text.translatable("tryfishport.log.traceroute.start").getString());
String finalServerHost = serverHost;
// 使用线程池执行traceroute,避免阻塞
CompletableFuture.runAsync(() -> {
try {
executeTraceRouteCommand(String.valueOf(finalServerHost));
} catch (Exception e) {
System.out.println(Text.translatable("tryfishport.log.exception.traceroute").getString() + e.getMessage());
e.printStackTrace();
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.error.route_trace").getString()).append(e.getMessage()).append("\n");
updatePingResult();
} finally {
isPinging.set(false);
System.out.println(Text.translatable("tryfishport.log.traceroute.finish").getString() + serverInfo.address);
System.out.println(Text.translatable("tryfishport.log.serverinfo.details").getString() + serverInfo.name + Text.translatable("tryfishport.log.serverinfo.address").getString() + serverInfo.address + Text.translatable("tryfishport.log.serverinfo.version").getString() + (serverInfo.version != null ? serverInfo.version.getString() : "null"));
}
}, traceExecutor);
}
/**
* 根据操作系统执行相应的路由追踪命令
*
* @param host 要traceroute的主机名或IP地址
*/
private void executeTraceRouteCommand(String host) {
try {
String os = System.getProperty("os.name").toLowerCase();
String[] command;
String friendlyName;
System.out.println("Operating system: " + os);
// 根据操作系统选择合适的路由追踪命令
if (os.contains("win")) {
// Windows系统: tracert host (系统自带)
command = new String[]{"cmd.exe", "/c", "tracert", "-d", host};
friendlyName = "tracert";
System.out.println("Using Windows tracert command (built-in)");
} else if (os.contains("mac") || os.contains("darwin")) {
// Mac系统: traceroute host (系统自带)
command = new String[]{"traceroute", host};
friendlyName = "traceroute";
System.out.println("Using Mac traceroute command (built-in)");
} else {
// Linux系统: 尝试多种方式
command = new String[]{"traceroute", host};
friendlyName = "traceroute";
System.out.println("Using Linux traceroute command");
}
System.out.println("Executing route trace command: " + String.join(" ", command));
// 尝试执行命令
try {
Process process = Runtime.getRuntime().exec(command);
// 读取命令输出
java.io.BufferedReader reader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
traceOutputBuffer.append(line).append("\n");
System.out.println("Route trace output line: " + line);
updatePingResult(); // 实时更新结果
}
// 读取错误输出
java.io.BufferedReader errorReader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getErrorStream()));
StringBuilder errorOutput = new StringBuilder();
while ((line = errorReader.readLine()) != null) {
errorOutput.append(line).append("\n");
System.out.println("Route trace error line: " + line);
}
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Route trace command exited with code: " + exitCode);
// 如果有错误输出,也包含在结果中
if (!errorOutput.isEmpty()) {
// 检查是否是因为命令不存在导致的错误
String errorStr = errorOutput.toString().toLowerCase();
if (errorStr.contains("not found") || errorStr.contains("not recognized") ||
errorStr.contains("No such file or directory".toLowerCase()) ||
errorStr.contains("command not found")) {
traceOutputBuffer.append(getCommandNotFoundMessage(friendlyName, os));
} else {
traceOutputBuffer.append("\n").append(Text.translatable("tryfishport.ui.ping.system.error_info").getString()).append(errorOutput);
}
}
// 如果输出为空但退出码为0,可能是命令执行了但没有输出
if (traceOutputBuffer.isEmpty() && exitCode == 0) {
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.no_output").getString());
}
updatePingResult(); // 最终更新结果
} catch (IOException e) {
System.out.println("IOException when executing command: " + e.getMessage());
// 如果命令不存在或无法执行
if (e.getMessage().contains("Cannot run program") ||
e.getMessage().contains("error=2") ||
e.getMessage().contains("No such file or directory")) {
traceOutputBuffer.append(getCommandNotFoundMessage(friendlyName, os));
} else {
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.error").getString()).append(e.getMessage());
}
updatePingResult();
throw e; // 重新抛出其他IO异常
}
} catch (Exception e) {
System.out.println(Text.translatable("tryfishport.log.exception.traceroute").getString() + e.getMessage());
e.printStackTrace();
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.error").getString()).append(e.getMessage()).append("\n");
updatePingResult();
}
}
/**
* 更新界面显示结果
*/
private void updatePingResult() {
// 在主线程中更新UI
MinecraftClient.getInstance().execute(() -> {
pingResult = traceOutputBuffer.toString();
System.out.println("Updating UI with current result");
});
}
/**
* 获取命令未找到时的友好提示信息
*
* @param command 命令名称
* @param os 操作系统名称
* @return 友好的错误提示信息
*/
private String getCommandNotFoundMessage(String command, String os) {
StringBuilder message = new StringBuilder();
message.append(Text.translatable("tryfishport.ui.ping.error.command_not_found").getString()).append(command).append("\n\n");
if (os.contains("win")) {
message.append(Text.translatable("tryfishport.ui.ping.system.windows.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line3").getString()).append("\n");
} else if (os.contains("mac") || os.contains("darwin")) {
message.append(Text.translatable("tryfishport.ui.ping.system.mac.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line3").getString()).append("\n");
} else {
message.append(Text.translatable("tryfishport.ui.ping.system.linux.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line3").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line4").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line5").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line6").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line7").getString()).append("\n");
}
message.append(Text.translatable("tryfishport.ui.ping.system.tip").getString());
if (os.contains("win")) {
message.append(" tracert ").append(ServerAddress.parse(serverInfo.address).getAddress());
} else {
message.append(" traceroute ").append(ServerAddress.parse(serverInfo.address).getAddress());
}
return message.toString();
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
// 首先调用父类的render方法来渲染背景和控件
super.render(context, mouseX, mouseY, delta);
// 绘制标题文本在屏幕顶部中央
context.drawCenteredTextWithShadow(this.textRenderer, this.title, this.width / 2, 15, 0xFFFFFF);
// 绘制服务器信息在左上角区域
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.ping.server.name").getString() + serverInfo.name, 10, 35, 0xFFFFFF);
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.ping.server.address").getString() + serverInfo.address, 10, 50, 0xFFFFFF);
// 绘制结果信息 - 支持多行显示
String[] lines = pingResult.split("\n");
for (int i = 0; i < lines.length && i < 20; i++) { // 限制显示20行
context.drawTextWithShadow(this.textRenderer, lines[i], 10, 70 + i * 10, 0xFFFFFF);
}
// 添加调试信息
// System.out.println("Render method called");
}
// 添加资源清理方法
public static void shutdown() {
traceExecutor.shutdown();
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/PingUI.java | Java | mit | 17,044 |
package fun.xingwangzhe.tryfishport.client;
import net.minecraft.client.network.ServerAddress;
import net.minecraft.text.Text;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RouteTracer {
private final StringBuilder traceOutputBuffer = new StringBuilder();
private String serverInfoAddress;
private String serverInfoName;
// 创建专用的线程池用于traceroute操作
private static final ExecutorService traceExecutor = Executors.newFixedThreadPool(2);
public RouteTracer(String serverInfoAddress, String serverInfoName) {
this.serverInfoAddress = serverInfoAddress;
this.serverInfoName = serverInfoName;
}
/**
* 根据操作系统执行相应的路由追踪命令
*
* @param host 要traceroute的主机名或IP地址
*/
public CompletableFuture<Void> executeTraceRouteCommandAsync(String host) {
return CompletableFuture.runAsync(() -> executeTraceRouteCommand(host), traceExecutor);
}
public void executeTraceRouteCommand(String host) {
try {
String os = System.getProperty("os.name").toLowerCase();
String[] command;
String friendlyName;
System.out.println("Operating system: " + os);
// 根据操作系统选择合适的路由追踪命令
if (os.contains("win")) {
// Windows系统: tracert host (系统自带)
command = new String[]{"cmd.exe", "/c", "tracert", "-d", host};
friendlyName = "tracert";
System.out.println("Using Windows tracert command (built-in)");
} else if (os.contains("mac") || os.contains("darwin")) {
// Mac系统: traceroute host (系统自带)
command = new String[]{"traceroute", host};
friendlyName = "traceroute";
System.out.println("Using Mac traceroute command (built-in)");
} else {
// Linux系统: 尝试多种方式
command = new String[]{"traceroute", host};
friendlyName = "traceroute";
System.out.println("Using Linux traceroute command");
}
System.out.println("Executing route trace command: " + String.join(" ", command));
// 尝试执行命令
try {
Process process = Runtime.getRuntime().exec(command);
// 读取命令输出
java.io.BufferedReader reader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
traceOutputBuffer.append(line).append("\n");
System.out.println("Route trace output line: " + line);
}
// 读取错误输出
java.io.BufferedReader errorReader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getErrorStream()));
StringBuilder errorOutput = new StringBuilder();
while ((line = errorReader.readLine()) != null) {
errorOutput.append(line).append("\n");
System.out.println("Route trace error line: " + line);
}
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Route trace command exited with code: " + exitCode);
// 如果有错误输出,也包含在结果中
if (!errorOutput.isEmpty()) {
// 检查是否是因为命令不存在导致的错误
String errorStr = errorOutput.toString().toLowerCase();
if (errorStr.contains("not found") || errorStr.contains("not recognized") ||
errorStr.contains("No such file or directory".toLowerCase()) ||
errorStr.contains("command not found")) {
traceOutputBuffer.append(getCommandNotFoundMessage(friendlyName, os));
} else {
traceOutputBuffer.append("\n").append(Text.translatable("tryfishport.ui.ping.system.error_info").getString()).append(errorOutput);
}
}
// 如果输出为空但退出码为0,可能是命令执行了但没有输出
if (traceOutputBuffer.isEmpty() && exitCode == 0) {
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.no_output").getString());
}
} catch (IOException e) {
System.out.println("IOException when executing command: " + e.getMessage());
// 如果命令不存在或无法执行
if (e.getMessage().contains("Cannot run program") ||
e.getMessage().contains("error=2") ||
e.getMessage().contains("No such file or directory")) {
traceOutputBuffer.append(getCommandNotFoundMessage(friendlyName, os));
} else {
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.error").getString()).append(e.getMessage());
}
throw e; // 重新抛出其他IO异常
}
} catch (Exception e) {
System.out.println(Text.translatable("tryfishport.log.exception.traceroute").getString() + e.getMessage());
e.printStackTrace();
traceOutputBuffer.append(Text.translatable("tryfishport.ui.ping.system.command.error").getString()).append(e.getMessage()).append("\n");
}
}
/**
* 获取命令未找到时的友好提示信息
*
* @param command 命令名称
* @param os 操作系统名称
* @return 友好的错误提示信息
*/
private String getCommandNotFoundMessage(String command, String os) {
StringBuilder message = new StringBuilder();
message.append(Text.translatable("tryfishport.ui.ping.error.command_not_found").getString()).append(command).append("\n\n");
if (os.contains("win")) {
message.append(Text.translatable("tryfishport.ui.ping.system.windows.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.windows.line3").getString()).append("\n");
} else if (os.contains("mac") || os.contains("darwin")) {
message.append(Text.translatable("tryfishport.ui.ping.system.mac.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.mac.line3").getString()).append("\n");
} else {
message.append(Text.translatable("tryfishport.ui.ping.system.linux.info").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line1").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line2").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line3").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line4").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line5").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line6").getString()).append("\n");
message.append(Text.translatable("tryfishport.ui.ping.system.linux.line7").getString()).append("\n");
}
message.append(Text.translatable("tryfishport.ui.ping.system.tip").getString());
if (os.contains("win")) {
message.append(" tracert ").append(ServerAddress.parse(serverInfoAddress).getAddress());
} else {
message.append(" traceroute ").append(ServerAddress.parse(serverInfoAddress).getAddress());
}
return message.toString();
}
public String getTraceOutput() {
return traceOutputBuffer.toString();
}
// 添加资源清理方法
public static void shutdown() {
traceExecutor.shutdown();
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/RouteTracer.java | Java | mit | 8,912 |
package fun.xingwangzhe.tryfishport.client;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.client.MinecraftClient;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TryFishportUI extends Screen {
// 创建一个共享的线程池用于所有网络操作
private static final ExecutorService networkExecutor = Executors.newFixedThreadPool(4);
private final Screen parent;
private String ipAddress = Text.translatable("tryfishport.ui.unban.ip.getting").getString();
private String status = Text.translatable("tryfishport.ui.unban.status.checking").getString();
private String captcha = "";
// 保存翻译键而不是实际文本
private String resultMessage = "";
private boolean isChecking = false;
private boolean isBanned = false;
private boolean isIPv6 = false;
private String ipv4Token = "";
private String captchaToken = "";
// 服务类
private final IPAddressService ipService = new IPAddressService();
private final UnbanService unbanService = new UnbanService();
private final CaptchaService captchaService = new CaptchaService();
public TryFishportUI(Screen parent) {
super(Text.translatable("tryfishport.ui.unban.title"));
this.parent = parent;
}
@Override
protected void init() {
// 添加关闭按钮
this.addDrawableChild(ButtonWidget.builder(Text.translatable("tryfishport.ui.unban.button.close"), button -> close()).dimensions(this.width / 2 - 50, this.height - 30, 100, 20).build());
// 添加检查按钮
this.addDrawableChild(ButtonWidget.builder(Text.translatable("tryfishport.ui.unban.button.check_status"), button -> checkBanStatus()).dimensions(this.width / 2 - 105, this.height - 60, 100, 20).build());
// 添加解封按钮(初始禁用)
ButtonWidget unbanButton = ButtonWidget.builder(Text.translatable("tryfishport.ui.unban.button.submit_unban"), button -> submitUnbanRequest()).dimensions(this.width / 2 + 5, this.height - 60, 100, 20).build();
unbanButton.active = false;
this.addDrawableChild(unbanButton);
// 获取IP地址
getIPAddress();
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
// 绘制标题
context.drawCenteredTextWithShadow(this.textRenderer, this.title, this.width / 2, 15, 0xFFFFFF);
// 绘制IP地址信息
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.general.ip").getString() + ipAddress, 10, 50, 0xFFFFFF);
// 绘制IPv6提示信息
if (isIPv6) {
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.unban.ipv6.warning").getString(), 10, 65, 0xFFFF00);
}
// 绘制状态信息
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.general.status").getString() + status, 10, 70, 0xFFFFFF);
// 绘制封禁状态
if (isBanned) {
context.drawTextWithShadow(this.textRenderer, Text.translatable("tryfishport.ui.general.captcha").getString() + captcha, 10, 90, 0xFFFFFF);
}
// 绘制结果信息
if (!Text.translatable(resultMessage).getString().isEmpty()) {
context.drawTextWithShadow(this.textRenderer, Text.translatable(resultMessage), 10, 110, 0xFFFFFF);
}
}
private void getIPAddress() {
// 避免重复执行IP获取
if (!ipAddress.equals(Text.translatable("tryfishport.ui.unban.ip.getting").getString())) {
return;
}
CompletableFuture.runAsync(() -> {
try {
ipService.fetchIPAddress();
ipAddress = ipService.getIpAddress();
isIPv6 = ipService.isIPv6();
ipv4Token = ipService.getIpv4Token();
// 更新状态文本为可翻译格式
status = Text.translatable(status).getString();
// 检查是否为IPv6地址
isIPv6 = ipAddress.contains(":") && !ipAddress.contains(".");
// CHECK STATUS
checkBanStatus();
} catch (Exception e) {
ipAddress = Text.translatable("tryfishport.ui.unban.ip.failed").getString();
status = Text.translatable("tryfishport.ui.unban.status.error").getString();
resultMessage = Text.translatable("tryfishport.ui.unban.result.get_ip_failed").getString();
e.printStackTrace();
}
// 更新UI
MinecraftClient.getInstance().execute(this::refreshUI);
}, networkExecutor);
}
private void checkBanStatus() {
if (isChecking) {
return;
}
// 如果是IPv6地址,不允许检查状态
if (isIPv6) {
resultMessage = Text.translatable("tryfishport.ui.unban.result.ipv6_not_supported").getString();
refreshUI();
return;
}
isChecking = true;
status = Text.translatable("tryfishport.ui.unban.status.checking").getString();
resultMessage = "";
refreshUI();
CompletableFuture.runAsync(() -> {
try {
UnbanService.CheckResult result = unbanService.checkBanStatus(ipv4Token);
ipAddress = result.getIp();
isBanned = result.isBlacklisted();
if (isBanned) {
status = Text.translatable("tryfishport.ui.unban.status.banned").getString();
resultMessage = Text.translatable("tryfishport.ui.unban.captcha.calculating").getString();
calculateCaptcha();
} else {
status = Text.translatable("tryfishport.ui.unban.status.normal").getString();
resultMessage = Text.translatable("tryfishport.ui.unban.result.not_banned").getString();
}
} catch (Exception e) {
status = Text.translatable("tryfishport.ui.unban.status.check_failed").getString();
resultMessage = Text.translatable("tryfishport.ui.unban.result.check_failed").getString();
e.printStackTrace();
} finally {
isChecking = false;
MinecraftClient.getInstance().execute(this::refreshUI);
}
}, networkExecutor);
}
private void calculateCaptcha() {
// 如果是IPv6地址,不计算验证码
if (isIPv6) {
resultMessage = Text.translatable("tryfishport.ui.unban.result.ipv6_not_supported").getString();
refreshUI();
return;
}
// 使用新的异步方法
captchaService.calculateCaptchaAsync()
.thenAccept(result -> {
this.captcha = result.getCaptcha();
this.captchaToken = result.getCaptchaToken();
resultMessage = Text.translatable("tryfishport.ui.unban.captcha.ready").getString();
status = Text.translatable("tryfishport.ui.unban.status.ready").getString();
MinecraftClient.getInstance().execute(this::refreshUI);
})
.exceptionally(throwable -> {
captcha = "";
resultMessage = Text.translatable("tryfishport.ui.unban.result.captcha_calc_failed").getString();
status = Text.translatable("tryfishport.ui.unban.status.error").getString();
throwable.printStackTrace();
MinecraftClient.getInstance().execute(this::refreshUI);
return null;
});
}
private void submitUnbanRequest() {
// 如果是IPv6地址,不允许提交解封请求
if (isIPv6) {
resultMessage = Text.translatable("tryfishport.ui.unban.result.ipv6_not_supported").getString();
refreshUI();
return;
}
if (captcha.isEmpty() || !isBanned) {
resultMessage = Text.translatable("tryfishport.ui.unban.result.captcha_failed").getString();
refreshUI();
return;
}
boolean useToken = ipv4Token != null && !ipv4Token.isEmpty();
resultMessage = Text.translatable("tryfishport.ui.unban.result.request_submitted").getString();
refreshUI();
CompletableFuture.runAsync(() -> {
try {
UnbanService.UnbanResult result = unbanService.submitUnbanRequest(captcha, captchaToken, ipv4Token);
if (result.isSuccess()) {
// success
resultMessage = Text.translatable("tryfishport.ui.unban.status.unbanned").getString();
isBanned = false;
} else {
// fail
resultMessage = Text.translatable("tryfishport.ui.unban.result.unban_failed").getString() + result.getMessage();
}
} catch (Exception e) {
resultMessage = Text.translatable("tryfishport.ui.unban.result.unban_failed").getString();
e.printStackTrace();
}
// 更新UI
MinecraftClient.getInstance().execute(this::refreshUI);
}, networkExecutor);
}
private void refreshUI() {
// 触发UI重绘
this.init();
// 更新解封按钮状态
this.children().forEach(element -> {
if (element instanceof ButtonWidget button) {
if (button.getMessage().getString().equals(Text.translatable("tryfishport.ui.unban.button.submit_unban").getString())) {
button.active = isBanned && !captcha.isEmpty() && !Text.translatable("tryfishport.ui.unban.result.captcha_invalid").getString().equals(Text.translatable(resultMessage).getString()) && !isIPv6;
}
}
});
}
@Override
public void close() {
MinecraftClient.getInstance().setScreen(parent);
}
@Override
public boolean shouldPause() {
return false;
}
// 添加资源清理方法
public static void shutdown() {
networkExecutor.shutdown();
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/TryFishportUI.java | Java | mit | 10,690 |
package fun.xingwangzhe.tryfishport.client;
import net.fabricmc.api.ClientModInitializer;
public class TryfishportClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
System.out.println("Tryfishport Client Initialized");
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/TryfishportClient.java | Java | mit | 279 |
package fun.xingwangzhe.tryfishport.client;
import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint;
import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator;
public class TryfishportDataGenerator implements DataGeneratorEntrypoint {
@Override
public void onInitializeDataGenerator(FabricDataGenerator fabricDataGenerator) {
FabricDataGenerator.Pack pack = fabricDataGenerator.createPack();
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/TryfishportDataGenerator.java | Java | mit | 417 |
package fun.xingwangzhe.tryfishport.client;
import com.google.gson.Gson;
import net.minidev.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class UnbanService {
public static class CheckResult {
private final String ip;
private final boolean blacklisted;
public CheckResult(String ip, boolean blacklisted) {
this.ip = ip;
this.blacklisted = blacklisted;
}
public String getIp() {
return ip;
}
public boolean isBlacklisted() {
return blacklisted;
}
}
public CheckResult checkBanStatus(String ipv4Token) throws Exception {
if (ipv4Token != null && !ipv4Token.isEmpty()) {
// POST /check 提交 IPv4 token
URL checkUrl = URI.create("https://ip-unban.fishport.net/check").toURL();
HttpURLConnection checkConn = (HttpURLConnection) checkUrl.openConnection();
checkConn.setRequestMethod("POST");
checkConn.setRequestProperty("Content-Type", "application/json");
checkConn.setDoOutput(true);
String body = "{\"token\":\"" + ipv4Token + "\"}";
try (OutputStream os = checkConn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
}
int checkCode = checkConn.getResponseCode();
if (checkCode == 200) {
BufferedReader checkReader = new BufferedReader(new InputStreamReader(checkConn.getInputStream()));
StringBuilder checkResp = new StringBuilder();
String l;
while ((l = checkReader.readLine()) != null) {
checkResp.append(l);
}
checkReader.close();
String checkText = checkResp.toString();
// 解析JSON格式
Gson gson = new Gson();
JSONObject checkJson = gson.fromJson(checkText, JSONObject.class);
String ip = (String) checkJson.get("ip");
Boolean blacklisted = (Boolean) checkJson.get("blacklisted");
return new CheckResult(ip, blacklisted != null ? blacklisted : false);
} else {
throw new Exception("Check failed with code: " + checkCode);
}
} else {
// 默认IPV4 直接 GET /check
// 检查IP是否被封 使用URI方式创建URL对象,避免使用已过时的URL构造函数
URL url = new URI("https://ip-unban.fishport.net/check").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String responseText = response.toString();
// JSON解析
Gson gson = new Gson();
JSONObject jsonObject = gson.fromJson(responseText, JSONObject.class);
Boolean blacklisted = (Boolean) jsonObject.get("blacklisted");
String ip = (String) jsonObject.get("ip");
return new CheckResult(ip, blacklisted != null ? blacklisted : false);
} else {
throw new Exception("Check failed with code: " + responseCode);
}
}
}
public static class UnbanResult {
private final boolean success;
private final String message;
public UnbanResult(boolean success, String message) {
this.success = success;
this.message = message;
}
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
}
public UnbanResult submitUnbanRequest(String captcha, String captchaToken, String ipv4Token) throws Exception {
URL url = URI.create("https://ip-unban.fishport.net/unblock").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// 构造请求体
StringBuilder body = new StringBuilder();
body.append("{\"suffix\":\"").append(captcha).append("\"");
body.append(",\"captcha_token\":\"").append(captchaToken).append("\"");
// 新增:如果有ipv4Token,带上
if (ipv4Token != null && !ipv4Token.isEmpty()) {
body.append(",\"ipv4_token\":\"").append(ipv4Token).append("\"");
}
body.append("}");
try (OutputStream os = connection.getOutputStream()) {
os.write(body.toString().getBytes(StandardCharsets.UTF_8));
}
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String responseText = response.toString();
// 解析JSON格式
Gson gson = new Gson();
JSONObject jsonObject = gson.fromJson(responseText, JSONObject.class);
if (jsonObject.containsKey("msg")) {
// success
return new UnbanResult(true, (String) jsonObject.get("msg"));
} else {
// fail
return new UnbanResult(false, (String) jsonObject.get("error"));
}
} else {
throw new Exception("Unban request failed with code: " + responseCode);
}
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/client/UnbanService.java | Java | mit | 6,583 |
package fun.xingwangzhe.tryfishport.mixin.client;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import fun.xingwangzhe.tryfishport.client.TryFishportUI;
@Mixin(MultiplayerScreen.class)
public class MultiplayerScreenMixin extends Screen {
protected MultiplayerScreenMixin(Text title) {
super(title);
}
@Inject(at = @At("TAIL"), method = "init()V")
private void onInit(CallbackInfo ci) {
// 在服务器列表界面左下角添加自定义按钮
this.addDrawableChild(ButtonWidget
.builder(Text.translatable("tryfishport.button.tryfishport"), button -> {
System.out.println(Text.translatable("tryfishport.log.button.tryfishport.clicked").getString());
// 打开TryFishportUI界面
net.minecraft.client.MinecraftClient.getInstance().setScreen(new TryFishportUI(this));
})
.dimensions(5, this.height - 25, 100, 20)
.build());
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/mixin/client/MultiplayerScreenMixin.java | Java | mit | 1,326 |
package fun.xingwangzhe.tryfishport.mixin.client;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerServerListWidget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.HashMap;
import java.util.Map;
import fun.xingwangzhe.tryfishport.client.PingUI;
@Mixin(MultiplayerServerListWidget.ServerEntry.class)
public class ServerEntryMixin {
@Unique
private static final Logger LOGGER = LogManager.getLogger("TryFishport");
// 存储每个服务器条目的按钮
@Unique
private static final Map<MultiplayerServerListWidget.ServerEntry, ButtonWidget> entryButtons = new HashMap<>();
@Inject(at = @At("TAIL"), method = "render(Lnet/minecraft/client/gui/DrawContext;IIIIIIIZF)V")
private void onRender(DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta, CallbackInfo info) {
MultiplayerServerListWidget.ServerEntry entry = (MultiplayerServerListWidget.ServerEntry) (Object) this;
// 只有在hovered为true时才显示按钮
if (hovered) {
// 获取或创建按钮
ButtonWidget button = entryButtons.get(entry);
if (button == null) {
button = ButtonWidget.builder(Text.translatable("tryfishport.button.ping"), btn -> {
System.out.println("tryfishport.log.button.ping"); // 添加日志
// 获取当前屏幕并确保它是MultiplayerScreen
Screen currentScreen = MinecraftClient.getInstance().currentScreen;
if (currentScreen instanceof MultiplayerScreen) {
MinecraftClient.getInstance().setScreen(new PingUI((MultiplayerScreen) currentScreen, entry.getServer()));
} else {
// 如果由于某种原因当前屏幕不是MultiplayerScreen,则创建一个新的
MinecraftClient.getInstance().setScreen(new PingUI(new MultiplayerScreen(null), entry.getServer()));
}
}).dimensions(0, 0, 60, 20).build();
entryButtons.put(entry, button);
}
// 设置按钮位置(右下角)
int buttonX = x + entryWidth - 62; // 右边距2px + 按钮宽度60px
int buttonY = y + entryHeight - 22; // 底边距2px + 按钮高度20px
button.setX(buttonX);
button.setY(buttonY);
// 渲染按钮
button.render(context, mouseX, mouseY, tickDelta);
}
}
@Inject(method = "mouseClicked", at = @At("HEAD"), cancellable = true)
private void onMouseClicked(double mouseX, double mouseY, int button, CallbackInfoReturnable<Boolean> cir) {
MultiplayerServerListWidget.ServerEntry entry = (MultiplayerServerListWidget.ServerEntry) (Object) this;
// 获取该条目对应的按钮
ButtonWidget btn = entryButtons.get(entry);
if (btn != null && btn.mouseClicked(mouseX, mouseY, button)) {
cir.setReturnValue(true);
}
}
@Inject(method = "close", at = @At("HEAD"))
private void onClose(CallbackInfo ci) {
MultiplayerServerListWidget.ServerEntry entry = (MultiplayerServerListWidget.ServerEntry) (Object) this;
entryButtons.remove(entry);
}
// 替换 printStackTrace 为更可靠的日志记录
@Unique
private void logException(Exception e) {
LOGGER.error(Text.translatable("tryfishport.log.exception.button").getString(), e);
}
} | 2303_806435pww/TryFishport_moved | src/client/java/fun/xingwangzhe/tryfishport/mixin/client/ServerEntryMixin.java | Java | mit | 4,245 |
package fun.xingwangzhe.tryfishport;
import net.fabricmc.api.ModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Tryfishport implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("tryfishport");
@Override
public void onInitialize() {
LOGGER.info("Tryfishport mod initialized!");
}
} | 2303_806435pww/TryFishport_moved | src/main/java/fun/xingwangzhe/tryfishport/Tryfishport.java | Java | mit | 359 |
# This file is part of the openHiTLS project.
#
# openHiTLS is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
project(openHiTLS)
set(HiTLS_SOURCE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR})
if(DEFINED BUILD_DIR)
set(HiTLS_BUILD_DIR ${BUILD_DIR})
else()
set(HiTLS_BUILD_DIR ${HiTLS_SOURCE_ROOT_DIR}/build)
endif()
execute_process(COMMAND python3 ${HiTLS_SOURCE_ROOT_DIR}/configure.py -m --build_dir ${HiTLS_BUILD_DIR})
include(${HiTLS_BUILD_DIR}/modules.cmake)
install(DIRECTORY ${HiTLS_SOURCE_ROOT_DIR}/include/
DESTINATION ${CMAKE_INSTALL_PREFIX}/include/hitls/
FILES_MATCHING PATTERN "*.h")
| 2302_82127028/openHiTLS-examples_2931 | CMakeLists.txt | CMake | unknown | 1,079 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_CONF_H
#define HITLS_APP_CONF_H
#include <stdint.h>
#include "bsl_obj.h"
#include "bsl_conf.h"
#include "hitls_pki_types.h"
#include "hitls_pki_utils.h"
#include "hitls_pki_csr.h"
#include "hitls_pki_cert.h"
#include "hitls_pki_crl.h"
#include "hitls_pki_x509.h"
#include "hitls_pki_pkcs12.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* x509 v3 extensions
*/
#define HITLS_CFG_X509_EXT_AKI "authorityKeyIdentifier"
#define HITLS_CFG_X509_EXT_SKI "subjectKeyIdentifier"
#define HITLS_CFG_X509_EXT_BCONS "basicConstraints"
#define HITLS_CFG_X509_EXT_KU "keyUsage"
#define HITLS_CFG_X509_EXT_EXKU "extendedKeyUsage"
#define HITLS_CFG_X509_EXT_SAN "subjectAltName"
/* Key usage */
#define HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN "digitalSignature"
#define HITLS_CFG_X509_EXT_KU_NON_REPUDIATION "nonRepudiation"
#define HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT "keyEncipherment"
#define HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT "dataEncipherment"
#define HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT "keyAgreement"
#define HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN "keyCertSign"
#define HITLS_CFG_X509_EXT_KU_CRL_SIGN "cRLSign"
#define HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY "encipherOnly"
#define HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY "decipherOnly"
/* Extended key usage */
#define HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH "serverAuth"
#define HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH "clientAuth"
#define HITLS_CFG_X509_EXT_EXKU_CODE_SING "codeSigning"
#define HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT "emailProtection"
#define HITLS_CFG_X509_EXT_EXKU_TIME_STAMP "timeStamping"
#define HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN "OCSPSigning"
/* Subject Alternative Name */
#define HITLS_CFG_X509_EXT_SAN_EMAIL "email"
#define HITLS_CFG_X509_EXT_SAN_DNS "DNS"
#define HITLS_CFG_X509_EXT_SAN_DIR_NAME "dirName"
#define HITLS_CFG_X509_EXT_SAN_URI "URI"
#define HITLS_CFG_X509_EXT_SAN_IP "IP"
/* Authority key identifier */
#define HITLS_CFG_X509_EXT_AKI_KID (1 << 0)
#define HITLS_CFG_X509_EXT_AKI_KID_ALWAYS (1 << 1)
typedef struct {
HITLS_X509_ExtAki aki;
uint32_t flag;
} HITLS_CFG_ExtAki;
/**
* @ingroup apps
*
* @brief Split String by character.
* Remove spaces before and after separators.
*
* @param str [IN] String to be split.
* @param separator [IN] Separator.
* @param allowEmpty [IN] Indicates whether empty substrings can be contained.
* @param strArr [OUT] String array. Only the first string needs to be released after use.
* @param maxArrCnt [IN] String array. Only the first string needs to be released after use.
* @param realCnt [OUT] Number of character strings after splitting。
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt,
uint32_t *realCnt);
/**
* @ingroup apps
*
* @brief Process function of X509 extensions.
*
* @param cid [IN] Cid of extension
* @param val [IN] Data pointer.
* @param ctx [IN] Context.
*
* @retval HITLS_APP_SUCCESS
*/
typedef int32_t (*ProcExtCallBack)(BslCid cid, void *val, void *ctx);
/**
* @ingroup apps
*
* @brief Process function of X509 extensions.
*
* @param value [IN] conf
* @param section [IN] The section name of x509 extension
* @param extCb [IN] Callback function of one extension.
* @param ctx [IN] Context of callback function.
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx);
/**
* @ingroup apps
*
* @brief The callback function to add distinguish name
*
* @param ctx [IN] The context of callback function
* @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN
*
* @retval HITLS_APP_SUCCESS
*/
typedef int32_t (*AddDnNameCb)(void *ctx, BslList *nameList);
/**
* @ingroup apps
*
* @brief The callback function to add subject name to csr
*
* @param ctx [IN] The context of callback function
* @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList);
/**
* @ingroup apps
*
* @brief Process distinguish name string.
* The distinguish name format is /type0=value0/type1=value1/type2=...
*
* @param nameStr [IN] distinguish name string
* @param cb [IN] The callback function to add distinguish name to csr or cert
* @param ctx [IN] Context of callback function.
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb cb, void *ctx);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_CONF_H
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_conf.h | C | unknown | 5,429 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_CRL_H
#define HITLS_APP_CRL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_CrlMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_crl.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_DGST_H
#define HITLS_APP_DGST_H
#include <stdint.h>
#include <stddef.h>
#include "crypt_algid.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const int mdId;
const char *mdAlgName;
} HITLS_AlgList;
int32_t HITLS_DgstMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_dgst.h | C | unknown | 866 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_ENC_H
#define HITLS_APP_ENC_H
#include <stdint.h>
#include <linux/limits.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_ITERATION_TIMES 10000
#define REC_MAX_FILE_LENGEN 512
#define REC_MAX_FILENAME_LENGTH PATH_MAX
#define REC_MAX_MAC_KEY_LEN 64
#define REC_MAX_KEY_LENGTH 64
#define REC_MAX_IV_LENGTH 16
#define REC_HEX_BASE 16
#define REC_SALT_LEN 8
#define REC_HEX_BUF_LENGTH 8
#define REC_MIN_PRE_LENGTH 6
#define REC_DOUBLE 2
#define MAX_BUFSIZE 4096
#define XTS_MIN_DATALEN 16
#define BUF_SAFE_BLOCK 16
#define BUF_READABLE_BLOCK 32
#define IS_SUPPORT_GET_EOF 1
#define BSL_SUCCESS 0
typedef enum {
HITLS_APP_OPT_CIPHER_ALG = 2,
HITLS_APP_OPT_IN_FILE,
HITLS_APP_OPT_OUT_FILE,
HITLS_APP_OPT_DEC,
HITLS_APP_OPT_ENC,
HITLS_APP_OPT_MD,
HITLS_APP_OPT_PASS,
} HITLS_OptType;
typedef struct {
const int cipherId;
const char *cipherAlgName;
} HITLS_CipherAlgList;
typedef struct {
const int macId;
const char *macAlgName;
} HITLS_MacAlgList;
int32_t HITLS_EncMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_enc.h | C | unknown | 1,853 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_ERRNO_H
#define HITLS_APP_ERRNO_H
#ifdef __cplusplus
extern "C" {
#endif
#define HITLS_APP_SUCCESS 0
// The return value of HITLS APP ranges from 0, 1, 3 to 125.
// 3 to 125 are external error codes.
enum HITLS_APP_ERROR {
HITLS_APP_HELP = 0x1, /* *< the subcommand has the help option */
HITLS_APP_SECUREC_FAIL, /* *< error returned by the safe function */
HITLS_APP_MEM_ALLOC_FAIL, /* *< failed to apply for memory resources */
HITLS_APP_INVALID_ARG, /* *< invalid parameter */
HITLS_APP_INTERNAL_EXCEPTION,
HITLS_APP_ENCODE_FAIL, /* *< encodeing failure */
HITLS_APP_CRYPTO_FAIL,
HITLS_APP_PASSWD_FAIL,
HITLS_APP_UIO_FAIL,
HITLS_APP_STDIN_FAIL, /* *< incorrect stdin input */
HITLS_APP_INFO_CMP_FAIL, /* *< failed to match the received information with the parameter */
HITLS_APP_INVALID_DN_TYPE,
HITLS_APP_INVALID_DN_VALUE,
HITLS_APP_INVALID_GENERAL_NAME_TYPE,
HITLS_APP_INVALID_GENERAL_NAME,
HITLS_APP_INVALID_IP,
HITLS_APP_ERR_CONF_GET_SECTION,
HITLS_APP_NO_EXT,
HITLS_APP_INIT_FAILED,
HITLS_APP_COPY_ARGS_FAILED,
HITLS_APP_OPT_UNKOWN, /* *< option error */
HITLS_APP_OPT_NAME_INVALID, /* *< the subcommand name is invalid */
HITLS_APP_OPT_VALUETYPE_INVALID, /* *< the parameter type of the subcommand is invalid */
HITLS_APP_OPT_TYPE_INVALID, /* *< the subcommand type is invalid */
HITLS_APP_OPT_VALUE_INVALID, /* *< the subcommand parameter value is invalid */
HITLS_APP_DECODE_FAIL, /* *< decoding failure */
HITLS_APP_CERT_VERIFY_FAIL, /* *< certificate verification failed */
HITLS_APP_X509_FAIL, /* *< x509-related error. */
HITLS_APP_SAL_FAIL, /* *< sal-related error. */
HITLS_APP_BSL_FAIL, /* *< bsl-related error. */
HITLS_APP_CONF_FAIL, /* *< conf-related error. */
HITLS_APP_LOAD_CERT_FAIL, /* *< Failed to load the cert. */
HITLS_APP_LOAD_CSR_FAIL, /* *< Failed to load the csr. */
HITLS_APP_LOAD_KEY_FAIL, /* *< Failed to load the public and private keys. */
HITLS_APP_ENCODE_KEY_FAIL, /* *< Failed to encode the public and private keys. */
HITLS_APP_MAX = 126, /* *< maximum of the error code */
};
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_errno.h | C | unknown | 3,087 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_FUNCTION_H
#define HITLS_APP_FUNCTION_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FUNC_TYPE_NONE, // default
FUNC_TYPE_GENERAL, // general command
} HITLS_CmdFuncType;
typedef struct {
const char *name; // second-class command name
HITLS_CmdFuncType type; // type of command
int (*main)(int argc, char *argv[]); // second-class entry function
} HITLS_CmdFunc;
int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func);
void AppPrintFuncList(void);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_function.h | C | unknown | 1,129 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_GENPKEY_H
#define HITLS_APP_GENPKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_GenPkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_Genpkey_H | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_genpkey.h | C | unknown | 769 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_GENRSA_H
#define HITLS_APP_GENRSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_PEM_FILELEN 65537
#define REC_MAX_PKEY_LENGTH 16384
#define REC_MIN_PKEY_LENGTH 512
#define REC_ALG_NUM_EACHLINE 4
typedef struct {
const int id;
const char *algName;
} HITLS_APPAlgList;
int32_t HITLS_GenRSAMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_genrsa.h | C | unknown | 967 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_HELP_H
#define HITLS_APP_HELP_H
#ifdef __cplusplus
extern "C" {
#endif
int HITLS_HelpMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_help.h | C | unknown | 714 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_KDF_H
#define HITLS_APP_KDF_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_KdfMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_kdf.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_LIST_H
#define HITLS_APP_LIST_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
HITLS_APP_LIST_OPT_ALL_ALG = 2,
HITLS_APP_LIST_OPT_DGST_ALG,
HITLS_APP_LIST_OPT_CIPHER_ALG,
HITLS_APP_LIST_OPT_ASYM_ALG,
HITLS_APP_LIST_OPT_MAC_ALG,
HITLS_APP_LIST_OPT_RAND_ALG,
HITLS_APP_LIST_OPT_KDF_ALG,
HITLS_APP_LIST_OPT_CURVES
} HITLSListOptType;
int HITLS_ListMain(int argc, char *argv[]);
int32_t HITLS_APP_GetCidByName(const char *name, int32_t type);
const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_LIST_H
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_list.h | C | unknown | 1,183 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_MAC_H
#define HITLS_APP_MAC_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_MacMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_mac.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_OPT_H
#define HITLS_APP_OPT_H
#include <stdint.h>
#include "bsl_uio.h"
#include "bsl_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define HILTS_APP_FORMAT_UNDEF 0
#define HITLS_APP_FORMAT_PEM BSL_FORMAT_PEM // 1
#define HITLS_APP_FORMAT_ASN1 BSL_FORMAT_ASN1 // 2
#define HITLS_APP_FORMAT_TEXT 3
#define HITLS_APP_FORMAT_BASE64 4
#define HITLS_APP_FORMAT_HEX 5
#define HITLS_APP_FORMAT_BINARY 6
#define HITLS_APP_PROV_ENUM \
HITLS_APP_OPT_PROVIDER, \
HITLS_APP_OPT_PROVIDER_PATH, \
HITLS_APP_OPT_PROVIDER_ATTR \
#define HITLS_APP_PROV_OPTIONS \
{"provider", HITLS_APP_OPT_PROVIDER, HITLS_APP_OPT_VALUETYPE_STRING, \
"Specify the cryptographic service provider"}, \
{"provider-path", HITLS_APP_OPT_PROVIDER_PATH, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set the path to the cryptographic service provider"}, \
{"provider-attr", HITLS_APP_OPT_PROVIDER_ATTR, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set additional attributes for the cryptographic service provider"} \
#define HITLS_APP_PROV_CASES(optType, provider) \
switch (optType) { \
case HITLS_APP_OPT_PROVIDER: \
(provider)->providerName = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_PATH: \
(provider)->providerPath = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_ATTR: \
(provider)->providerAttr = HITLS_APP_OptGetValueStr(); \
break; \
default: \
break; \
}
typedef enum {
HITLS_APP_OPT_VALUETYPE_NONE = 0,
HITLS_APP_OPT_VALUETYPE_NO_VALUE = 1,
HITLS_APP_OPT_VALUETYPE_IN_FILE,
HITLS_APP_OPT_VALUETYPE_OUT_FILE,
HITLS_APP_OPT_VALUETYPE_STRING,
HITLS_APP_OPT_VALUETYPE_PARAMTERS,
HITLS_APP_OPT_VALUETYPE_DIR,
HITLS_APP_OPT_VALUETYPE_INT,
HITLS_APP_OPT_VALUETYPE_UINT,
HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
HITLS_APP_OPT_VALUETYPE_LONG,
HITLS_APP_OPT_VALUETYPE_ULONG,
HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
HITLS_APP_OPT_VALUETYPE_FMT_ANY,
HITLS_APP_OPT_VALUETYPE_MAX,
} HITLS_ValueType;
typedef enum {
HITLS_APP_OPT_VALUECLASS_NONE = 0,
HITLS_APP_OPT_VALUECLASS_NO_VALUE = 1,
HITLS_APP_OPT_VALUECLASS_STR,
HITLS_APP_OPT_VALUECLASS_DIR,
HITLS_APP_OPT_VALUECLASS_INT,
HITLS_APP_OPT_VALUECLASS_LONG,
HITLS_APP_OPT_VALUECLASS_FMT,
HITLS_APP_OPT_VALUECLASS_MAX,
} HITLS_ValueClass;
typedef enum {
HITLS_APP_OPT_ERR = -1,
HITLS_APP_OPT_EOF = 0,
HITLS_APP_OPT_PARAM = HITLS_APP_OPT_EOF,
HITLS_APP_OPT_HELP = 1,
} HITLS_OptChoice;
typedef struct {
const char *name; // option name
const int optType; // option type
int valueType; // options with parameters(type)
const char *help; // description of this option
} HITLS_CmdOption;
/**
* @ingroup HITLS_APP
* @brief Initialization of command-line argument parsing (internal function)
*
* @param argc [IN] number of options
* @param argv [IN] pointer to an array of options
* @param opts [IN] command option table
*
* @retval command name of command-line argument
*/
int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Parse next command-line argument (internal function)
*
* @param void
*
* @retval int32 option type
*/
int32_t HITLS_APP_OptNext(void);
/**
* @ingroup HITLS_APP
* @brief Finish parsing options
*
* @param void
*
* @retval void
*/
void HITLS_APP_OptEnd(void);
/**
* @ingroup HITLS_APP
* @brief Print command line parsing
*
* @param opts command option table
*
* @retval void
*/
void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Get the number of remaining options
*
* @param void
*
* @retval int32 number of remaining options
*/
int32_t HITLS_APP_GetRestOptNum(void);
/**
* @ingroup HITLS_APP
* @brief Get the remaining options
*
* @param void
*
* @retval char** the address of remaining options
*/
char **HITLS_APP_GetRestOpt(void);
/**
* @ingroup HITLS_APP
* @brief Get command option
* @param void
* @retval char* command option
*/
char *HITLS_APP_OptGetValueStr(void);
/**
* @ingroup HITLS_APP
* @brief option string to int
* @param valueS [IN] string value
* @param valueL [OUT] int value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI);
/**
* @ingroup HITLS_APP
* @brief option string to uint32_t
* @param valueS [IN] string value
* @param valueL [OUT] uint32_t value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU);
/**
* @ingroup HITLS_APP
* @brief Get the name of the current second-class command
*
* @param void
*
* @retval char* command name
*/
char *HITLS_APP_GetProgName(void);
/**
* @ingroup HITLS_APP
* @brief option string to long
*
* @param valueS [IN] string value
* @param valueL [OUT] long value
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL);
/**
* @ingroup HITLS_APP
* @brief Get the format type from the option value
*
* @param valueS [IN] string of value
* @param type [IN] value type
* @param formatType [OUT] format type
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType);
/**
* @ingroup HITLS_APP
* @brief Get UIO type from option value
*
* @param filename [IN] name of input file
* @param mode [IN] method of opening a file
* @param flag [OUT] whether the closing of the standard input/output window is bound to the UIO
*
* @retval BSL_UIO * when succeeded, NULL when failed
*/
BSL_UIO* HITLS_APP_UioOpen(const char* filename, char mode, int32_t flag);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a character string in Base64 format and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToBase64(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a hexadecimal character string and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToHex(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Output the buf to UIO
*
* @param uio [IN] output UIO
* @param buf [IN] output buf
* @param outLen [IN] the length of output buf
* @param format [IN] output format
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptWriteUio(BSL_UIO* uio, uint8_t* buf, uint32_t outLen, int32_t format);
/**
* @ingroup HITLS_APP
* @brief Read the content in the UIO to the readBuf
*
* @param uio [IN] input UIO
* @param readBuf [IN] buf which uio read
* @param readBufLen [IN] the length of readBuf
* @param maxBufLen [IN] the maximum length to be read.
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen);
/**
* @ingroup HITLS_APP
* @brief Get unknown option name
*
* @retval char*
*/
const char *HITLS_APP_OptGetUnKownOptName();
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_opt.h | C | unknown | 8,603 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PASSWD_H
#define HITLS_APP_PASSWD_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_ITER_TIMES 999999999
#define REC_DEF_ITER_TIMES 5000
#define REC_MAX_ARRAY_LEN 1025
#define REC_MIN_ITER_TIMES 1000
#define REC_SHA512_BLOCKSIZE 64
#define REC_HASH_BUF_LEN 64
#define REC_MIN_PREFIX_LEN 37
#define REC_MAX_SALTLEN 16
#define REC_SHA512_SALTLEN 16
#define REC_TEN 10
#define REC_PRE_ITER_LEN 8
#define REC_SEVEN 7
#define REC_SHA512_ALGTAG 6
#define REC_SHA256_ALGTAG 5
#define REC_PRE_TAG_LEN 3
#define REC_THREE 3
#define REC_TWO 2
#define REC_MD5_ALGTAG 1
int32_t HITLS_PasswdMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_passwd.h | C | unknown | 1,429 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PKCS12_H
#define HITLS_APP_PKCS12_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PKCS12Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_pkcs12.h | C | unknown | 745 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PKEY_H
#define HITLS_APP_PKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_PKEY_H | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_pkey.h | C | unknown | 757 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_LOG_H
#define HITLS_APP_LOG_H
#include <stdio.h>
#include <stdint.h>
#include "bsl_uio.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup HITLS_APPS
* @brief Print output to UIO
*
* @param uio [IN] UIO to be printed
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval int32_t
*/
int32_t AppPrint(BSL_UIO *uio, const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Print the output to stderr.
*
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval void
*/
void AppPrintError(const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Initialize the PrintErrUIO.
*
* @param fp [IN] File pointer, for example, stderr.
* @retval int32_t
*/
int32_t AppPrintErrorUioInit(FILE *fp);
/**
* @ingroup HiTLS_APPS
* @brief Deinitialize the PrintErrUIO.
*
* @retval void
*/
void AppPrintErrorUioUnInit(void);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_print.h | C | unknown | 1,527 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PROVIDER_H
#define HITLS_APP_PROVIDER_H
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_eal_provider.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
char *providerName;
char *providerPath;
char *providerAttr;
} AppProvider;
CRYPT_EAL_LibCtx *APP_Create_LibCtx(void);
CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void);
int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName);
#define HITLS_APP_FreeLibCtx CRYPT_EAL_LibCtxFree
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_provider.h | C | unknown | 1,083 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_RAND_H
#define HITLS_APP_RAND_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RandMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_rand.h | C | unknown | 737 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_REQ_H
#define HITLS_APP_REQ_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_ReqMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_REQ_H | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_req.h | C | unknown | 753 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_RSA_H
#define HITLS_APP_RSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RsaMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_rsa.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef APP_UTILS_H
#define APP_UTILS_H
#include <stddef.h>
#include <stdint.h>
#include "bsl_ui.h"
#include "bsl_types.h"
#include "crypt_eal_pkey.h"
#include "app_conf.h"
#include "hitls_csr_local.h"
#ifdef __cplusplus
extern "C" {
#endif
#define APP_MAX_PASS_LENGTH 1024
#define APP_MIN_PASS_LENGTH 1
#define APP_FILE_MAX_SIZE_KB 256
#define APP_FILE_MAX_SIZE (APP_FILE_MAX_SIZE_KB * 1024) // 256KB
#define DEFAULT_SALTLEN 16
#define DEFAULT_ITCNT 2048
void *ExpandingMem(void *oldPtr, size_t newSize, size_t oldSize);
/**
* @ingroup apps
*
* @brief Apps Function for Checking the Validity of Key Characters
*
* @attention If the key length needs to be limited, the caller needs to limit the key length outside the function.
*
* @param password [IN] Key entered by the user
* @param passwordLen [IN] Length of the key entered by the user
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_CheckPasswd(const uint8_t *password, const uint32_t passwordLen);
/**
* @ingroup apps
*
* @brief Apps Function for Verifying Passwd Received by the BSL_UI_ReadPwdUtil()
*
* @attention callBackData is the default callback structure APP_DefaultPassCBData.
*
* @param ui [IN] Input/Output Stream
* @param buff [IN] Buffer for receiving passwd
* @param buffLen [IN] Length of the buffer for receiving passwd
* @param callBackData [IN] Key verification information.
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_DefaultPassCB(BSL_UI *ui, char *buff, uint32_t buffLen, void *callBackData);
int32_t HITLS_APP_Passwd(char *buf, int32_t bufMaxLen, int32_t flag, void *userdata);
void HITLS_APP_PrintPassErrlog(void);
/**
* @ingroup apps
*
* @brief Obtain the password from the command line argument.
*
* @attention pass: The memory needs to be released automatically.
*
* @param passArg [IN] Command line password parameters
* @param pass [OUT] Parsed password
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_ParsePasswd(const char *passArg, char **pass);
int32_t HITLS_APP_GetPasswd(BSL_UI_ReadPwdParam *param, char **passin, uint8_t **pass, uint32_t *passLen);
/**
* @ingroup apps
*
* @brief Load the public key.
*
* @attention If inFilePath is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Public Key Format
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPubKey(const char *inFilePath, BSL_ParseFormat informat);
/**
* @ingroup apps
*
* @brief Load the private key.
*
* @attention If inFilePath or passin is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Private Key Format
* @param passin [IN/OUT] Parsed password
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPrvKey(const char *inFilePath, BSL_ParseFormat informat, char **passin);
/**
* @ingroup apps
*
* @brief Print the public key.
*
* @attention If outFilePath is empty, the standard output is displayed.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Public Key Format
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPubKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat);
/**
* @ingroup apps
*
* @brief Print the private key.
*
* @attention If outFilePath is empty, the standard output is displayed, If passout is empty, it is read
* from the standard input.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Private Key Format
* @param cipherAlgCid [IN] Encryption algorithm cid
* @param passout [IN/OUT] encryption password
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPrvKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat,
int32_t cipherAlgCid, char **passout);
typedef struct {
const char *name;
BSL_ParseFormat outformat;
int32_t cipherAlgCid;
bool text;
bool noout;
} AppKeyPrintParam;
int32_t HITLS_APP_PrintPrvKeyByUio(BSL_UIO *uio, CRYPT_EAL_PkeyCtx *pkey, AppKeyPrintParam *printKeyParam,
char **passout);
/**
* @ingroup apps
*
* @brief Obtain and check the encryption algorithm.
*
* @param name [IN] encryption name
* @param symId [IN/OUT] encryption algorithm cid
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
*/
int32_t HITLS_APP_GetAndCheckCipherOpt(const char *name, int32_t *symId);
/**
* @ingroup apps
*
* @brief Load the cert.
*
* @param inPath [IN] cert path
* @param inform [IN] cert format
*
* @retval HITLS_X509_Cert
*/
HITLS_X509_Cert *HITLS_APP_LoadCert(const char *inPath, BSL_ParseFormat inform);
/**
* @ingroup apps
*
* @brief Load the csr.
*
* @param inPath [IN] csr path
* @param inform [IN] csr format
*
* @retval HITLS_X509_Csr
*/
HITLS_X509_Csr *HITLS_APP_LoadCsr(const char *inPath, BSL_ParseFormat inform);
int32_t HITLS_APP_GetAndCheckHashOpt(const char *name, int32_t *hashId);
int32_t HITLS_APP_PrintText(const BSL_Buffer *csrBuf, const char *outFileName);
int32_t HITLS_APP_HexToByte(const char *hex, uint8_t **bin, uint32_t *len);
CRYPT_EAL_PkeyCtx *HITLS_APP_GenRsaPkeyCtx(uint32_t bits);
#ifdef __cplusplus
}
#endif
#endif // APP_UTILS_H | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_utils.h | C | unknown | 6,401 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_VERIFY_H
#define HITLS_APP_VERIFY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_VerifyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_2931 | apps/include/app_verify.h | C | unknown | 744 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_X509_H
#define HITLS_APP_X509_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_X509Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_X509_H | 2302_82127028/openHiTLS-examples_2931 | apps/include/app_x509.h | C | unknown | 757 |