From 63d8ffe81f499a105b8d56f99c7da3a5eafb2ffc Mon Sep 17 00:00:00 2001 From: openharmony_ci <120357966@qq.com> Date: Tue, 30 Apr 2024 02:34:44 +0000 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E9=80=80=20'Pull=20Request=20!412=20:?= =?UTF-8?q?=20=E6=9C=89=E7=BA=BF=E5=A4=96=E5=9B=B4=E9=9C=80=E6=B1=82?= =?UTF-8?q?=E6=95=B4=E6=94=B9'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- etc/param/usb_service.para | 2 +- .../UsbFunctionSwitchWindowAbility.ts | 154 ++++++++-- .../src/main/ets/pages/Index.ets | 274 ++++++++++++------ .../usb_right_dialog/src/main/module.json | 4 +- .../src/main/resources/en/element/string.json | 2 +- .../src/main/resources/zh/element/string.json | 4 +- services/BUILD.gn | 3 - .../include/usb_function_switch_window.h | 13 +- services/native/src/usb_device_manager.cpp | 10 + .../native/src/usb_function_switch_window.cpp | 117 +------- services/native/src/usb_service.cpp | 13 +- usbmgr.gni | 4 - 12 files changed, 350 insertions(+), 250 deletions(-) diff --git a/etc/param/usb_service.para b/etc/param/usb_service.para index 5ba8c142..1cbe098e 100644 --- a/etc/param/usb_service.para +++ b/etc/param/usb_service.para @@ -10,4 +10,4 @@ # 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. -persist.usb.setting.gadget_conn_prompt=true +persist.usb.setting.gadget_conn_prompt=false diff --git a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/ServiceExtAbility/UsbFunctionSwitchWindowAbility.ts b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/ServiceExtAbility/UsbFunctionSwitchWindowAbility.ts index e503f9d6..2a8eef51 100755 --- a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/ServiceExtAbility/UsbFunctionSwitchWindowAbility.ts +++ b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/ServiceExtAbility/UsbFunctionSwitchWindowAbility.ts @@ -12,44 +12,156 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility' -import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession' + +import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; +import window from '@ohos.window'; +import display from '@ohos.display'; import rpc from '@ohos.rpc'; +import { notificationUtil } from '../util/NotificationUtil'; +import {GlobalThisProxy} from '../util/GlobalThisProxy'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import type { Permissions } from '@ohos.abilityAccessCtrl'; -let TAG: string = 'UsbService'; +let TAG: string = 'usbfunctionswitchwindow_ServiceExtensionAbility'; +let WINDOW_NAME: string = 'UsbFunctionSwitchWindow'; +const ENTERPRISE_MANAGE_USB = 'ohos.permission.ENTERPRISE_MANAGE_USB'; const ACCESS_TYPE_MASK = 0b11; const SHIFT_DIGIT = 27; const TOKEN_NATIVE = 1; -const TOKEN_HAP = 0; -const BG_COLOR = '#00000000'; -export default class UsbFunctionSwitchAbility extends UIExtensionAbility { - onSessionCreate(want, session): void { - console.log(TAG + 'UsbFunctionSwitchAbility onSessionCreate'); +class UsbFunctionSwitchStub extends rpc.RemoteObject { + constructor(des) { + super(des); + } + onRemoteRequest(code, data, reply, option): boolean { let callingTokenId: number = rpc.IPCSkeleton.getCallingTokenId(); - if (!this.isSystemAbility(callingTokenId)) { + if (!this.isSystemAbility(callingTokenId) && !this.checkPermission(callingTokenId, ENTERPRISE_MANAGE_USB)) { console.error('check permission fail'); - return; + return false; } - AppStorage.setOrCreate("session", session); - (session as UIExtensionContentSession)?.loadContent('pages/Index'); + return true; + } + + private isSystemAbility(callingTokenId: number): boolean { + let type: number = ACCESS_TYPE_MASK & (callingTokenId >> SHIFT_DIGIT); + console.info('isSystemAbility, type:' + type); + return type === TOKEN_NATIVE; + } + + private checkPermission(tokenID: number, permissionName: Permissions): boolean { + let aac = abilityAccessCtrl.createAtManager(); try { - (session as UIExtensionContentSession)?.setWindowBackgroundColor(BG_COLOR); + let grantStatus = aac.verifyAccessTokenSync(tokenID, permissionName); + if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) { + console.error(`verify ${permissionName} fail`); + } } catch (error) { - console.error(TAG + 'UsbFunctionSwitchAbility onSessionCreate error: ' + error?.code); - (session as UIExtensionContentSession)?.terminateSelf(); + console.error(`verify ${permissionName}, ${error}`); + } + console.info(`verify ${permissionName}, success`); + return true; + } +} + +const BG_COLOR = '#00000000'; +let usbServiceSwitchWindowFirst = undefined; + +export default class UsbFunctionSwitchAbility extends ServiceExtensionAbility { + + /** + * Lifecycle function, called back when a service extension is started for initialization. + */ + onCreate(want): void { + console.log('onCreate want: ' + JSON.stringify(want)); + GlobalThisProxy.getInstance().setContext('extensionAbility', this.context); + globalThis.extensionContext = this.context; + globalThis.want = want; + globalThis.windowNum = 0; + globalThis.usbServiceSwitchWindowFirst = usbServiceSwitchWindowFirst; + } + + /** + * Lifecycle function, called back when a service extension is started or recall. + */ + onRequest(want, startId): void { + console.log('onRequest want: ' + JSON.stringify(want)); + GlobalThisProxy.getInstance().setNumInfo('workWant_defaultChoose', want.parameters.defaultChoose); + GlobalThisProxy.getInstance().setNumInfo('workWant_funcSelect', want.parameters.funcSelect); + globalThis.abilityWant = want; + let displayClass: display.Display | null = null; + try { + displayClass = display.getDefaultDisplaySync(); + } catch { + console.info('display.getDefaultDisplaySync failed'); } + + let navigationBarRect = { + left: 0, + top: 0, + width: displayClass.width, + height: displayClass.height + }; + + this.createOrShowUsbWindow(WINDOW_NAME, window.WindowType.TYPE_FLOAT, navigationBarRect); + } + + onConnect(want): rpc.RemoteObject { + globalThis.abilityWant = want; + console.log('onConnect want: ' + JSON.stringify(want)); + return new UsbFunctionSwitchStub('test'); + } + + + onDisconnect(want): void { + console.log('onDisconnect'); return; } - onSessionDestroy(session): void { - console.log(TAG + 'UsbFunctionSwitchAbility onSessionDestroy'); + + /** + * Lifecycle function, called back before a service extension is destroyed. + */ + onDestroy(): void { + console.log(TAG + 'onDestroy'); + if (globalThis.window) { + globalThis.usbServiceSwitchWindowFirst = undefined; + notificationUtil.cancelAllNotifications(); + globalThis.window.destroy((err, data) => { + if (err.code) { + console.error(TAG + 'Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.log(TAG + 'Succeeded in destroy the window'); + globalThis.window = undefined; + }); + } } - private isSystemAbility(callingTokenId: number): boolean { - let type: number = ACCESS_TYPE_MASK & (callingTokenId >> SHIFT_DIGIT); - console.info('isSystemAbility, type:' + type); - return type === TOKEN_NATIVE || type === TOKEN_HAP; + private async createOrShowUsbWindow(winName: string, windowType: number, rect): Promise { + try { + if (globalThis.usbServiceSwitchWindowFirst !== undefined) { + console.log(TAG + 'destroy first power window'); + globalThis.usbServiceSwitchWindowFirst.destroy(); + globalThis.usbServiceSwitchWindowFirst = undefined; + } + + let config = {name: winName, windowType: windowType, ctx: globalThis.extensionContext}; + const usbWin = await window.createWindow(config); + if (globalThis.usbServiceSwitchWindowFirst === undefined) { + console.log(TAG + 'usbServiceSwitchWindowFirst not init, init now'); + usbServiceSwitchWindowFirst = usbWin; + globalThis.usbServiceSwitchWindowFirst = usbServiceSwitchWindowFirst; + } + globalThis.window = usbWin; + await usbWin.moveWindowTo(rect.left, rect.top); + await usbWin.resize(rect.width, rect.height); + await usbWin.setUIContent('pages/Index'); + await usbWin.setWindowBackgroundColor(BG_COLOR); + await usbWin.showWindow(); + console.log('UsbFunctionSwitchAbility window create successfully'); + } catch { + console.info('UsbFunctionSwitchAbility window create failed'); + } } }; diff --git a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/pages/Index.ets b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/pages/Index.ets index 49b41fb6..a47a54ad 100755 --- a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/pages/Index.ets +++ b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/ets/pages/Index.ets @@ -13,144 +13,226 @@ * limitations under the License. */ -import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession' +import { notificationUtil } from '../util/NotificationUtil'; import { usbServiceSwitch } from '../util/UsbServiceSwitch'; import {GlobalThisProxy} from '../util/GlobalThisProxy'; import { BusinessError } from '@ohos.base'; import window from '@ohos.window'; import common from '@ohos.app.ability.common' import Want from '@ohos.app.ability.Want'; -let TAG: string = 'UsbService'; +let TAG: string = 'usbfunctionswitchwindow_Index'; let USBSERVICESWITCH_ID_DEFAULT : number = -1; let USBSERVICESWITCH_ID_CHARGE_ONLY : number = -1; let USBSERVICESWITCH_ID_XFER_FILE : number = 8; let USBSERVICESWITCH_ID_XFER_PIC : number = 16; -const FIRST_ITEM_INDEX: number = 0; -const LIST_MIN_HEIGHT: number = 48; + @CustomDialog export default struct PopUpWindow { @State curSelectNumber: number = USBSERVICESWITCH_ID_DEFAULT; customDialogController: CustomDialogController; - radioContent: Array = []; - build() { Column() { - Row() { - Text($r('app.string.USB_hint')) - .fontSize(20) - .fontWeight('Bold') - .textAlign(TextAlign.Start) - .textOverflow({overflow: TextOverflow.Ellipsis}) - } - .height(56) + Blank().height(5) + Text($r('app.string.USB_hint')) .width('100%') - List({ space: 1 }) { - ForEach(this.radioContent, (item: SheetInfo, index?: number) => { - ListItem() { - Column() { - Button() { - Row() { - Text(item.title) - .fontSize(16) - .fontWeight('Medium') - .fontColor($r('sys.color.font_primary')) - .layoutWeight(1) - Radio({ value: 'item.title', group: 'radioGroup' }) - .size({ width: 16, height: 16 }) - .checked(this.curSelectNumber === index) - .hitTestBehavior(HitTestMode.None) - .id(String(index)) - .onFocus(() => { - // this.curSelectNumber === index - if (index == FIRST_ITEM_INDEX) { - } else if (index == this.radioContent.length - 1) { - } - }) - }.constraintSize({ minHeight: LIST_MIN_HEIGHT }).clip(false) - .padding({ top: 13, bottom: 13 }) + .height('15%') + .textAlign(TextAlign.Center) + .fontSize(20) + + Blank() + + Row({ space: 5 }){ + Button({ type: ButtonType.Normal, stateEffect: true }) { + Column() { + Text($r('app.string.USB_func_charge')) + .fontSize(20) + .fontColor(0xffffff) + .textAlign(TextAlign.Center) + .width('100%') + } + } + .height('100%') + .width('30%') + .borderRadius(10) + .onClick(() => { + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); + let tmpChooseNumber: number = USBSERVICESWITCH_ID_CHARGE_ONLY; + usbServiceSwitch.serviceChoose(tmpChooseNumber); + notificationUtil.publishChooseNotify(tmpChooseNumber); + this.curSelectNumber = tmpChooseNumber; + + console.log(TAG + 'close pop up window: charge only'); + this.customDialogController.close(); + windowClass.hide((err: BusinessError) => { + const errCode: number = err.code; + if (errCode) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; } - .type(ButtonType.Normal) - .borderRadius($r('sys.float.corner_radius_level8')) - .buttonStyle(ButtonStyleMode.TEXTUAL) - .padding({left: 12, right: 12}) - .onClick(() => { - item.action && item.action(); - }) - if (index < this.radioContent.length - 1) { - Divider() - .color($r('sys.color.comp_divider')) - .padding({left: 12, right: 12}) + console.info('Succeeded in hiding the window.'); + }); + }) + .borderColor(Color.Red) + .borderWidth(this.curSelectNumber === USBSERVICESWITCH_ID_CHARGE_ONLY ? 2 : 0) + + Button({ type: ButtonType.Normal, stateEffect: true }) { + Column() { + Text($r('app.string.USB_func_mtp')) + .fontSize(20) + .fontColor(0xffffff) + .textAlign(TextAlign.Center) + } + } + .height('100%') + .width('30%') + .borderRadius(10) + .onClick(() => { + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); + let tmpChooseNumber: number = USBSERVICESWITCH_ID_XFER_FILE; + usbServiceSwitch.serviceChoose(tmpChooseNumber); + notificationUtil.publishChooseNotify(tmpChooseNumber); + this.curSelectNumber = tmpChooseNumber; + + console.log(TAG + 'close pop up window: xfer file'); + this.customDialogController.close(); + windowClass.hide((err: BusinessError) => { + const errCode: number = err.code; + if (errCode) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; } - } + console.info('Succeeded in hiding the window.'); + }); + }) + .borderColor(Color.Red) + .borderWidth(this.curSelectNumber === USBSERVICESWITCH_ID_XFER_FILE ? 2 : 0) + + Button({ type: ButtonType.Normal, stateEffect: true }) { + Column() { + Text($r('app.string.USB_func_ptp')) + .fontSize(20) + .fontColor(0xffffff) + .textAlign(TextAlign.Center) } - }) + } + .height('100%') + .width('30%') + .borderRadius(10) + .onClick(() => { + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); + let tmpChooseNumber: number = USBSERVICESWITCH_ID_XFER_PIC; + usbServiceSwitch.serviceChoose(tmpChooseNumber); + notificationUtil.publishChooseNotify(tmpChooseNumber); + this.curSelectNumber = tmpChooseNumber; + + console.log(TAG + 'close pop up window: xfer pic'); + windowClass.hide((err: BusinessError) => { + const errCode: number = err.code; + if (errCode) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the window.'); + }); + }) + .borderColor(Color.Red) + .borderWidth(this.curSelectNumber === USBSERVICESWITCH_ID_XFER_PIC ? 2 : 0) } - .width('100%') - .clip(false) - .onFocus(() => { - }) - .defaultFocus(true) + .height('60%') - Button({ type: ButtonType.Normal, stateEffect: true }) { + Divider().height('5%') + + Button({ type: ButtonType.Capsule, stateEffect: true }) { Text($r('app.string.USB_hint_cancel')) - .fontSize(16) - .fontColor(0x0000FF) - .fontWeight('Medium') + .fontSize(20) .height('100%') .width('100%') .textAlign(TextAlign.Center) } - .height(40) - .width(296) - .backgroundColor(0xFFFFFF) - .padding({right: 16, left: 16, bottom: 0}) + .height('15%') + .width('90%') + .backgroundColor('#ff9d6b6b') .onClick(() => { console.log(TAG + 'close pop up window: cancel'); - this.destruction(); + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); + notificationUtil.publishChooseNotify(this.curSelectNumber); + this.customDialogController.close(); + + windowClass.hide((err: BusinessError) => { + const errCode: number = err.code; + if (errCode) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the window.'); + }); + }) + + Blank().height(5) } - .width(328) - .height(167) + .height('40%') } destruction() { + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); console.log(TAG + 'destruction') - let session = AppStorage.get('session'); - if (session) { - session.terminateSelf(); - } + this.customDialogController.close() + windowClass.destroyWindow() + let extensionContextCtr: common.ServiceExtensionContext = GlobalThisProxy.getInstance().getContext('extensionAbility') + extensionContextCtr.terminateSelf() } } @Entry @Component struct IndexHapComponent { - private curChoose: number = 0; + private curChoose: number = -1; private content: string = '' private thisWant: string = '' customDialogController: CustomDialogController = new CustomDialogController({ - builder: PopUpWindow({ - curSelectNumber: this.curChoose, - radioContent: [ - { - title: $r('app.string.USB_func_charge'), - action: () => { - let tmpChooseNumber:number = USBSERVICESWITCH_ID_CHARGE_ONLY; - usbServiceSwitch.serviceChoose(tmpChooseNumber); - let session = AppStorage.get('session'); - if (session) { - session.terminateSelf(); - } - } - } - ] - }), + builder: PopUpWindow({ curSelectNumber: this.curChoose }), autoCancel: true, cancel: this.onCancel }); async aboutToAppear() { + let defaultChoose: number = GlobalThisProxy.getInstance().getNumInfo('workWant_defaultChoose'); + let funcSelect: number = GlobalThisProxy.getInstance().getNumInfo('workWant_funcSelect'); + if (defaultChoose) { + this.curChoose = defaultChoose; + console.log(TAG + 'use want defaultChoose: ' + this.curChoose); + } else if (funcSelect) { + this.curChoose = funcSelect; + console.log(TAG + 'use want funcSelect: ' + this.curChoose); + } + + if (this.curChoose !== USBSERVICESWITCH_ID_CHARGE_ONLY && this.curChoose !== USBSERVICESWITCH_ID_XFER_FILE && + this.curChoose !== USBSERVICESWITCH_ID_XFER_PIC) { + this.curChoose = USBSERVICESWITCH_ID_CHARGE_ONLY; + console.log(TAG + 'error, use default: ' + this.curChoose); + } + + notificationUtil.enableNotification(); + + if (this.curChoose === USBSERVICESWITCH_ID_CHARGE_ONLY) { + console.log(TAG + 'aboutToAppear: publish charge only'); + notificationUtil.publishChooseNotify(USBSERVICESWITCH_ID_CHARGE_ONLY); + } else if (this.curChoose === USBSERVICESWITCH_ID_XFER_FILE) { + console.log(TAG + 'aboutToAppear: publish xfer file'); + notificationUtil.publishChooseNotify(USBSERVICESWITCH_ID_XFER_FILE); + } else if (this.curChoose === USBSERVICESWITCH_ID_XFER_PIC) { + console.log(TAG + 'aboutToAppear: publish xfer pic'); + notificationUtil.publishChooseNotify(USBSERVICESWITCH_ID_XFER_PIC); + } else { + console.log(TAG + 'this.curChoose: ' + JSON.stringify(this.curChoose)); + } + if (defaultChoose) { + console.log(TAG + 'first time show window'); + } else if (funcSelect) { + console.log(TAG + 'second time show window'); + } this.customDialogController.open(); } @@ -161,6 +243,7 @@ struct IndexHapComponent { async onPageShow() { console.log(TAG + 'onPageShow, curChoose: ' + this.curChoose); + } async onPageHide() { @@ -168,10 +251,17 @@ struct IndexHapComponent { } async onCancel() { console.log(TAG + 'onCancel'); - let session = AppStorage.get('session'); - if (session) { - session.terminateSelf(); - } + let windowClass: window.Window = window.findWindow('UsbFunctionSwitchWindow'); + this.customDialogController.close(); + + windowClass.hide((err: BusinessError) => { + const errCode: number = err.code; + if (errCode) { + console.error('TAG + Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('TAG + Succeeded in hiding the window.'); + }); } build() { } } diff --git a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/module.json b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/module.json index 6e3af95c..9c44d451 100644 --- a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/module.json +++ b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/module.json @@ -41,8 +41,8 @@ "description": "$string:UsbFunctionSwitchWindowAbility_desc", "icon": "$media:icon", "label": "$string:UsbFunctionSwitchWindowAbility_label", - "exported": true, - "type": "sysDialog/common" + "visible": true, + "type": "service" } ] } diff --git a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/en/element/string.json b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/en/element/string.json index 4b1b9d18..f33fad90 100644 --- a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/en/element/string.json +++ b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/en/element/string.json @@ -38,7 +38,7 @@ }, { "name": "USB_hint", - "value": "USB Connected" + "value": "USB Used" }, { "name": "USB_func_charge", diff --git a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/zh/element/string.json b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/zh/element/string.json index b9ee994d..c04d0a34 100755 --- a/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/zh/element/string.json +++ b/frameworks/dialog/dialog_ui/usb_right_dialog/src/main/resources/zh/element/string.json @@ -38,11 +38,11 @@ }, { "name": "USB_hint", - "value": "USB连接方式" + "value": "USB用于" }, { "name": "USB_func_charge", - "value": "仅充电" + "value": "仅限充电" }, { "name": "USB_func_mtp", diff --git a/services/BUILD.gn b/services/BUILD.gn index ce7f8950..9d57e214 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -107,9 +107,6 @@ ohos_shared_library("usbservice") { defines += [ "USB_NOTIFICATION_ENABLE" ] } - if (usb_manager_feature_pop_up_func_switch_model) { - defines += [ "USB_FUNC_SWITCH_MODE" ] - } subsystem_name = "usb" part_name = "usb_manager" } diff --git a/services/native/include/usb_function_switch_window.h b/services/native/include/usb_function_switch_window.h index de3849b0..c8625fdd 100644 --- a/services/native/include/usb_function_switch_window.h +++ b/services/native/include/usb_function_switch_window.h @@ -48,27 +48,20 @@ public: int32_t Init(); bool PopUpFunctionSwitchWindow(); bool DismissFunctionSwitchWindow(); - int32_t SetCurrentFunctionLabel(int32_t func); - int32_t RemoveCurrentFunctionLabel(); + private: UsbFunctionSwitchWindow(); DISALLOW_COPY_AND_MOVE(UsbFunctionSwitchWindow); - class UsbFuncAbilityConn : public OHOS::AAFwk::AbilityConnectionStub { - void OnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, - int32_t resultCode) override; - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override; - public: - }; + bool GetDefaultChooseFunction(int32_t &defaultChoose); bool ShowFunctionSwitchWindow(int32_t defaultChoose); bool UnShowFunctionSwitchWindow(); + static std::shared_ptr instance_; - sptr usbFuncAbilityConn = nullptr; int32_t windowAction_ = UsbFunctionSwitchWindowAction::FUNCTION_SWITCH_WINDOW_ACTION_DEFAULT; std::mutex opMutex_; const std::string functionSwitchBundleName_ = "com.usb.right"; const std::string functionSwitchExtAbility_ = "UsbFunctionSwitchExtAbility"; - int32_t setCurrentFuncLabel = 0; }; } // namespace USB } // namespace OHOS diff --git a/services/native/src/usb_device_manager.cpp b/services/native/src/usb_device_manager.cpp index aadb99a9..12484ee8 100644 --- a/services/native/src/usb_device_manager.cpp +++ b/services/native/src/usb_device_manager.cpp @@ -200,6 +200,16 @@ void UsbDeviceManager::ProcessFunctionSwitchWindow(int32_t status) { std::shared_ptr window_ = UsbFunctionSwitchWindow::GetInstance(); if (status == ACT_UPDEVICE) { + uint32_t currentFunctionsUint32 = static_cast(currentFunctions_); + uint32_t targetFunction = currentFunctionsUint32; + targetFunction &= ~(UsbSrvSupport::FUNCTION_MTP | UsbSrvSupport::FUNCTION_PTP); + if (targetFunction != currentFunctionsUint32) { + int32_t ret = usbd_->SetCurrentFunctions(targetFunction); + if (ret != UEC_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "restore function from %{public}d to %{public}d failed: %{public}d", + currentFunctions_, targetFunction, ret); + } + } USB_HILOGD(MODULE_USB_SERVICE, "start pop up usb service switch window"); if (!window_->PopUpFunctionSwitchWindow()) { USB_HILOGE(MODULE_USB_SERVICE, "start pop up usb service switch window failed"); diff --git a/services/native/src/usb_function_switch_window.cpp b/services/native/src/usb_function_switch_window.cpp index c13e6f56..22838e3c 100644 --- a/services/native/src/usb_function_switch_window.cpp +++ b/services/native/src/usb_function_switch_window.cpp @@ -20,8 +20,6 @@ #include #include -#include "cJSON.h" - #include "ability_manager_client.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -32,12 +30,7 @@ using namespace OHOS::EventFwk; namespace OHOS { namespace USB { -constexpr int32_t INVALID_USERID = -1; -constexpr int32_t MESSAGE_PARCEL_KEY_SIZE = 3; -#ifdef USB_FUNC_SWITCH_MODE -constexpr int32_t FUNC_LABEL_NOT_NONE = 2; -constexpr int32_t FUNC_LABEL_NONE = 1; -#endif + std::shared_ptr UsbFunctionSwitchWindow::instance_; std::shared_ptr UsbFunctionSwitchWindow::GetInstance() @@ -107,116 +100,30 @@ bool UsbFunctionSwitchWindow::GetDefaultChooseFunction(int32_t &defaultChoose) defaultChoose = UsbFunctionChoose::FUNCTION_CHOOSE_CHARGE_ONLY; return true; } -void UsbFunctionSwitchWindow::UsbFuncAbilityConn::OnAbilityConnectDone(const AppExecFwk::ElementName &element, - const sptr &remoteObject, int32_t resultCode) -{ - USB_HILOGI(MODULE_USB_SERVICE, "OnAbilityConnectDone"); - MessageParcel data; - MessageParcel reply; - MessageOption option; - data.WriteInt32(MESSAGE_PARCEL_KEY_SIZE); - data.WriteString16(u"bundleName"); - data.WriteString16(u"com.usb.right"); - data.WriteString16(u"abilityName"); - data.WriteString16(u"UsbFunctionSwitchExtAbility"); - data.WriteString16(u"parameters"); - cJSON* paramJson = cJSON_CreateObject(); - std::string uiExtensionTypeStr = "sysDialog/common"; - cJSON_AddStringToObject(paramJson, "ability.want.params.uiExtensionType", uiExtensionTypeStr.c_str()); - std::string paramStr(cJSON_PrintUnformatted(paramJson)); - data.WriteString16(Str8ToStr16(paramStr)); - cJSON_Delete(paramJson); - paramJson = nullptr; - - const uint32_t cmdCode = 1; - int32_t ret = remoteObject->SendRequest(cmdCode, data, reply, option); - if (ret != ERR_OK) { - USB_HILOGI(MODULE_USB_SERVICE, "show dialog is failed: %{public}d", ret); - return; - } - - return; -} - -void UsbFunctionSwitchWindow::UsbFuncAbilityConn::OnAbilityDisconnectDone( - const AppExecFwk::ElementName& element, int resultCode) -{ - USB_HILOGI(MODULE_USB_SERVICE, "OnAbilityDisconnectDone"); - return; -} bool UsbFunctionSwitchWindow::ShowFunctionSwitchWindow(int32_t defaultChoose) { USB_HILOGI(MODULE_USB_SERVICE, "show function switch window right now"); - if (usbFuncAbilityConn == nullptr) { - usbFuncAbilityConn = sptr(new (std::nothrow) UsbFuncAbilityConn()); - } - if (setCurrentFuncLabel > 0) { - auto labelSize = RemoveCurrentFunctionLabel(); - USB_HILOGI(MODULE_USB_SERVICE, "set current function trigger attach event, labelSize:%{public}d", labelSize); - return true; - } - auto abilityManager = AAFwk::AbilityManagerClient::GetInstance(); - if (abilityManager == nullptr) { - USB_HILOGE(MODULE_USB_SERVICE, "AbilityManagerClient is nullptr"); + auto abmc = AAFwk::AbilityManagerClient::GetInstance(); + if (abmc == nullptr) { + USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed"); return false; } - AAFwk::Want want; - want.SetElementName("com.ohos.sceneboard", "com.ohos.sceneboard.systemdialog"); - auto ret = abilityManager->ConnectAbility(want, usbFuncAbilityConn, INVALID_USERID); - if (ret != ERR_OK) { - want.SetElementName("com.ohos.systemui", "com.ohos.systemui.dialog"); - ret = abilityManager->ConnectAbility(want, usbFuncAbilityConn, INVALID_USERID); - if (ret != ERR_OK) { - USB_HILOGE(MODULE_USB_SERVICE, "ConnectServiceExtensionAbility systemui failed, ret: %{public}d", ret); - usbFuncAbilityConn = nullptr; - return false; - } + want.SetElementName(functionSwitchBundleName_, functionSwitchExtAbility_); + want.SetParam("defaultChoose", defaultChoose); + + auto ret = abmc->StartAbility(want); + if (ret != UEC_OK) { + USB_HILOGE(MODULE_SERVICE, "StartAbility failed %{public}d", ret); + return false; } - USB_HILOGI(MODULE_SERVICE, "StartAbility success, ret: %{public}d", ret); + USB_HILOGD(MODULE_SERVICE, "StartAbility success"); return true; } -int32_t UsbFunctionSwitchWindow::SetCurrentFunctionLabel(int32_t func) -{ - if (usbFuncAbilityConn == nullptr) { - USB_HILOGW(MODULE_USB_SERVICE, "set label connn is nullptr"); - return 0; - } -#ifdef USB_FUNC_SWITCH_MODE - if (func > 0) { - setCurrentFuncLabel = setCurrentFuncLabel + FUNC_LABEL_NOT_NONE; - } else if (func == 0) { - setCurrentFuncLabel = setCurrentFuncLabel + FUNC_LABEL_NONE; - } -#endif - return setCurrentFuncLabel; -} -int32_t UsbFunctionSwitchWindow::RemoveCurrentFunctionLabel() -{ - if (usbFuncAbilityConn == nullptr) { - USB_HILOGW(MODULE_USB_SERVICE, "remove label connn is nullptr"); - return 0; - } -#ifdef USB_FUNC_SWITCH_MODE - if (setCurrentFuncLabel == 0) { - return 0; - } - setCurrentFuncLabel--; -#endif - return setCurrentFuncLabel; -} bool UsbFunctionSwitchWindow::UnShowFunctionSwitchWindow() { - if (usbFuncAbilityConn == nullptr) { - return true; - } - if (setCurrentFuncLabel > 0) { - auto labelSize = RemoveCurrentFunctionLabel(); - USB_HILOGI(MODULE_USB_SERVICE, "set current function trigger dettach event, %{public}d", labelSize); - return true; - } auto abmc = AAFwk::AbilityManagerClient::GetInstance(); if (abmc == nullptr) { USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed"); diff --git a/services/native/src/usb_service.cpp b/services/native/src/usb_service.cpp index 69c6fd15..8a18c8c3 100644 --- a/services/native/src/usb_service.cpp +++ b/services/native/src/usb_service.cpp @@ -42,7 +42,7 @@ #include "usbd_bulkcallback_impl.h" #include "tokenid_kit.h" #include "accesstoken_kit.h" -#include "usb_function_switch_window.h" + using OHOS::sptr; using namespace OHOS::HDI::Usb::V1_1; @@ -517,13 +517,7 @@ int32_t UsbService::SetCurrentFunctions(int32_t functions) USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr"); return UEC_SERVICE_INVALID_VALUE; } - - ret = usbd_->SetCurrentFunctions(functions); - if (ret == UEC_OK) { - auto labelNum = UsbFunctionSwitchWindow::GetInstance()->SetCurrentFunctionLabel(functions); - USB_HILOGE(MODULE_USB_SERVICE, "UsbService::SetCurrentFunctionLabel size: %{public}d", labelNum); - } - return ret; + return usbd_->SetCurrentFunctions(functions); } int32_t UsbService::UsbFunctionsFromString(std::string_view funcs) @@ -1397,7 +1391,8 @@ bool UsbService::GetBundleInfo(std::string &tokenId, int32_t &userId) OHOS::Security::AccessToken::HapTokenInfo hapTokenInfoRes; int32_t ret = OHOS::Security::AccessToken::AccessTokenKit::GetHapTokenInfo(token, hapTokenInfoRes); if (ret != ERR_OK) { - USB_HILOGE(MODULE_USB_SERVICE, "failed, ret: %{public}d", ret); + USB_HILOGE(MODULE_USB_SERVICE, "failed, ret: %{public}d, id: %{public}u", + ret, (uint32_t)token); return false; } tokenId = USB_DEFAULT_TOKEN; diff --git a/usbmgr.gni b/usbmgr.gni index 83e7dc06..777d7ce5 100644 --- a/usbmgr.gni +++ b/usbmgr.gni @@ -23,7 +23,3 @@ if (defined(global_parts_info) && } else { distributed_notification_enable = false } - -declare_args() { - usb_manager_feature_pop_up_func_switch_model = true -} -- Gitee