1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import UIAbility from '@ohos.app.ability.UIAbility';
17import deviceInfo from '@ohos.deviceInfo';
18import AbilityConstant from '@ohos.app.ability.AbilityConstant'
19import fileio from '@ohos.fileio'
20import inputMethod from '@ohos.inputMethod';
21import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil'
22import display from '@ohos.display';
23import window from '@ohos.window';
24import util from '@ohos.util';
25
26globalThis.rdbStore = undefined
27
28export default class MainAbility extends UIAbility {
29    private Tag = "MainAbility_Tablet"
30
31    onCreate(want, launchParam) {
32        AppStorage.SetOrCreate('context', this.context)
33        // @ts-ignore
34        LogUtil.info(this.Tag, " onCreate, launchReason is " + launchParam.launchReason + ", deviceType" + deviceInfo.deviceType)
35        if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') {
36            AppStorage.SetOrCreate<boolean>('Expand', false)
37            AppStorage.SetOrCreate<boolean>('Choose', true)
38        }
39        if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
40            // 设置迁移标记
41            AppStorage.SetOrCreate<boolean>('IsContinue', true)
42            // 获取对端的迁移数据
43            let Search: boolean = want.parameters["Search"]
44            let continueNote: string = want.parameters["ContinueNote"]
45            let continueSection: number = want.parameters["ContinueSection"]
46            let scrollTopPercent: number = want.parameters["ScrollTopPercent"]
47            let isFocusOnSearch: boolean = want.parameters["isFocusOnSearch"]
48            LogUtil.info(this.Tag, " continueSection : " + continueSection)
49            AppStorage.SetOrCreate<boolean>('Search', Search)
50            AppStorage.SetOrCreate<string>('ContinueNote', continueNote)
51            AppStorage.SetOrCreate<number>('ContinueSection', continueSection)
52            // 使用新的key保存数据,防止迁移过来的数据在使用前被本地操作覆盖
53            AppStorage.SetOrCreate<number>('remoteScrollTopPercent', scrollTopPercent)
54            AppStorage.SetOrCreate<boolean>('isRemoteFocusOnSearch', isFocusOnSearch)
55            // 来自手机的迁移
56            let continueChoose: boolean = want.parameters["ContinueChoose"]
57            if (continueChoose) {
58                LogUtil.info(this.Tag, " continue from phone")
59                AppStorage.SetOrCreate<boolean>('ContinueFromPhone', true)
60            } else {
61                AppStorage.SetOrCreate<boolean>('ContinueFromTablet', true)
62                LogUtil.info(this.Tag, " continue from tablet")
63            }
64            this.context.restoreWindowStage(null)
65        }
66        globalThis.noteContext = this.context
67    }
68
69    onDestroy() {
70        LogUtil.info(this.Tag, " onDestroy")
71    }
72
73    onWindowStageCreate(windowStage) {
74        windowStage.getMainWindow((err, data) => {
75            let windowClass = data
76            try {
77                windowClass.on('windowSizeChange', (data) => {
78                    this.screenBreakPoints(data.width)
79                })
80            } catch (exception) {
81                LogUtil.info(this.Tag, 'windowSizeChange fail')
82            }
83        })
84        window.getLastWindow(this.context, (err, data) => {
85            if (data && data.getWindowProperties()) {
86                let windowWidth = data.getWindowProperties().windowRect.width
87                LogUtil.info(this.Tag, " getLastWindow:" + windowWidth)
88                this.screenBreakPoints(windowWidth)
89            } else {
90                LogUtil.info(this.Tag, "getWindowProperties error:" + JSON.stringify(err))
91            }
92        })
93        LogUtil.info(this.Tag, " onWindowStageCreate")
94        windowStage.setUIContent(this.context, "pages/MyNoteHome", null)
95    }
96
97    onWindowStageDestroy() {
98        LogUtil.info(this.Tag, " onWindowStageDestroy")
99    }
100
101    onForeground() {
102        LogUtil.info(this.Tag, " onForeground")
103    }
104
105    onBackground() {
106        LogUtil.info(this.Tag, " onBackground")
107        // 退出键盘
108        // @ts-ignore
109        inputMethod.getController().stopInputSession();
110    }
111
112    onContinue(wantParam: { [key: string]: any }) {
113        LogUtil.info(this.Tag, " onContinue")
114        // 获取本端的迁移数据
115        let Search = AppStorage.Get<boolean>('Search')
116        let continueNote = AppStorage.Get<string>('ContinueNote')
117        if (continueNote == undefined || continueNote == null) {
118            LogUtil.info(this.Tag, " onContinue, continueNote is error, default [0]")
119            continueNote = JSON.stringify(AppStorage.Get('AllNoteArray')[0].toNoteObject())
120        }
121
122        let continueSection = AppStorage.Get<number>('ContinueSection')
123        if (continueSection == undefined || continueSection == null) {
124            LogUtil.info(this.Tag, " onContinue, continueSection is error, default 3")
125            continueSection = 3
126        }
127        LogUtil.info(this.Tag, " onContinue, continueSection : " + continueSection)
128
129        let scrollTopPercent = AppStorage.Get<number>('ScrollTopPercent')
130        if (scrollTopPercent == undefined || scrollTopPercent == null) {
131            LogUtil.info(this.Tag, " onContinue, scrollTopPercent is error, default 0")
132            scrollTopPercent = 0
133        }
134
135        let isFocusOnSearch = AppStorage.Get<boolean>('isFocusOnSearch')
136        if (isFocusOnSearch == undefined || isFocusOnSearch == null) {
137            LogUtil.info(this.Tag, " onContinue, isFocusOnSearch is error, default true")
138            isFocusOnSearch = true
139        }
140
141        // 保存本端的迁移数据
142        wantParam["Search"] = Search
143        wantParam["ContinueNote"] = continueNote
144        wantParam["ContinueSection"] = continueSection
145        wantParam["ScrollTopPercent"] = scrollTopPercent
146        wantParam["isFocusOnSearch"] = isFocusOnSearch
147        if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') {
148            wantParam["ContinueChoose"] = true
149        }
150
151        // save img to DisFileDir
152        LogUtil.info(this.Tag, " onContinue, save img to DisFileDir")
153        let continueNoteObj = JSON.parse(continueNote)
154        let srcArray = this.getSrcFromHtml(continueNoteObj.content_text)
155        srcArray.forEach((src: string) => {
156            let lastIndex = src.lastIndexOf('/')
157            if (lastIndex != -1) {
158                let imgName = src.substring(lastIndex + 1)
159                this.writeToDisFileDir(imgName)
160            }
161        })
162        LogUtil.info(this.Tag, " onContinue end")
163        return AbilityConstant.OnContinueResult.AGREE
164    }
165
166    getSrcFromHtml(html: string): any {
167        let srcArray = []
168        if (html == undefined || html == null || html == "") {
169            return srcArray
170        }
171        let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
172        let realHtml
173        if (base64regex.test(html)) {
174            let base64 = new util.Base64Helper
175            realHtml = base64.decodeSync(html).toString()
176        } else {
177            realHtml = html;
178        }
179        let imgReg = /<img[^>]+>/g
180        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
181        let imgArray = realHtml.match(imgReg)
182        if (imgArray != null) {
183            for (let i = 0; i < imgArray.length; i++) {
184                let src = imgArray[i].match(srcReg)
185                if (src != null && src.length > 1) {
186                    LogUtil.info(this.Tag, " getSrcFromHtml, src[1] : " + src[1])
187                    srcArray.push(src[1])
188                }
189            }
190        }
191        return srcArray
192    }
193
194    writeToDisFileDir(fileName: string) {
195        LogUtil.info(this.Tag, " writeToDisFileDir, fileName : " + fileName)
196        let filesDir = this.context.filesDir
197        let srcPath = filesDir + "/" + fileName
198        let distributedFilesDir = this.context.distributedFilesDir
199        let desPath = distributedFilesDir + "/" + fileName
200        try {
201            fileio.copyFileSync(srcPath, desPath)
202            LogUtil.info(this.Tag, " onContinue, writeToDisFileDir, copyFile successfully" + desPath + " " + srcPath)
203        } catch (err) {
204            LogUtil.warn(this.Tag, " onContinue, writeToDisFileDir, copyFile failed : " + err)
205        }
206    }
207
208    screenBreakPoints(data) {
209        let displayClass = null
210        let screenDpi = null
211        displayClass = display.getDefaultDisplaySync()
212        screenDpi = displayClass.densityDPI
213        AppStorage.SetOrCreate('dpi', screenDpi)
214        let windowWidth = data / (screenDpi / 160)
215        LogUtil.debug(this.Tag, " screenBreakPoints windowWidth: " + windowWidth)
216        if (windowWidth >= 320 && windowWidth < 520 || windowWidth < 320) {
217            AppStorage.SetOrCreate('breakPoint', 'sm')
218        } else if (windowWidth >= 520 && windowWidth < 840) {
219            AppStorage.SetOrCreate('breakPoint', 'md')
220        } else if (windowWidth >= 840) {
221            AppStorage.SetOrCreate('breakPoint', 'lg')
222        }
223    }
224}