• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.selectionInput.selectionManager (划词管理)(系统接口)
2
3本模块提供划词管理能力,包括创建窗口、显示窗口、移动窗口、隐藏窗口、销毁窗口、监听鼠标划词事件、获取选中文本等。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 20开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 仅支持集成了划词扩展的应用调用。
9> - 本模块接口为系统接口。
10
11## 导入模块
12
13```ts
14import { selectionManager } from '@kit.BasicServicesKit';
15```
16
17##
18
19## on('selectionCompleted')
20
21on(type: 'selectionCompleted', callback: Callback\<SelectionInfo>): void
22
23订阅划词完成事件。使用callback异步回调。
24
25**系统能力:** SystemCapability.SelectionInput.Selection
26
27**参数:**
28
29| 参数名   | 类型                                        | 必填 | 说明                                           |
30| -------- | ------------------------------------------- | ---- | ---------------------------------------------- |
31| type     | string                                      | 是   | 设置监听类型,固定取值为'selectionCompleted'。 |
32| callback | Callback\<[SelectionInfo](#selectioninfo)> | 是   | 回调函数,返回当前划词信息。       |
33
34**错误码:**
35
36以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
37
38| 错误码ID   | 错误信息                       |
39| ---------- | ----------------------------- |
40| 33600003   | Invalid operation. The selection app is not valid. |
41
42**示例:**
43
44```ts
45import { selectionManager } from '@kit.BasicServicesKit';
46
47try {
48  selectionManager.on('selectionCompleted', (info: selectionManager.SelectionInfo) => {
49    console.info(`SelectionInfo text: ${info.text}`);
50  });
51} catch (err) {
52  console.error(`Failed to register selectionCompleted callback: ${JSON.stringify(err)}`);
53}
54```
55
56## off('selectionCompleted')
57
58off(type: 'selectionCompleted', callback?: Callback\<SelectionInfo>): void
59
60取消订阅划词完成事件。使用callback异步回调。
61
62**系统能力:** SystemCapability.SelectionInput.Selection
63
64**参数:**
65
66| 参数名   | 类型                                        | 必填 | 说明                                                         |
67| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
68| type     | string                                      | 是   | 设置监听类型,固定取值为'selectionCompleted'。               |
69| callback | Callback\<[SelectionInfo](#selectioninfo)> | 否   | 取消订阅的回调函数。参数不填写时,取消订阅type对应的所有回调事件。 |
70
71**示例:**
72
73```ts
74import { selectionManager } from '@kit.BasicServicesKit';
75
76let selectionChangeCallback = (info: selectionManager.SelectionInfo) => {
77  console.info(`SelectionInfo text: ${info.text}`);
78};
79
80selectionManager.on('selectionCompleted', selectionChangeCallback);
81try {
82  selectionManager.off('selectionCompleted', selectionChangeCallback);
83} catch (err) {
84  console.error(`Failed to unregister selectionCompleted: ${JSON.stringify(err)}`);
85}
86```
87
88## createPanel
89
90createPanel(ctx: Context, info: PanelInfo): Promise\<Panel>
91
92创建划词面板。使用Promise异步回调。
93
94单个划词应用仅允许创建一个[主面板类型](./js-apis-selectionInput-selectionPanel-sys.md)和一个[菜单面板类型](./js-apis-selectionInput-selectionPanel-sys.md)的窗口。
95
96**系统能力:** SystemCapability.SelectionInput.Selection
97
98**参数:**
99
100| 参数名   | 类型        | 必填 | 说明                     |
101| ------- | ----------- | ---- | ------------------------ |
102| ctx     | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | 是   | 当前划词面板依赖的上下文信息。 |
103| info    | [PanelInfo](./js-apis-selectionInput-selectionPanel-sys.md)   | 是   | 划词面板信息。 |
104
105**返回值:**
106| 类型   | 说明                                                                 |
107| ------- | ------------------------------------------------------------------ |
108| Promise\<[Panel](#panel)> | Promise对象,返回当前创建的划词面板对象。  |
109
110**错误码:**
111
112以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
113
114| 错误码ID   | 错误信息                       |
115| ---------- | ----------------------------- |
116| 33600001   | Selection service exception. |
117| 33600003   | Invalid operation. The selection app is not valid. |
118
119**示例:**
120
121```ts
122import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
123import { rpc } from '@kit.IPCKit';
124import { Want } from '@kit.AbilityKit';
125
126class SelectionAbilityStub extends rpc.RemoteObject {
127  constructor(des: string) {
128    super(des);
129  }
130  onRemoteMessageRequest(
131    code: number,
132    data: rpc.MessageSequence,
133    reply: rpc.MessageSequence,
134    options: rpc.MessageOption
135  ): boolean | Promise<boolean> {
136    return true;
137  }
138}
139
140class ServiceExtAbility extends SelectionExtensionAbility {
141  onConnect(want: Want): rpc.RemoteObject {
142    let panelInfo: PanelInfo = {
143      panelType: PanelType.MENU_PANEL,
144      x: 0,
145      y: 0,
146      width: 500,
147      height: 200
148    }
149    selectionManager.createPanel(this.context, panelInfo)
150      .then((panel: selectionManager.Panel) => {
151        console.info('Succeed in creating panel.');
152      }).catch((err: BusinessError) => {
153      console.error(`Failed to create panel: ${JSON.stringify(err)}`);
154    });
155    return new SelectionAbilityStub('remote');
156  }
157}
158export default ServiceExtAbility;
159```
160
161## destroyPanel
162
163destroyPanel(panel: Panel): Promise\<void>
164
165销毁划词面板。使用Promise异步回调。
166
167**系统能力:** SystemCapability.SelectionInput.Selection
168
169**参数:**
170
171| 参数名   | 类型        | 必填 | 说明                     |
172| ---------| ----------- | ---- | ------------------------ |
173| panel    | [Panel](#panel)       | 是   | 要销毁的面板对象。      |
174
175**返回值:**
176| 类型    | 说明                                                                 |
177| ------- | -------------------------------------------------------------------- |
178| Promise\<void> | Promise对象,无返回结果。|
179
180**错误码:**
181
182以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
183
184| 错误码ID   | 错误信息                       |
185| ---------- | ----------------------------- |
186| 33600001   | Selection service exception. |
187
188**示例:**
189
190```ts
191import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
192import { rpc } from '@kit.IPCKit';
193import { Want } from '@kit.AbilityKit';
194
195class SelectionAbilityStub extends rpc.RemoteObject {
196  constructor(des: string) {
197    super(des);
198  }
199  onRemoteMessageRequest(
200    code: number,
201    data: rpc.MessageSequence,
202    reply: rpc.MessageSequence,
203    options: rpc.MessageOption
204  ): boolean | Promise<boolean> {
205    return true;
206  }
207}
208
209class ServiceExtAbility extends SelectionExtensionAbility {
210  onConnect(want: Want): rpc.RemoteObject {
211    let panelInfo: PanelInfo = {
212      panelType: PanelType.MENU_PANEL,
213      x: 0,
214      y: 0,
215      width: 500,
216      height: 200
217    }
218    let selectionPanel: selectionManager.Panel | undefined = undefined;
219
220    selectionManager.createPanel(this.context, panelInfo)
221      .then((panel: selectionManager.Panel) => {
222        console.info('Succeed in creating panel.');
223        selectionPanel = panel;
224        try {
225          if (selectionPanel) {
226            selectionManager.destroyPanel(selectionPanel).then(() => {
227              console.info('Succeed in destroying panel.');
228            }).catch((err: BusinessError) => {
229              console.error(`Failed to destroy panel: ${JSON.stringify(err)}`);
230            });
231          }
232        } catch (err) {
233          console.error(`Failed to destroy panel: ${JSON.stringify(err)}`);
234        }
235      }).catch((err: BusinessError) => {
236      console.error(`Failed to create panel: ${JSON.stringify(err)}`);
237    });
238    return new SelectionAbilityStub('remote');
239  }
240}
241export default ServiceExtAbility;
242```
243
244## SelectionInfo
245
246划词事件信息。
247
248**系统能力:** SystemCapability.SelectionInput.Selection
249
250| 名称      | 类型 | 只读 | 可选 | 说明         |
251| --------- | -------- | ---- | ---- | ------------ |
252| text   	| string   | 否   | 否   | 划词文本。 |
253| selectionType	    | [SelectionType](#selectiontype)   | 否   | 否   | 触发划词类型。 |
254| startDisplayX   	| number   | 否   | 否   | 划词起始位置的屏幕x轴坐标,单位为px。 |
255| startDisplayY   	| number   | 否   | 否   | 划词起始位置的屏幕y轴坐标,单位为px。 |
256| endDisplayX   	| number   | 否   | 否   | 划词结束位置的屏幕x轴坐标,单位为px。 |
257| endDisplayY   	| number   | 否   | 否   | 划词结束位置的屏幕y轴坐标,单位为px。 |
258| startWindowX   	| number   | 否   | 否   | 划词起始位置的窗口x轴坐标,单位为px。 |
259| startWindowY   	| number   | 否   | 否   | 划词起始位置的窗口y轴坐标,单位为px。 |
260| endWindowX   	| number   | 否   | 否   | 划词结束位置的窗口x轴坐标,单位为px。 |
261| endWindowY   	| number   | 否   | 否   | 划词结束位置的窗口y轴坐标,单位为px。 |
262| displayID   	| number   | 否   | 否   | 被划词应用窗口的屏幕ID。 |
263| windowID   	| number   | 否   | 否   | 被划词应用的窗口ID。 |
264| bundleName   	| string   | 否   | 否   | 划词应用的bundleName。 |
265
266## Panel
267
268下列API均需使用[createPanel](#createpanel)获取到Panel实例后,通过实例调用。
269
270### setUiContent
271
272setUiContent(path: string): Promise\<void>
273
274为当前的划词面板加载具体页面内容。使用Promise异步回调。
275
276**系统能力:** SystemCapability.SelectionInput.Selection
277
278**参数:**
279
280| 参数名   | 类型                   | 必填 | 说明     |
281| -------- | ---------------------- | ---- | -------- |
282| path | string | 是   |  要加载到面板中的页面内容的路径,Stage模型下该路径需添加到工程的resources/base/profile/main_pages.json文件中,不支持FA模型。 |
283
284**返回值:**
285
286| 类型   | 说明                             |
287| ------- | ------------------------------ |
288| Promise\<void> | Promise对象,无返回结果。  |
289
290**错误码:**
291
292以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
293
294| 错误码ID   | 错误信息                       |
295| ---------- | ----------------------------- |
296| 33600001   | Selection service exception. |
297| 33600002   | This selection window has been destroyed. |
298
299**示例:**
300
301```ts
302import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
303
304try {
305  selectionPanel.setUiContent('pages/Index').then(() => {
306    console.info('Succeeded in setting the content.');
307  }).catch((err: BusinessError) => {
308    console.error(`Failed to setUiContent: ${JSON.stringify(err)}`);
309  });
310} catch (err) {
311  console.error(`Failed to setUiContent: ${JSON.stringify(err)}`);
312}
313```
314
315### show
316
317show(): Promise\<void>
318
319显示划词面板。使用Promise异步回调。
320
321**系统能力:** SystemCapability.SelectionInput.Selection
322
323**返回值:**
324
325| 类型   | 说明                             |
326| ------- | ------------------------------ |
327| Promise\<void> | Promise对象,无返回结果。  |
328
329**错误码:**
330
331以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
332
333| 错误码ID   | 错误信息                       |
334| ---------- | ----------------------------- |
335| 33600001   | Selection service exception. |
336| 33600002   | This selection window has been destroyed. |
337
338**示例:**
339
340```ts
341import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
342
343selectionPanel.show().then(() => {
344  console.info('Succeeded in showing the panel.');
345}).catch((err: BusinessError) => {
346  console.error(`Failed to show panel: ${JSON.stringify(err)}`);
347});
348```
349
350### hide
351
352hide(): Promise\<void>
353
354隐藏当前划词面板。使用Promise异步回调。
355
356**系统能力:** SystemCapability.SelectionInput.Selection
357
358**返回值:**
359
360| 类型   | 说明                             |
361| ------- | ------------------------------ |
362| Promise\<void> | Promise对象,无返回结果。  |
363
364**错误码:**
365
366以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
367
368| 错误码ID   | 错误信息                       |
369| ---------- | ----------------------------- |
370| 33600001   | Selection service exception. |
371| 33600002   | This selection window has been destroyed. |
372
373**示例:**
374
375```ts
376import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
377
378selectionPanel.hide().then(() => {
379  console.info('Succeeded in hiding the panel.');
380}).catch((err: BusinessError) => {
381  console.error(`Failed to hide panel: ${JSON.stringify(err)}`);
382});
383```
384
385### startMoving
386
387startMoving(): Promise\<void>
388
389使当前划词面板可以随鼠标拖动位置。使用Promise异步回调。
390
391**系统能力:** SystemCapability.SelectionInput.Selection
392
393**返回值:**
394
395| 类型   | 说明                             |
396| ------- | ------------------------------ |
397| Promise\<void> | Promise对象,无返回结果。  |
398
399**错误码:**
400
401以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
402
403| 错误码ID   | 错误信息                       |
404| ---------- | ----------------------------- |
405| 33600001   | Selection service exception. |
406| 33600002   | This selection window has been destroyed. |
407
408**示例:**
409
410```ts
411import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
412
413RelativeContainer() {
414}
415.onTouch((event: TouchEvent) => {
416  if (event.type === TouchType.Down) {
417    if (selectionPanel !== undefined) {
418      selectionPanel.startMoving().then(() => {
419        console.info('Succeeded in startMoving the panel.');
420      }).catch((err: BusinessError) => {
421        console.error(`Failed to startMoving panel: ${JSON.stringify(err)}`);
422      });
423    }
424  }
425})
426```
427
428### moveTo
429
430moveTo(x: number, y: number): Promise\<void>
431
432移动划词面板至屏幕指定位置。使用Promise异步回调。
433
434**系统能力:** SystemCapability.SelectionInput.Selection
435
436**参数:**
437
438| 参数名   | 类型                   | 必填 | 说明     |
439| -------- | ---------------------- | ---- | -------- |
440| x | number | 是   |x轴方向移动的值,单位为px。|
441| y | number | 是   |y轴方向移动的值,单位为px。|
442
443**返回值:**
444
445| 类型   | 说明                             |
446| ------- | ------------------------------ |
447| Promise\<void> | Promise对象,无返回结果。  |
448
449**错误码:**
450
451以下错误码的详细介绍请参见[划词服务错误码](errorcode-selection.md)。
452
453| 错误码ID   | 错误信息                       |
454| ---------- | ----------------------------- |
455| 33600001   | Selection service exception. |
456| 33600002   | This selection window has been destroyed. |
457
458**示例:**
459
460```ts
461import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
462
463try {
464  selectionPanel.moveTo(200, 200).then(() => {
465    console.info('Succeeded in moving the panel.');
466  }).catch((err: BusinessError) => {
467    console.error(`Failed to move panel: ${JSON.stringify(err)}`);
468  });
469} catch (err) {
470  console.error(`Failed to move panel: ${JSON.stringify(err)}`);
471}
472```
473
474### on('destroyed')
475
476on(type: 'destroyed', callback: Callback\<void>): void
477
478订阅划词窗口销毁事件。使用callback异步回调。
479
480**系统能力:** SystemCapability.SelectionInput.Selection
481
482**参数:**
483
484| 参数名   | 类型                                        | 必填 | 说明                                           |
485| -------- | ------------------------------------------- | ---- | ---------------------------------------------- |
486| type     | string                                      | 是   | 设置监听类型,固定取值为'destroyed'。 |
487| callback | Callback\<void> | 是   | 回调函数。       |
488
489**示例:**
490
491```ts
492import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
493
494try {
495  selectionPanel.on('destroyed', () => {
496    console.info('Panel has destroyed.');
497  });
498} catch (err) {
499  console.error(`Failed to register destroyed callback: ${JSON.stringify(err)}`);
500}
501```
502
503### off('destroyed')
504
505off(type: 'destroyed', callback?: Callback\<void>): void
506
507取消订阅划词窗口销毁事件。使用callback异步回调。
508
509**系统能力:** SystemCapability.SelectionInput.Selection
510
511**参数:**
512
513| 参数名   | 类型                                        | 必填 | 说明                                                         |
514| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
515| type     | string                                      | 是   | 设置监听类型,固定取值为'destroyed'。               |
516| callback | Callback\<void> | 否   | 取消订阅的回调函数。参数不填写时,取消订阅type对应的所有回调事件。|
517
518**示例:**
519
520```ts
521import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
522
523try {
524  selectionPanel.off('destroyed');
525} catch (err) {
526  console.error(`Failed to unregister destroyed: ${JSON.stringify(err)}`);
527}
528```
529
530### on('hidden')
531
532on(type: 'hidden', callback: Callback\<void>): void
533
534订阅划词窗口隐藏事件。使用callback异步回调。
535
536**系统能力:** SystemCapability.SelectionInput.Selection
537
538**参数:**
539
540| 参数名   | 类型                                        | 必填 | 说明                                           |
541| -------- | ------------------------------------------- | ---- | ---------------------------------------------- |
542| type     | string                                      | 是   | 设置监听类型,固定取值为'hidden'。 |
543| callback | Callback\<void> | 是   | 回调函数,返回当前划词服务的信息。       |
544
545**示例:**
546
547```ts
548import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
549
550try {
551  selectionPanel.on('hidden', () => {
552    console.info('Panel has hidden.');
553  });
554} catch (err) {
555  console.error(`Failed to register hidden callback: ${JSON.stringify(err)}`);
556}
557```
558
559### off('hidden')
560
561off(type: 'hidden', callback?: Callback\<void>): void
562
563取消订阅划词窗口隐藏事件。使用callback异步回调。
564
565**系统能力:** SystemCapability.SelectionInput.Selection
566
567**参数:**
568
569| 参数名   | 类型                                        | 必填 | 说明                                                         |
570| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
571| type     | string                                      | 是   | 设置监听类型,固定取值为'hidden'。               |
572| callback | Callback\<void> | 否   | 取消订阅的回调函数。参数不填写时,取消订阅type对应的所有回调事件。 |
573
574**示例:**
575
576```ts
577import { selectionManager, BusinessError } from '@kit.BasicServicesKit';
578
579try {
580  selectionPanel.off('hidden');
581} catch (err) {
582  console.error(`Failed to unregister hidden: ${JSON.stringify(err)}`);
583}
584```
585
586## SelectionType
587
588定义触发划词的类型枚举。
589
590**系统能力:** SystemCapability.SelectionInput.Selection
591
592| 名称         | 值 | 说明               |
593| ------------ | -- | ------------------ |
594| MOUSE_MOVE | 1 | 滑动选词类型。 |
595| DOUBLE_CLICK   | 2 | 双击选词类型。 |
596| TRIPLE_CLICK   | 3 | 三击选词类型。 |
597