_LSP.js 107.8 KB
Newer Older
AndroidLeaves's avatar
AndroidLeaves 已提交
1 2
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3
// icon-color: gray; icon-glyph: user-astronaut;
AndroidLeaves's avatar
AndroidLeaves 已提交
4 5 6 7 8 9 10
/**
 * 公众号:杂货万事屋
 * Desc:集合了一些网上各位大神的代码,修改自用,侵权请联系公众号删除
 * Author:LSP
*/

// 当前环境版本号
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
11
const VERSION = 20221215
AndroidLeaves's avatar
AndroidLeaves 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24
// 组件配置文件名
const settingConfigName = 'settings.json';
// 组件默认配置
const defaultConfig = {
  notify: true,
  backgroundGradientColor: '#c93756,#243B55',
  backgroundGradientAngle: '0',
  bgType: '2', // 0:透明,1:在线,2:颜色
  refreshInterval: '30',
};

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
25
class BaseWidget {
AndroidLeaves's avatar
AndroidLeaves 已提交
26

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  constructor(scriptName) {
    //=====================
    this.scriptName = scriptName;
    this.ERRS = [];
    //=====================
  }

  readWidgetSetting = () => {
    try {
      const localFM = this.useFileManager({ useICloud: false });
      let settings = localFM.readJSONCache(settingConfigName);
      if (settings) {
        if (JSON.stringify(settings) == '{}') {
          settings = JSON.parse(JSON.stringify(defaultConfig));
          delete settings.bgType;
AndroidLeaves's avatar
AndroidLeaves 已提交
42
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
        return settings
      }
      const iCloudFM = this.useFileManager({ useICloud: true });
      settings = iCloudFM.readJSONCache(settingConfigName);
      if (settings) {
        if (JSON.stringify(settings) == '{}') {
          settings = JSON.parse(JSON.stringify(defaultConfig));
          delete settings.bgType;
        }
      }
      return settings;
    } catch (error) {
      console.error(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
56
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
57 58
      if (!config.runsInApp) {
        this.notify('配置读取失败', `${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
59 60
      } else {
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
61 62 63
      }
    }
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
64

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
65 66 67 68 69
  writeWidgetSetting = (data) => {
    try {
      this.useFileManager().writeJSONCache(settingConfigName, data);
    } catch (error) {
      console.error(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
70
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
71 72
      if (!config.runsInApp) {
        this.notify('配置写入失败', `${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
73 74
      } else {
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
75 76 77 78 79 80 81 82 83
      }
    }
  }

  removeWidgetSetting = () => {
    try {
      this.useFileManager().cleanWidgetCache();
    } catch (error) {
      console.error(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
84
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
85 86
      if (!config.runsInApp) {
        this.notify('配置移除失败', `${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
87 88
      } else {
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      }
    }
  }

  useFileManager = (options = {}) => {
    try {
      const { useICloud = false, scriptName = this.scriptName } = options;
      const fm = useICloud ? FileManager.iCloud() : FileManager.local();
      const rootDir = fm.joinPath(fm.documentsDirectory(), 'LSP/');

      // 创建根目录
      if (!fm.fileExists(rootDir)) {
        console.log(`✅ 创建LSP根目录`);
        fm.createDirectory(rootDir, true);
        this.logDivider();
      }

      // 创建对应脚本的缓存目录
      const cacheDir = fm.joinPath(rootDir, `${scriptName}/`)
      if (!fm.fileExists(cacheDir)) {
        console.log(`✅ 创建对应脚本缓存目录->${scriptName}`);
        fm.createDirectory(cacheDir, true);
        this.logDivider();
      }

      /**
       * 全路径名
       * @param {*} cacheFileName 
       * @returns 
       */
AndroidLeaves's avatar
AndroidLeaves 已提交
119 120
      const fullFileName = (cacheFileName, root = false) => {
        return `${root ? rootDir : cacheDir}/${cacheFileName}`
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
121 122 123 124 125 126 127 128
      }

      /**
       * 获取缓存文件的上次修改时间
       * @param {string} cacheKey 缓存key
       * @param {object} options 
       * @return 返回上次缓存文件修改的时间戳(单位:秒)
       */
AndroidLeaves's avatar
AndroidLeaves 已提交
129 130
      const getCacheModifyDate = (cacheKey, root = false) => {
        const cacheFileName = fullFileName(cacheKey, root);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
131 132 133
        const fileExists = fm.fileExists(cacheFileName);
        if (fileExists) {
          return Math.floor(fm.modificationDate(cacheFileName).getTime() / 1000);
AndroidLeaves's avatar
AndroidLeaves 已提交
134
        } else {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
135
          return 0;
AndroidLeaves's avatar
AndroidLeaves 已提交
136
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
137
      }
AndroidLeaves's avatar
AndroidLeaves 已提交
138

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152
      /**
       * 清空组件所有缓存
       */
      const cleanWidgetCache = () => {
        console.log(`🚫 移除组件内所有缓存->${cacheDir}`);
        fm.remove(cacheDir);
        this.logDivider();
      }

      /**
      * 保存字符串到本地
      * @param {string} cacheFileName 缓存文件名
      * @param {string} content 缓存内容
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
153 154
      const writeStringCache = (cacheFileName, content, root = false) => {
        fm.writeString(fullFileName(cacheFileName, root), content);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
155 156 157 158 159 160 161
      }

      /**
      * 获取本地缓存字符串
      * @param {string} cacheFileName 缓存文件名
      * @return {string} 本地字符串缓存
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
162 163
      const readStringCache = (cacheFileName, root = false) => {
        const fileName = fullFileName(cacheFileName, root);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176
        const fileExists = fm.fileExists(fileName);
        let cacheString;
        if (fileExists) {
          cacheString = fm.readString(fileName);
        }
        return cacheString;
      }

      /**
      * 获取本地缓存字符串
      * @param {string} cacheFileName 缓存文件名
      * @return {string} 本地字符串缓存
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
177 178
      const readJSONCache = (cacheFileName, root = false) => {
        const fileName = fullFileName(cacheFileName, root);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
        const fileExists = fm.fileExists(fileName);
        let cacheString = '{}';
        if (fileExists) {
          cacheString = fm.readString(fileName);
        }
        return JSON.parse(cacheString);
      }

      /**
      * 保存JSON字符串到本地
      * @param {string} cacheFileName 缓存文件名
      * @param {object} content 缓存对象
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
192 193
      const writeJSONCache = (cacheFileName, content, root = false) => {
        fm.writeString(fullFileName(cacheFileName, root), JSON.stringify(content));
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
194 195 196 197 198 199 200
      }

      /**
      * 保存图片到本地
      * @param {string} cacheFileName 缓存文件名
      * @param {Image} img 缓存图片
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
201 202
      const writeImgCache = (cacheFileName, img, root = false) => {
        fm.writeImage(fullFileName(cacheFileName, root), img);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
203 204 205 206 207 208 209
      }

      /**
      * 获取本地缓存图片
      * @param {string} cacheFileName 缓存文件名
      * @return {Image} 本地图片缓存
      */
AndroidLeaves's avatar
AndroidLeaves 已提交
210 211
      const readImgCache = (cacheFileName, root = false) => {
        const fileName = fullFileName(cacheFileName, root);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
212 213 214 215
        const fileExists = fm.fileExists(fileName);
        let img;
        if (fileExists) {
          img = fm.readImage(fileName);
AndroidLeaves's avatar
AndroidLeaves 已提交
216
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        return img
      }

      return {
        fm,
        rootDir,
        getCacheModifyDate,
        fullFileName,
        cleanWidgetCache,
        writeStringCache,
        readStringCache,
        readJSONCache,
        writeJSONCache,
        writeImgCache,
        readImgCache,
      }
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
236 237 238 239 240
      if (!config.runsInApp) {
        this.notify('文件操作', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253
    }
  }

  saveFile2Scriptable = (fileName, content) => {
    try {
      const { fm } = this.useFileManager({ useICloud: true });
      const hasSuffix = fileName.lastIndexOf(".") + 1;
      const fullFileName = !hasSuffix ? `${fileName}.js` : fileName;
      const filePath = fm.joinPath(fm.documentsDirectory(), fullFileName);
      fm.writeString(filePath, content);
      return true;
    } catch (error) {
      console.error(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
254
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
255 256
      if (!config.runsInApp) {
        this.notify('文件保存', `${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
257 258
      } else {
        throw error;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
      }
    }
  };

  downloadFile2Scriptable = async ({ moduleName, url }) => {
    const req = new Request(url);
    const content = await req.loadString();
    return this.saveFile2Scriptable(`${moduleName}`, content);
  };

  bgType2Text = (bgType) => {
    let typeText = '';
    switch (bgType) {
      case '0':
        typeText += `透明图片背景`;
AndroidLeaves's avatar
AndroidLeaves 已提交
274 275
        break;

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
276 277 278 279 280 281
      case '1':
        typeText += `在线图片背景`;
        break;

      case '2':
        typeText += `颜色背景`;
AndroidLeaves's avatar
AndroidLeaves 已提交
282 283
        break;
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
284 285 286
    return typeText;
  }

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
287
  changeBgMode2OnLineBg = (bgUrl, options = { shadowColor: '#000', shadowColorAlpha: '0', blur: false, darkBlur: true, blurRadius: 30 }) => {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
288 289 290 291 292 293 294 295 296 297 298
    let widgetSetting = this.readWidgetSetting();
    const { bgType, backgroundImageUrl } = widgetSetting
    if (bgType == undefined || (bgType == '1' && backgroundImageUrl == undefined)) {
      this.writeWidgetSetting(
        {
          ...widgetSetting,
          bgType: '1',
          backgroundImageUrl: bgUrl,
          ...options
        }
      )
AndroidLeaves's avatar
AndroidLeaves 已提交
299 300
    }
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313

  notify = async (title, body, url, opts = {}) => {
    const widgetSetting = await this.readWidgetSetting();
    if (widgetSetting.notify) {
      let n = new Notification();
      n = Object.assign(n, opts);
      n.title = title;
      n.body = body;
      if (url) n.openURL = url;
      return await n.schedule();
    } else {
      return null;
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
314
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
315 316 317 318 319

  scaleFontSize = (defaultFontSize, textLength, startLength) => {
    let fontSize = defaultFontSize;
    if (textLength >= startLength) {
      let count = textLength - startLength;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
320
      let loopSize = Math.round(count / 2.0);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
321 322 323 324
      fontSize -= loopSize;
      fontSize = fontSize < 6 ? 6 : fontSize;
    }
    return fontSize;
AndroidLeaves's avatar
AndroidLeaves 已提交
325
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
326 327 328

  logDivider = () => {
    console.log(`@--------------------------------------@`);
AndroidLeaves's avatar
AndroidLeaves 已提交
329
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
330 331 332 333

  splitColors = (color = '') => {
    const colors = typeof color === 'string' ? color.split(',') : []
    return colors;
AndroidLeaves's avatar
AndroidLeaves 已提交
334
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

  getLinearGradientColor = (colors, angle = 0) => {
    try {
      const locations = [];
      const linearColor = new LinearGradient();
      let x = 0, y = 0;
      if (angle < 45) {
        y = 0.5 - 0.5 / 45 * angle;
      } else if (angle < 135) {
        x = 1 / 90 * (angle - 45);
      } else if (angle <= 180) {
        x = 1;
        y = 0.5 / 45 * (angle - 135);
      }
      linearColor.startPoint = new Point(x, y);
      linearColor.endPoint = new Point(1 - x, 1 - y);
      let avg = 1 / (colors.length - 1);
      linearColor.colors = colors.map((item, index) => {
        locations.push(index * avg);
        return new Color(item);
      });
      linearColor.locations = locations;
      return linearColor;
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
361 362 363 364 365
      if (!config.runsInApp) {
        this.notify('渐变色', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
366
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
367
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
368 369 370 371 372 373 374 375

  loadSF2B64 = async (
    icon = 'square.grid.2x2',
    color = '#56A8D6',
    cornerWidth = 42
  ) => {
    const sfImg = await this.drawSFIcon(icon, color, cornerWidth);
    return `data:image/png;base64,${Data.fromPNG(sfImg).toBase64String()}`;
AndroidLeaves's avatar
AndroidLeaves 已提交
376
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

  drawSFIcon = async (
    icon = 'square.grid.2x2',
    color = '#e8e8e8',
    cornerWidth = 42
  ) => {
    try {
      let sf = SFSymbol.named(icon);
      if (sf == null) {
        sf = SFSymbol.named('scribble');
      }
      sf.applyFont(Font.mediumSystemFont(30));
      const imgData = Data.fromPNG(sf.image).toBase64String();
      const html = `
    <img id="sourceImg" src="data:image/png;base64,${imgData}" />
    <img id="silhouetteImg" src="" />
    <canvas id="mainCanvas" />
    `
      const js = `
    var canvas = document.createElement("canvas");
    var sourceImg = document.getElementById("sourceImg");
    var silhouetteImg = document.getElementById("silhouetteImg");
    var ctx = canvas.getContext('2d');
    var size = sourceImg.width > sourceImg.height ? sourceImg.width : sourceImg.height;
    canvas.width = size;
    canvas.height = size;
    ctx.drawImage(sourceImg, (canvas.width - sourceImg.width) / 2, (canvas.height - sourceImg.height) / 2);
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var pix = imgData.data;
    //convert the image into a silhouette
    for (var i=0, n = pix.length; i < n; i+= 4){
      //set red to 0
      pix[i] = 255;
      //set green to 0
      pix[i+1] = 255;
      //set blue to 0
      pix[i+2] = 255;
      //retain the alpha value
      pix[i+3] = pix[i+3];
    }
    ctx.putImageData(imgData,0,0);
    silhouetteImg.src = canvas.toDataURL();
    output=canvas.toDataURL()
    `

      let wv = new WebView();
      await wv.loadHTML(html);
      const base64Image = await wv.evaluateJavaScript(js);
      const iconImage = await new Request(base64Image).loadImage();
      const size = new Size(160, 160);
      const ctx = new DrawContext();
      ctx.opaque = false;
      ctx.respectScreenScale = true;
      ctx.size = size;
      const path = new Path();
      const rect = new Rect(0, 0, size.width, size.width);

      path.addRoundedRect(rect, cornerWidth, cornerWidth);
      path.closeSubpath();
      ctx.setFillColor(new Color(color));
      ctx.addPath(path);
      ctx.fillPath();
      const rate = 36;
      const iw = size.width - rate;
      const x = (size.width - iw) / 2;
      ctx.drawImageInRect(iconImage, new Rect(x, x, iw, iw));
      return ctx.getImage();
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
447 448 449 450 451
      if (!config.runsInApp) {
        await this.notify('icon绘制', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
452
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
453
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

  drawTextWithCustomFont = async (fontUrl, text, fontSize, textColor, option = { lineLimit: 1, align: "center", rowSpacing: 8 }) => {
    try {
      const font = new CustomFont(new WebView(), {
        fontFamily: 'customFont', // 字体名称
        fontUrl: fontUrl, // 字体地址
        timeout: 60000, // 加载字体的超时时间
      }) // 创建字体
      await font.load() // 加载字体
      const image = await font.drawText(text, {
        fontSize: fontSize, // 字体大小
        textWidth: 0, // 文本宽度
        textColor: textColor, // 文本颜色
        scale: 2, // 缩放因子
        ...option
      })
      return image;
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
475
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
476 477 478 479

  base64Encode = (str) => {
    const data = Data.fromString(str);
    return data.toBase64String();
AndroidLeaves's avatar
AndroidLeaves 已提交
480
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
481 482 483 484 485 486 487 488

  base64Decode = (b64) => {
    const data = Data.fromBase64String(b64);
    if (data) {
      return data.toRawString();
    } else {
      return b64;
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
489
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678

  md5 = (str) => {
    function d(n, t) {
      var r = (65535 & n) + (65535 & t);
      return (((n >> 16) + (t >> 16) + (r >> 16)) << 16) | (65535 & r);
    }

    function f(n, t, r, e, o, u) {
      return d(((c = d(d(t, n), d(e, u))) << (f = o)) | (c >>> (32 - f)), r);
      var c, f;
    }

    function l(n, t, r, e, o, u, c) {
      return f((t & r) | (~t & e), n, t, o, u, c);
    }

    function v(n, t, r, e, o, u, c) {
      return f((t & e) | (r & ~e), n, t, o, u, c);
    }

    function g(n, t, r, e, o, u, c) {
      return f(t ^ r ^ e, n, t, o, u, c);
    }

    function m(n, t, r, e, o, u, c) {
      return f(r ^ (t | ~e), n, t, o, u, c);
    }

    function i(n, t) {
      var r, e, o, u;
      (n[t >> 5] |= 128 << t % 32), (n[14 + (((t + 64) >>> 9) << 4)] = t);
      for (
        var c = 1732584193,
        f = -271733879,
        i = -1732584194,
        a = 271733878,
        h = 0;
        h < n.length;
        h += 16
      )
        (c = l((r = c), (e = f), (o = i), (u = a), n[h], 7, -680876936)),
          (a = l(a, c, f, i, n[h + 1], 12, -389564586)),
          (i = l(i, a, c, f, n[h + 2], 17, 606105819)),
          (f = l(f, i, a, c, n[h + 3], 22, -1044525330)),
          (c = l(c, f, i, a, n[h + 4], 7, -176418897)),
          (a = l(a, c, f, i, n[h + 5], 12, 1200080426)),
          (i = l(i, a, c, f, n[h + 6], 17, -1473231341)),
          (f = l(f, i, a, c, n[h + 7], 22, -45705983)),
          (c = l(c, f, i, a, n[h + 8], 7, 1770035416)),
          (a = l(a, c, f, i, n[h + 9], 12, -1958414417)),
          (i = l(i, a, c, f, n[h + 10], 17, -42063)),
          (f = l(f, i, a, c, n[h + 11], 22, -1990404162)),
          (c = l(c, f, i, a, n[h + 12], 7, 1804603682)),
          (a = l(a, c, f, i, n[h + 13], 12, -40341101)),
          (i = l(i, a, c, f, n[h + 14], 17, -1502002290)),
          (c = v(
            c,
            (f = l(f, i, a, c, n[h + 15], 22, 1236535329)),
            i,
            a,
            n[h + 1],
            5,
            -165796510,
          )),
          (a = v(a, c, f, i, n[h + 6], 9, -1069501632)),
          (i = v(i, a, c, f, n[h + 11], 14, 643717713)),
          (f = v(f, i, a, c, n[h], 20, -373897302)),
          (c = v(c, f, i, a, n[h + 5], 5, -701558691)),
          (a = v(a, c, f, i, n[h + 10], 9, 38016083)),
          (i = v(i, a, c, f, n[h + 15], 14, -660478335)),
          (f = v(f, i, a, c, n[h + 4], 20, -405537848)),
          (c = v(c, f, i, a, n[h + 9], 5, 568446438)),
          (a = v(a, c, f, i, n[h + 14], 9, -1019803690)),
          (i = v(i, a, c, f, n[h + 3], 14, -187363961)),
          (f = v(f, i, a, c, n[h + 8], 20, 1163531501)),
          (c = v(c, f, i, a, n[h + 13], 5, -1444681467)),
          (a = v(a, c, f, i, n[h + 2], 9, -51403784)),
          (i = v(i, a, c, f, n[h + 7], 14, 1735328473)),
          (c = g(
            c,
            (f = v(f, i, a, c, n[h + 12], 20, -1926607734)),
            i,
            a,
            n[h + 5],
            4,
            -378558,
          )),
          (a = g(a, c, f, i, n[h + 8], 11, -2022574463)),
          (i = g(i, a, c, f, n[h + 11], 16, 1839030562)),
          (f = g(f, i, a, c, n[h + 14], 23, -35309556)),
          (c = g(c, f, i, a, n[h + 1], 4, -1530992060)),
          (a = g(a, c, f, i, n[h + 4], 11, 1272893353)),
          (i = g(i, a, c, f, n[h + 7], 16, -155497632)),
          (f = g(f, i, a, c, n[h + 10], 23, -1094730640)),
          (c = g(c, f, i, a, n[h + 13], 4, 681279174)),
          (a = g(a, c, f, i, n[h], 11, -358537222)),
          (i = g(i, a, c, f, n[h + 3], 16, -722521979)),
          (f = g(f, i, a, c, n[h + 6], 23, 76029189)),
          (c = g(c, f, i, a, n[h + 9], 4, -640364487)),
          (a = g(a, c, f, i, n[h + 12], 11, -421815835)),
          (i = g(i, a, c, f, n[h + 15], 16, 530742520)),
          (c = m(
            c,
            (f = g(f, i, a, c, n[h + 2], 23, -995338651)),
            i,
            a,
            n[h],
            6,
            -198630844,
          )),
          (a = m(a, c, f, i, n[h + 7], 10, 1126891415)),
          (i = m(i, a, c, f, n[h + 14], 15, -1416354905)),
          (f = m(f, i, a, c, n[h + 5], 21, -57434055)),
          (c = m(c, f, i, a, n[h + 12], 6, 1700485571)),
          (a = m(a, c, f, i, n[h + 3], 10, -1894986606)),
          (i = m(i, a, c, f, n[h + 10], 15, -1051523)),
          (f = m(f, i, a, c, n[h + 1], 21, -2054922799)),
          (c = m(c, f, i, a, n[h + 8], 6, 1873313359)),
          (a = m(a, c, f, i, n[h + 15], 10, -30611744)),
          (i = m(i, a, c, f, n[h + 6], 15, -1560198380)),
          (f = m(f, i, a, c, n[h + 13], 21, 1309151649)),
          (c = m(c, f, i, a, n[h + 4], 6, -145523070)),
          (a = m(a, c, f, i, n[h + 11], 10, -1120210379)),
          (i = m(i, a, c, f, n[h + 2], 15, 718787259)),
          (f = m(f, i, a, c, n[h + 9], 21, -343485551)),
          (c = d(c, r)),
          (f = d(f, e)),
          (i = d(i, o)),
          (a = d(a, u));
      return [c, f, i, a];
    }

    function a(n) {
      for (var t = '', r = 32 * n.length, e = 0; e < r; e += 8)
        t += String.fromCharCode((n[e >> 5] >>> e % 32) & 255);
      return t;
    }

    function h(n) {
      var t = [];
      for (t[(n.length >> 2) - 1] = void 0, e = 0; e < t.length; e += 1)
        t[e] = 0;
      for (var r = 8 * n.length, e = 0; e < r; e += 8)
        t[e >> 5] |= (255 & n.charCodeAt(e / 8)) << e % 32;
      return t;
    }

    function e(n) {
      for (var t, r = '0123456789abcdef', e = '', o = 0; o < n.length; o += 1)
        (t = n.charCodeAt(o)),
          (e += r.charAt((t >>> 4) & 15) + r.charAt(15 & t));
      return e;
    }

    function r(n) {
      return unescape(encodeURIComponent(n));
    }

    function o(n) {
      return a(i(h((t = r(n))), 8 * t.length));
      var t;
    }

    function u(n, t) {
      return (function (n, t) {
        var r,
          e,
          o = h(n),
          u = [],
          c = [];
        for (
          u[15] = c[15] = void 0,
          16 < o.length && (o = i(o, 8 * n.length)),
          r = 0;
          r < 16;
          r += 1
        )
          (u[r] = 909522486 ^ o[r]), (c[r] = 1549556828 ^ o[r]);
        return (
          (e = i(u.concat(h(t)), 512 + 8 * t.length)), a(i(c.concat(e), 640))
        );
      })(r(n), r(t));
    }

    function t(n, t, r) {
      return t ? (r ? u(t, n) : e(u(t, n))) : r ? o(n) : e(o(n));
    }

    return t(str);
AndroidLeaves's avatar
AndroidLeaves 已提交
679
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
680 681 682

  rerunWidget = (scriptName = this.scriptName) => {
    Safari.open(`scriptable:///run/${encodeURIComponent(scriptName)}`);
AndroidLeaves's avatar
AndroidLeaves 已提交
683
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
684 685 686

  getCurrentTimeStamp = () => {
    return Math.floor(new Date().getTime() / 1000);
AndroidLeaves's avatar
AndroidLeaves 已提交
687
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
688 689 690 691 692 693

  getDateStr = (date, formatter = "yyyy年MM月d日 EEE", locale = "zh_cn") => {
    const df = new DateFormatter();
    df.locale = locale;
    df.dateFormat = formatter;
    return df.string(date);
AndroidLeaves's avatar
AndroidLeaves 已提交
694
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
695 696 697 698

  /**
  * Http Get 请求接口
  * @param {string} url 请求的url
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
699
  * @param {bool} jsonFormat 返回数据是否为json,默认true
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
700 701 702 703 704 705 706 707 708 709
  * @param {object} headers 请求头
  * @param {boolean} logable 是否打印数据,默认true
  * @param {boolean} useICloud 是否使用iCloud
  * @param {string} scriptName 脚本名称
  * @return {string | json | null}
  */
  httpGet = async (url, options = {}) => {
    let data;
    try {
      const defaultOptions = {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
710
        jsonFormat: true,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
711 712 713
        headers: null,
        logable: false,
        useICloud: false,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
714
        useCache: true,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
715 716 717 718 719 720
        scriptName: this.scriptName
      };
      options = {
        ...defaultOptions,
        ...options
      };
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
721 722
      const { jsonFormat, headers, logable, useICloud, useCache, scriptName } = options;

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
723 724 725 726 727
      // 根据URL进行md5生成cacheKey
      const cacheFileName = this.md5(url);
      const ufm = this.useFileManager({ useICloud, scriptName });
      // 读取本地缓存
      const localCache = ufm.readStringCache(cacheFileName);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745

      if (useCache) {
        // 判断是否需要刷新
        const lastCacheTime = ufm.getCacheModifyDate(cacheFileName);
        const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60);
        const canUseCache = localCache != null && localCache.length > 0;
        // 过时且有本地缓存则直接返回本地缓存数据 
        const { refreshInterval = '0' } = this.readWidgetSetting();
        const shouldLoadCache = timeInterval <= Number(refreshInterval) && canUseCache;
        console.log(`⏰ ${this.getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}加入缓存,已缓存 ${lastCacheTime > 0 ? timeInterval : 0}min,缓存${shouldLoadCache ? '未过期' : '已过期'}`);
        if (shouldLoadCache) {
          console.log(`🤖 Get读取缓存:${url}`);
          // 是否打印响应数据
          if (logable) {
            console.log(`🤖 Get请求响应:${localCache}`);
          }
          this.logDivider();
          return jsonFormat ? JSON.parse(localCache) : localCache;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
746 747
        }
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
748

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
749 750 751 752 753 754
      console.log(`🚀 Get在线请求:${url}`);
      let req = new Request(url);
      req.method = 'GET';
      if (headers != null && headers != undefined) {
        req.headers = headers;
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
755
      data = await (jsonFormat ? req.loadJSON() : req.loadString());
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
756 757 758 759
      // 判断数据是否为空(加载失败)
      if (!data && canLoadCache) {
        console.log(`🤖 Get读取缓存:${url}`);
        this.logDivider();
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
760
        return jsonFormat ? JSON.parse(localCache) : localCache;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
761 762
      }
      // 存储缓存
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
763
      ufm.writeStringCache(cacheFileName, jsonFormat ? JSON.stringify(data) : data);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
764 765 766 767
      // 是否打印响应数据
      if (logable) {
        console.log(`🤖 Get请求响应:${JSON.stringify(data)}`);
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
768 769 770
    } catch (error) {
      console.error(`🚫 Get请求失败:${error}${url}`);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
771
      if (!config.runsInApp) {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
772
        await this.notify('网络请求失败', `🚫 ${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
773
      } else {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
774 775
        await this.generateAlert('🚫 GET请求出错', `${error}`, ['确定']);
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
776 777 778 779 780 781 782 783 784 785
      }
    }
    this.logDivider();
    return data;
  }

  /**
  * Http Post 请求接口
  * @param {string} url 请求的url
  * @param {Array} parameterKV 请求参数键值对数组
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
786
  * @param {bool} jsonFormat 返回数据是否为json,默认true
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
787 788 789 790 791 792 793 794 795 796
  * @param {object} headers 请求头
  * @param {boolean} logable 是否打印数据,默认true
  * @param {boolean} useICloud 是否使用iCloud
  * @param {string} scriptName 脚本名称
  * @return {string | json | null}
  */
  httpPost = async (url, parameterKV, options = {}) => {
    let data;
    try {
      const defaultOptions = {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
797
        jsonFormat: true,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
798 799 800
        headers: null,
        logable: false,
        useICloud: false,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
801
        useCache: true,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
802 803 804 805 806 807
        scriptName: Script.name()
      };
      options = {
        ...defaultOptions,
        ...options
      };
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
808
      const { jsonFormat, headers, logable, useICloud, scriptName } = options;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
809

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
810 811 812 813 814
      // 根据URL进行md5生成cacheKey
      const cacheFileName = this.md5(url);
      const ufm = this.useFileManager({ useICloud, scriptName });
      // 读取本地缓存
      const localCache = ufm.readStringCache(cacheFileName);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

      if (useCache) {
        // 判断是否需要刷新
        const lastCacheTime = ufm.getCacheModifyDate(cacheFileName);
        const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60);
        const canUseCache = localCache != null && localCache.length > 0;
        // 过时且有本地缓存则直接返回本地缓存数据 
        const { refreshInterval = '0' } = this.readWidgetSetting();
        const shouldLoadCache = timeInterval <= Number(refreshInterval) && canUseCache;
        console.log(`⏰ ${this.getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}加入缓存,已缓存 ${lastCacheTime > 0 ? timeInterval : 0}min,缓存${shouldLoadCache ? '未过期' : '已过期'}`);
        if (shouldLoadCache) {
          console.log(`🤖 Post读取缓存:${url}`);
          // 是否打印响应数据
          if (logable) {
            console.log(`🤖 Post请求响应:${localCache}`);
          }
          this.logDivider();
          return jsonFormat ? JSON.parse(localCache) : localCache;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
833 834
        }
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
835

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
836 837 838 839 840 841 842 843 844
      console.log(`🚀 Post在线请求:${url}`);
      let req = new Request(url);
      req.method = 'POST';
      if (headers != null && headers != undefined) {
        req.headers = headers;
      }
      for (const parameter of parameterKV) {
        req.addParameterToMultipart(Object.keys(parameter)[0], Object.values(parameter)[0])
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
845
      data = await (jsonFormat ? req.loadJSON() : req.loadString());
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
846 847 848 849
      // 判断数据是否为空(加载失败)
      if (!data && canLoadCache) {
        console.log(`🤖 Post读取缓存:${url}`);
        this.logDivider();
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
850
        return jsonFormat ? JSON.parse(localCache) : localCache;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
851 852
      }
      // 存储缓存
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
853
      ufm.writeStringCache(cacheFileName, jsonFormat ? JSON.stringify(data) : data);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
854 855 856 857 858 859
      // 是否打印响应数据
      if (logable) {
        console.log(`🤖 Post请求响应:${JSON.stringify(data)}`);
      }
    } catch (error) {
      console.error(`🚫 Post请求失败:${error}${url}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
860
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
861 862
      if (!config.runsInApp) {
        await this.notify('网络请求失败', `🚫 ${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
863
      } else {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
864
        await this.generateAlert('🚫 POST请求出错', `${error}`, ['确定']);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
865
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
866 867 868 869
      }
    }
    this.logDivider();
    return data;
AndroidLeaves's avatar
AndroidLeaves 已提交
870
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
871 872 873 874 875 876 877 878 879 880 881

  getSFSymbol = (name, size = 16) => {
    const sf = SFSymbol.named(name)
    if (sf != null) {
      if (size != undefined && size != null) {
        sf.applyFont(Font.systemFont(size))
      }
      return sf.image
    } else {
      return undefined
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
882
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
883 884 885 886 887 888 889 890

  getLocation = async (locale = "zh_cn", options = {}) => {
    // 定位信息
    let locationData = {
      "latitude": undefined,
      "longitude": undefined,
      "locality": undefined,
      "subLocality": undefined
AndroidLeaves's avatar
AndroidLeaves 已提交
891 892 893 894 895 896 897 898 899 900
    };
    const { location = true, longitude, latitude } = this.readWidgetSetting();
    if (!location) {
      locationData.longitude = longitude;
      locationData.latitude = latitude;
      if (longitude == null || longitude == undefined || latitude == null || latitude == undefined) {
        await this.generateAlert('定位信息', '系统定位已关闭\n配置中找不到指定定位信息\n请开关定位后输入定位\n点击左上角关闭脚本重新运行', ['确定']);
        throw new Error('获取定位信息失败,请打开定位或者手动输入定位信息!');
      }
      return locationData;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
901 902 903 904 905 906 907 908 909 910 911
    }
    // 缓存
    const defaultOptions = {
      useICloud: false,
      scriptName: this.scriptName
    };
    options = {
      ...defaultOptions,
      ...options
    };
    const { useICloud, scriptName } = options;
AndroidLeaves's avatar
AndroidLeaves 已提交
912 913
    // 缓存文件
    const cacheFileName = this.md5("lsp-location-cache");
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
914 915 916
    const ufm = this.useFileManager({ useICloud, scriptName });
    try {
      // 读取本地缓存
AndroidLeaves's avatar
AndroidLeaves 已提交
917
      const locationCache = ufm.readStringCache(cacheFileName, true);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
918
      // 判断是否需要刷新
AndroidLeaves's avatar
AndroidLeaves 已提交
919 920
      const lastCacheTime = ufm.getCacheModifyDate(cacheFileName, true);
      const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
      const canUseCache = locationCache != null && locationCache.length > 0;
      const { refreshInterval = '0' } = this.readWidgetSetting();
      const shouldLoadCache = timeInterval <= Number(refreshInterval) && canUseCache;
      console.log(`⏰ ${this.getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}加入缓存,已缓存 ${lastCacheTime > 0 ? timeInterval : 0}min,缓存${shouldLoadCache ? '未过期' : '已过期'}`);
      if (shouldLoadCache) {
        // 读取缓存数据
        console.log(`🤖 读取定位缓存数据:${locationCache}`);
        locationData = JSON.parse(locationCache);
      } else {
        console.log(`📌 开始调用手机定位`);
        const location = await Location.current();
        const geocode = await Location.reverseGeocode(location.latitude, location.longitude, locale);
        locationData.latitude = location.latitude;
        locationData.longitude = location.longitude;
        const geo = geocode[0];
        // 市
        if (locationData.locality == undefined) {
          locationData.locality = geo.locality;
        }
        // 区
        if (locationData.subLocality == undefined) {
          locationData.subLocality = geo.subLocality;
        }
        // 街道
        locationData.street = geo.thoroughfare;
        // 缓存数据
AndroidLeaves's avatar
AndroidLeaves 已提交
947
        ufm.writeStringCache(cacheFileName, JSON.stringify(locationData), true);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
948 949 950
        console.log(`🚀 定位信息:latitude=${location.latitude},longitude=${location.longitude},locality=${locationData.locality},subLocality=${locationData.subLocality},street=${locationData.street}`);
      }
    } catch (error) {
AndroidLeaves's avatar
AndroidLeaves 已提交
951
      console.error(`🚫 定位出错了,${error.toString()}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
952
      // 读取缓存数据
AndroidLeaves's avatar
AndroidLeaves 已提交
953
      const locationCache = ufm.readStringCache(cacheFileName, true);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
954 955 956 957
      console.log(`🤖 读取定位缓存数据:${locationCache}`);
      if (locationCache && locationCache.length > 0) {
        locationData = JSON.parse(locationCache);
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
958
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
959 960
      if (!config.runsInApp) {
        await this.notify('定位出错', `🚫 ${error}`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
961 962
      } else {
        throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
963 964 965 966
      }
    }
    this.logDivider();
    return locationData;
AndroidLeaves's avatar
AndroidLeaves 已提交
967
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
968

AndroidLeaves's avatar
udate  
AndroidLeaves 已提交
969 970
  getSettingValueByKey = (key, defaultValue) => this.readWidgetSetting()[key] ?? defaultValue;

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
971 972
  loadShadowColor2Image = async (img, shadowColor) => {
    try {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
973 974
      let drawContext = new DrawContext()
      drawContext.size = img.size
AndroidLeaves's avatar
AndroidLeaves 已提交
975
      drawContext.respectScreenScale = true
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
976
      // 把图片画上去
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
977
      drawContext.drawImageInRect(img, new Rect(0, 0, img.size['width'], img.size['height']))
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
978
      // 填充蒙版颜色
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
979
      drawContext.setFillColor(shadowColor)
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
980
      // 填充
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
981 982
      drawContext.fillRect(new Rect(0, 0, img.size['width'], img.size['height']))
      return await drawContext.getImage()
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
983 984 985
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
986 987 988 989 990 991
      this.logDivider();
      if (!config.runsInApp) {
        await this.notify('蒙层添加', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
992
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
993
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

  /**
  * 在线图片加载
  * @param {string} url 图片链接
  * @param {string} pointCacheKey 指定缓存key
  * @param {bool} useCache 是否使用缓存
  * @return {Image}
  */
  getImageByUrl = async (url, options = {}) => {
    const { pointCacheKey = null, useCache = true } = options;
    // 缓存
    options = {
      useICloud: false,
      scriptName: this.scriptName,
      ...options,
    };
    const { useICloud, scriptName } = options;
    const ufm = this.useFileManager({ useICloud, scriptName });
    // 根据URL进行md5生成cacheKey
    let cacheFileName = pointCacheKey;
    if (cacheFileName == undefined || cacheFileName == null || cacheFileName.length == 0) {
      cacheFileName = this.md5(url);
    }
    try {
      // 缓存数据
      if (useCache) {
        const cacheImg = ufm.readImgCache(cacheFileName);
        if (cacheImg != undefined && cacheImg != null) {
          console.log(`🤖 返回缓存图片:${url}`);
          this.logDivider();
          return cacheImg;
        }
      }
      console.log(`🚀 在线请求图片:${url}`);
      const req = new Request(url);
      let img = await req.loadImage();
      // 存储到缓存
      ufm.writeImgCache(cacheFileName, img);
      this.logDivider();
      return img;
    } catch (e) {
      this.ERRS.push(e);
      console.error(`🚫 图片加载失败:${e}`);
      // 判断本地是否有缓存,有的话直接返回缓存
      let cacheImg = ufm.readImgCache(cacheFileName);
      if (cacheImg != undefined) {
        console.error(`🚫 图片加载失败,返回缓存图片`);
        this.logDivider();
        return cacheImg;
      }
      // 没有缓存+失败情况下,返回灰色背景
      console.log(`📵 返回默认图片,原链接:${url}`)
      let ctx = new DrawContext();
      ctx.opaque = false;
      ctx.respectScreenScale = true;
      ctx.size = new Size(80, 80);
      ctx.setFillColor(Color.darkGray());
      ctx.fillRect(new Rect(0, 0, 80, 80));
      this.logDivider();
      return await ctx.getImage();
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
1055
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1056

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1057
  carouselIndex = (cacheKey, size) => {
AndroidLeaves's avatar
up  
AndroidLeaves 已提交
1058 1059 1060
    if (size <= 0) {
      return 0;
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1061
    let index = -1;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1062 1063
    if (Keychain.contains(cacheKey)) {
      let cacheString = this.keyGet(cacheKey);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1064 1065 1066 1067
      index = parseInt(cacheString);
    }
    index = index + 1;
    index = index % size;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1068
    this.keySave(cacheKey, `${index}`)
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1069
    return index
AndroidLeaves's avatar
AndroidLeaves 已提交
1070
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1071

AndroidLeaves's avatar
AndroidLeaves 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080
  getRandowArrValue(arr) {
    const key = parseInt(Math.random() * arr.length)
    let item = arr[key]
    if (item == undefined) {
      item = arr[0]
    }
    return item
  }

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1081 1082 1083 1084
  keySave = (cacheKey, cache) => {
    if (cache) {
      Keychain.set(cacheKey, cache);
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
1085
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1086 1087 1088 1089 1090 1091 1092

  keyGet = (cacheKey, defaultValue = '') => {
    if (Keychain.contains(cacheKey)) {
      return Keychain.get(cacheKey);
    } else {
      return defaultValue;
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
1093
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1094 1095 1096 1097 1098 1099 1100

  generateAlert = async (title, message, options) => {
    let alert = new Alert();
    alert.title = title;
    alert.message = `\n${message}`;
    if (!options) {
      throw new Error('generateAlert 方法的 "options" 属性不可为空');
AndroidLeaves's avatar
AndroidLeaves 已提交
1101
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1102 1103
    for (const option of options) {
      alert.addAction(option);
AndroidLeaves's avatar
AndroidLeaves 已提交
1104
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1105 1106
    let response = await alert.presentAlert();
    return response;
AndroidLeaves's avatar
AndroidLeaves 已提交
1107
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

  generateInputAlert = async (options, confirm) => {
    options = {
      cancelText: '取消',
      confirmText: '确定',
      ...options
    };
    const inputAlert = new Alert();
    inputAlert.title = options.title;
    const message = options.message;
    if (message) {
      inputAlert.message = `\n${message}`;
AndroidLeaves's avatar
AndroidLeaves 已提交
1120
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1121 1122 1123 1124 1125
    inputAlert.addAction(options.cancelText);
    inputAlert.addAction(options.confirmText);
    const fieldArr = options.options;
    if (!fieldArr) {
      throw new Error('generateInputAlert 方法的 "options" 属性不可为空')
AndroidLeaves's avatar
AndroidLeaves 已提交
1126
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    for (const option of fieldArr) {
      inputAlert.addTextField(option.hint, option.value);
    }
    let selectIndex = await inputAlert.presentAlert();
    if (selectIndex == 1) {
      const inputObj = [];
      fieldArr.forEach((_, index) => {
        let value = inputAlert.textFieldValue(index);
        inputObj.push({ index, value });
      });
      confirm(inputObj);
AndroidLeaves's avatar
AndroidLeaves 已提交
1138
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1139 1140
    return selectIndex;
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
1141

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
  presentSheet = async (options) => {
    options = {
      showCancel: true,
      cancelText: '取消',
      ...options
    };
    const alert = new Alert();
    if (options.title) {
      alert.title = options.title;
    }
    if (options.message) {
      alert.message = options.message;
    }
    if (!options.options) {
      throw new Error('presentSheet 方法的 "options" 属性不可为空')
    }
    for (const option of options.options) {
      alert.addAction(option.name);
    }
    if (options.showCancel) {
      alert.addCancelAction(options.cancelText);
    }
    return await alert.presentSheet();
  };
AndroidLeaves's avatar
AndroidLeaves 已提交
1166

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  /**
  * 手机各大小组件尺寸
  */
  phoneSizes = () => {
    return {
      // 14 Pro Max
      "2796": { 小号: 510, 中号: 1092, 大号: 1146, 左边: 99, 右边: 681, 顶部: 282, 中间: 918, 底部: 1554 },
      // 14 Pro
      "2556": { 小号: 474, 中号: 1014, 大号: 1062, 左边: 82, 右边: 622, 顶部: 270, 中间: 858, 底部: 1446 },
      // 12/13 Pro Max
      "2778": { 小号: 510, 中号: 1092, 大号: 1146, 左边: 96, 右边: 678, 顶部: 246, 中间: 882, 底部: 1518 },
      // 12/13 and 12/13 Pro
      "2532": { 小号: 474, 中号: 1014, 大号: 1062, 左边: 78, 右边: 618, 顶部: 231, 中间: 819, 底部: 1407 },
      // 11 Pro Max, XS Max
      "2688": { 小号: 507, 中号: 1080, 大号: 1137, 左边: 81, 右边: 654, 顶部: 228, 中间: 858, 底部: 1488 },
      // 11, XR
      "1792": { 小号: 338, 中号: 720, 大号: 758, 左边: 54, 右边: 436, 顶部: 160, 中间: 580, 底部: 1000 },
      // 11 Pro, XS, X, 12 mini
      "2436": {
        x: { 小号: 465, 中号: 987, 大号: 1035, 左边: 69, 右边: 591, 顶部: 213, 中间: 783, 底部: 1353 },
        mini: { 小号: 465, 中号: 987, 大号: 1035, 左边: 69, 右边: 591, 顶部: 231, 中间: 801, 底部: 1371 }
      },
      // Plus phones
      "2208": { 小号: 471, 中号: 1044, 大号: 1071, 左边: 99, 右边: 672, 顶部: 114, 中间: 696, 底部: 1278 },
      // SE2 and 6/6S/7/8
      "1334": { 小号: 296, 中号: 642, 大号: 648, 左边: 54, 右边: 400, 顶部: 60, 中间: 412, 底部: 764 },
      // SE1
      "1136": { 小号: 282, 中号: 584, 大号: 622, 左边: 30, 右边: 332, 顶部: 59, 中间: 399, 底部: 399 },
      // 11 and XR in Display Zoom mode
      "1624": { 小号: 310, 中号: 658, 大号: 690, 左边: 46, 右边: 394, 顶部: 142, 中间: 522, 底部: 902 },
      // Plus in Display Zoom mode
      "2001": { 小号: 444, 中号: 963, 大号: 972, 左边: 81, 右边: 600, 顶部: 90, 中间: 618, 底部: 1146 },
    }
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
1201

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1202 1203 1204 1205 1206 1207 1208
  cropImage = (crop, image) => {
    let draw = new DrawContext();
    let rect = new Rect(crop.x, crop.y, crop.w, crop.h);
    draw.size = new Size(rect.width, rect.height);
    draw.drawImageAtPoint(image, new Point(-rect.x, -rect.y));
    return draw.getImage();
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
1209

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1210 1211
  blurImage = async (img, crop, style, blur = 150) => {
    const js = `
AndroidLeaves's avatar
AndroidLeaves 已提交
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    var mul_table = [
        512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512,
        454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512,
        482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456,
        437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512,
        497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328,
        320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456,
        446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335,
        329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512,
        505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405,
        399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328,
        324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271,
        268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456,
        451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388,
        385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335,
        332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292,
        289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259];
    
    var shg_table = [
        9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
        17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
        19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
        20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
        21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
        21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
        22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
        22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24];

    function stackBlurCanvasRGB(id, top_x, top_y, width, height, radius) {
        if (isNaN(radius) || radius < 1) return;
        radius |= 0;
    
        var canvas = document.getElementById(id);
        var context = canvas.getContext("2d");
        var imageData;
    
        try {
            try {
                imageData = context.getImageData(top_x, top_y, width, height);
            } catch (e) {
                // NOTE: this part is supposedly only needed if you want to work with local files
                // so it might be okay to remove the whole try/catch block and just use
                // imageData = context.getImageData( top_x, top_y, width, height );
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
                    imageData = context.getImageData(top_x, top_y, width, height);
                } catch (e) {
                    alert("Cannot access local image");
                    throw new Error("unable to access local image data: " + e);
                    return;
                }
            }
        } catch (e) {
            alert("Cannot access image");
            throw new Error("unable to access image data: " + e);
        }
    
        var pixels = imageData.data;
    
        var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum,
            r_out_sum, g_out_sum, b_out_sum,
            r_in_sum, g_in_sum, b_in_sum,
            pr, pg, pb, rbs;
    
        var div = radius + radius + 1;
        var w4 = width << 2;
        var widthMinus1 = width - 1;
        var heightMinus1 = height - 1;
        var radiusPlus1 = radius + 1;
        var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2;
    
        var stackStart = new BlurStack();
        var stack = stackStart;
        for (i = 1; i < div; i++) {
            stack = stack.next = new BlurStack();
            if (i == radiusPlus1) var stackEnd = stack;
        }
        stack.next = stackStart;
        var stackIn = null;
        var stackOut = null;
    
        yw = yi = 0;
    
        var mul_sum = mul_table[radius];
        var shg_sum = shg_table[radius];
    
        for (y = 0; y < height; y++) {
            r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;
    
            r_out_sum = radiusPlus1 * (pr = pixels[yi]);
            g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
            b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
    
            r_sum += sumFactor * pr;
            g_sum += sumFactor * pg;
            b_sum += sumFactor * pb;
    
            stack = stackStart;
    
            for (i = 0; i < radiusPlus1; i++) {
                stack.r = pr;
                stack.g = pg;
                stack.b = pb;
                stack = stack.next;
            }
    
            for (i = 1; i < radiusPlus1; i++) {
                p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
                r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i);
                g_sum += (stack.g = (pg = pixels[p + 1])) * rbs;
                b_sum += (stack.b = (pb = pixels[p + 2])) * rbs;
    
                r_in_sum += pr;
                g_in_sum += pg;
                b_in_sum += pb;
    
                stack = stack.next;
            }
    
            stackIn = stackStart;
            stackOut = stackEnd;
            for (x = 0; x < width; x++) {
                pixels[yi] = (r_sum * mul_sum) >> shg_sum;
                pixels[yi + 1] = (g_sum * mul_sum) >> shg_sum;
                pixels[yi + 2] = (b_sum * mul_sum) >> shg_sum;
    
                r_sum -= r_out_sum;
                g_sum -= g_out_sum;
                b_sum -= b_out_sum;
    
                r_out_sum -= stackIn.r;
                g_out_sum -= stackIn.g;
                b_out_sum -= stackIn.b;
    
                p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2;
    
                r_in_sum += (stackIn.r = pixels[p]);
                g_in_sum += (stackIn.g = pixels[p + 1]);
                b_in_sum += (stackIn.b = pixels[p + 2]);
    
                r_sum += r_in_sum;
                g_sum += g_in_sum;
                b_sum += b_in_sum;
    
                stackIn = stackIn.next;
    
                r_out_sum += (pr = stackOut.r);
                g_out_sum += (pg = stackOut.g);
                b_out_sum += (pb = stackOut.b);
    
                r_in_sum -= pr;
                g_in_sum -= pg;
                b_in_sum -= pb;
    
                stackOut = stackOut.next;
                yi += 4;
            }
            yw += width;
        }
    
        for (x = 0; x < width; x++) {
            g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0;
    
            yi = x << 2;
            r_out_sum = radiusPlus1 * (pr = pixels[yi]);
            g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
            b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
    
            r_sum += sumFactor * pr;
            g_sum += sumFactor * pg;
            b_sum += sumFactor * pb;
    
            stack = stackStart;
    
            for (i = 0; i < radiusPlus1; i++) {
                stack.r = pr;
                stack.g = pg;
                stack.b = pb;
                stack = stack.next;
            }
    
            yp = width;
    
            for (i = 1; i <= radius; i++) {
                yi = (yp + x) << 2;
    
                r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i);
                g_sum += (stack.g = (pg = pixels[yi + 1])) * rbs;
                b_sum += (stack.b = (pb = pixels[yi + 2])) * rbs;
    
                r_in_sum += pr;
                g_in_sum += pg;
                b_in_sum += pb;
    
                stack = stack.next;
    
                if (i < heightMinus1) {
                    yp += width;
                }
            }
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
            yi = x;
            stackIn = stackStart;
            stackOut = stackEnd;
            for (y = 0; y < height; y++) {
                p = yi << 2;
                pixels[p] = (r_sum * mul_sum) >> shg_sum;
                pixels[p + 1] = (g_sum * mul_sum) >> shg_sum;
                pixels[p + 2] = (b_sum * mul_sum) >> shg_sum;
    
                r_sum -= r_out_sum;
                g_sum -= g_out_sum;
                b_sum -= b_out_sum;
    
                r_out_sum -= stackIn.r;
                g_out_sum -= stackIn.g;
                b_out_sum -= stackIn.b;
    
                p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2;
    
                r_sum += (r_in_sum += (stackIn.r = pixels[p]));
                g_sum += (g_in_sum += (stackIn.g = pixels[p + 1]));
                b_sum += (b_in_sum += (stackIn.b = pixels[p + 2]));
    
                stackIn = stackIn.next;
    
                r_out_sum += (pr = stackOut.r);
                g_out_sum += (pg = stackOut.g);
                b_out_sum += (pb = stackOut.b);
    
                r_in_sum -= pr;
                g_in_sum -= pg;
                b_in_sum -= pb;
    
                stackOut = stackOut.next;
    
                yi += width;
            }
        }
    
        context.putImageData(imageData, top_x, top_y);
    }

    function BlurStack() {
        this.r = 0;
        this.g = 0;
        this.b = 0;
        this.a = 0;
        this.next = null;
    }
    
    // https://gist.github.com/mjackson/5311256
    function rgbToHsl(r, g, b) {
        r /= 255, g /= 255, b /= 255;
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h, s, l = (max + min) / 2;
        if (max == min) {
            h = s = 0; // achromatic
        } else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        return [h, s, l];
    }

    function hslToRgb(h, s, l) {
        var r, g, b;
        if (s == 0) {
            r = g = b = l; // achromatic
        } else {
            var hue2rgb = function hue2rgb(p, q, t) {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1 / 6) return p + (q - p) * 6 * t;
                if (t < 1 / 2) return q;
                if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                return p;
            }
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
        return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
    }
    
    function lightBlur(hsl) {
        // Adjust the luminance.
        let lumCalc = 0.35 + (0.3 / hsl[2]);
        if (lumCalc < 1) { lumCalc = 1; }
        else if (lumCalc > 3.3) { lumCalc = 3.3; }
        const l = hsl[2] * lumCalc;
    
        // Adjust the saturation. 
        const colorful = 2 * hsl[1] * l;
        const s = hsl[1] * colorful * 1.5;
AndroidLeaves's avatar
AndroidLeaves 已提交
1523
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1524 1525
        return [hsl[0], s, l];
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
1526
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1527 1528 1529 1530
    function darkBlur(hsl) {
        // Adjust the saturation. 
        const colorful = 2 * hsl[1] * hsl[2];
        const s = hsl[1] * (1 - hsl[2]) * 3;
AndroidLeaves's avatar
AndroidLeaves 已提交
1531
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
        return [hsl[0], s, hsl[2]];
    }

    // Set up the canvas.
    const img = document.getElementById("blurImg");
    const canvas = document.getElementById("mainCanvas");
    const w = img.naturalWidth;
    const h = img.naturalHeight;
    canvas.style.width = w + "px";
    canvas.style.height = h + "px";
    canvas.width = w;
    canvas.height = h;
    const context = canvas.getContext("2d");
    context.clearRect(0, 0, w, h);
    context.drawImage(img, 0, 0);
AndroidLeaves's avatar
AndroidLeaves 已提交
1547
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1548 1549 1550
    // Get the image data from the context.
    var imageData = context.getImageData(0, 0, w, h);
    var pix = imageData.data;
AndroidLeaves's avatar
AndroidLeaves 已提交
1551
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1552 1553 1554 1555 1556 1557 1558 1559
    // Set the image function, if any.
    var imageFunc;
    var style = "${style}";
    if (style == "dark") { imageFunc = darkBlur; }
    else if (style == "light") { imageFunc = lightBlur; }
    for (let i = 0; i < pix.length; i += 4) {
        // Convert to HSL.
        let hsl = rgbToHsl(pix[i], pix[i + 1], pix[i + 2]);
AndroidLeaves's avatar
AndroidLeaves 已提交
1560
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1561 1562
        // Apply the image function if it exists.
        if (imageFunc) { hsl = imageFunc(hsl); }
AndroidLeaves's avatar
AndroidLeaves 已提交
1563
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1564 1565
        // Convert back to RGB.
        const rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
AndroidLeaves's avatar
AndroidLeaves 已提交
1566
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
        // Put the values back into the data.
        pix[i] = rgb[0];
        pix[i + 1] = rgb[1];
        pix[i + 2] = rgb[2];
    }

    // Draw over the old image.
    context.putImageData(imageData, 0, 0);
    // Blur the image.
    stackBlurCanvasRGB("mainCanvas", 0, 0, w, h, ${blur});
AndroidLeaves's avatar
AndroidLeaves 已提交
1577
    
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    // Perform the additional processing for dark images.
    if (style == "dark") {
        // Draw the hard light box over it.
        context.globalCompositeOperation = "hard-light";
        context.fillStyle = "rgba(55,55,55,0.2)";
        context.fillRect(0, 0, w, h);
        // Draw the soft light box over it.
        context.globalCompositeOperation = "soft-light";
        context.fillStyle = "rgba(55,55,55,1)";
        context.fillRect(0, 0, w, h);
        // Draw the regular box over it.
        context.globalCompositeOperation = "source-over";
        context.fillStyle = "rgba(55,55,55,0.4)";
        context.fillRect(0, 0, w, h);
        // Otherwise process light images.
    } else if (style == "light") {
        context.fillStyle = "rgba(255,255,255,0.4)";
        context.fillRect(0, 0, w, h);
    }
    // Return a base64 representation.
    canvas.toDataURL();    
    `

    // Convert the images and create the HTML.
    let blurImgData = Data.fromPNG(img).toBase64String()
    let html = `
        <img id="blurImg" src="data:image/png;base64,${blurImgData}" />
        <canvas id="mainCanvas" />
    `

    // Make the web view and get its return value.
    let view = new WebView()
    await view.loadHTML(html)
    let returnValue = await view.evaluateJavaScript(js)

    // Remove the data type from the string and convert to data.
    let imageDataString = returnValue.slice(22)
    let imageData = Data.fromBase64String(imageDataString)

    // Convert to image and crop before returning.
    let imageFromData = Image.fromData(imageData)
    if (crop != null && crop != undefined) {
      return this.cropImage(crop, imageFromData)
    } else {
      return imageFromData
    }
  }

  transparentBg = async () => {
    try {
      if (config.runsInApp) {
        let alertTitle = '背景设置'
        let imgCrop = undefined
        const tips = "小组件透明背景已经设置完成,\n退到桌面刷新/预览组件即可查看效果"
        // Determine if user has taken the screenshot.
        let message = "如需实现透明背景\n长按桌面然后滑到桌面最右边进行截图"
        let options = ["退出进行截图", "继续选择图片"]
        let response = await this.generateAlert(alertTitle, message, options)
        // Return if we need to exit.
        if (response == 0) return null
        // Get screenshot and determine phone size.
        let img = await Photos.fromLibrary()
        let height = img.size.height
        let phone = this.phoneSizes()[height]
        if (!phone) {
          message = "你似乎选择了非iPhone屏幕截图的图像\n或者不支持你的iPhone\n请使用其他图像再试一次!"
          await this.generateAlert(alertTitle, message, ["好的"])
          return null
        }

        const ufm = this.useFileManager();
        const { fm, fullFileName, writeStringCache, readStringCache, writeImgCache } = ufm;

        // Extra setup needed for 2436-sized phones.
        if (height == 2436) {
          let cacheName = "lsp-phone-type"
          const cacheFileName = fullFileName(cacheName);
          const fileExists = fm.fileExists(cacheFileName);
          // If we already cached the phone size, load it.
          if (fileExists) {
            let typeString = readStringCache(cacheFileName)
            phone = phone[typeString]
            // Otherwise, prompt the user.
          } else {
            message = "你使用什么型号的iPhone?"
            let types = ["iPhone 12 mini", "iPhone 11 Pro, XS, or X"]
            let typeIndex = await this.generateAlert(alertTitle, message, types)
            let type = (typeIndex == 0) ? "mini" : "x"
            phone = phone[type]
            writeStringCache(cacheFileName, type)
          }
        }

        // Prompt for widget size and position.
        message = "你想要创建什么尺寸的小部件?"
        let sizes = ["小号", "中号", "大号"]
        let size = await this.generateAlert(alertTitle, message, sizes)
        let widgetSize = sizes[size]

        message = "你想它应用在什么位置?"
        message += (height == 1136 ? " (请注意,你的设备仅支持两行小部件,因此中间和底部选项相同。)" : "")

        // Determine image crop based on phone size.
        let crop = { w: "", h: "", x: "", y: "" }
        if (widgetSize == "小号") {
          crop.w = phone.小号
          crop.h = phone.小号
          let positions = ["顶部 左边", "顶部 右边", "中间 左边", "中间 右边", "底部 左边", "底部 右边"]
          let position = await this.generateAlert(alertTitle, message, positions)
          // Convert the two words into two keys for the phone size dictionary.
          let keys = positions[position].toLowerCase().split(' ')
          crop.y = phone[keys[0]]
          crop.x = phone[keys[1]]
        } else if (widgetSize == "中号") {
          crop.w = phone.中号
          crop.h = phone.小号
          // 中号 and 大号 widgets have a fixed x-value.
          crop.x = phone.左边
          let positions = ["顶部", "中间", "底部"]
          let position = await this.generateAlert(alertTitle, message, positions)
          let key = positions[position].toLowerCase()
          crop.y = phone[key]
        } else if (widgetSize == "大号") {
          crop.w = phone.中号
          crop.h = phone.大号
          crop.x = phone.左边
          let positions = ["顶部", "底部"]
          let position = await this.generateAlert(alertTitle, message, positions)
          // 大号 widgets at the 底部 have the "中间" y-value.
          crop.y = position ? phone.中间 : phone.顶部
        }

        // Prompt for blur style.
        message = "你想要一个完全透明的小部件,还是半透明的模糊效果?"
        let blurOptions = ["透明背景", "浅色模糊", "深色模糊", "完全模糊"]
        let blurred = await this.generateAlert(alertTitle, message, blurOptions)

        // We always need the cropped image.
        imgCrop = this.cropImage(crop, img)

        // If it's blurred, set the blur style.
        if (blurred) {
          const styles = ["", "light", "dark", "none"]
          const style = styles[blurred]
          imgCrop = await this.blurImage(img, crop, style)
        }

        message = tips
        const exportPhotoOptions = ["导出", "完成"]
        const exportToPhoto = await this.generateAlert(alertTitle, message, exportPhotoOptions)

        if (exportToPhoto == 0) {
          Photos.save(imgCrop)
        }

        // 保存图片缓存
        writeImgCache(this.scriptName, imgCrop);
        return true
      }
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1740 1741 1742 1743 1744
      if (!config.runsInApp) {
        await this.notify('透明背景', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    }
  }

  /**
  * 获取组件尺寸大小
  * @param {string} size 组件尺寸【小号】、【中号】、【大号】
  * @param {bool} isIphone12Mini 是否是12mini
  */
  getWidgetSize = (size, isIphone12Mini = false) => {
    // 屏幕缩放比例
    const screenScale = Device.screenScale();
    // 组件宽度
    let phoneWidgetSize = undefined;
    // 手机屏幕高度
    const screenHeight = Device.screenSize().height * screenScale;
    if (screenHeight == 2436) {
      // 2436尺寸的手机有【11 Pro, XS, X】 & 【12 mini】
      if (isIphone12Mini) {
        phoneWidgetSize = this.phoneSizes()[screenHeight].mini;
      } else {
        phoneWidgetSize = this.phoneSizes()[screenHeight].x;
      }
    } else {
      phoneWidgetSize = this.phoneSizes()[screenHeight];
    }
    //
    let width = phoneWidgetSize[size] / screenScale;
    if (size === '大号') {
      width = phoneWidgetSize['中号'] / screenScale;
    }
    //
    let height = phoneWidgetSize['小号'] / screenScale;
    if (size === '大号') {
      height = phoneWidgetSize['大号'] / screenScale;
    }
    //
    return { width, height };
  }

  // *******************常用api信息接口*******************
  /**
  * 获取农历信息
  */
  getLunarInfo = async () => {
    const day = new Date().getDate() - 1;
    // 万年历数据
    const url = "https://wannianrili.51240.com/";
    const headers = {
      "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36"
    };
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1795
    const html = await this.httpGet(url, { jsonFormat: false, headers });
AndroidLeaves's avatar
AndroidLeaves 已提交
1796
    const webview = new WebView();
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1797
    await webview.loadHTML(html);
AndroidLeaves's avatar
AndroidLeaves 已提交
1798
    const getData = `
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
        function getData() {
            try {
                infoLunarText = document.querySelector('div#wnrl_k_you_id_${day}.wnrl_k_you .wnrl_k_you_id_wnrl_nongli').innerText
                holidayText = document.querySelectorAll('div.wnrl_k_zuo div.wnrl_riqi')[${day}].querySelector('.wnrl_td_bzl').innerText
                lunarYearText = document.querySelector('div.wnrl_k_you_id_wnrl_nongli_ganzhi').innerText
                lunarYearText = lunarYearText.slice(0, lunarYearText.indexOf('年') + 1)
                if (infoLunarText.search(holidayText) != -1) {
                    holidayText = ''
                }
            } catch {
                infoLunarText = '*'
                holidayText = '*'
                lunarYearText = '*'
AndroidLeaves's avatar
AndroidLeaves 已提交
1812
            }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1813
            return { infoLunarText: infoLunarText, holidayText: holidayText , lunarYearText: lunarYearText}
AndroidLeaves's avatar
AndroidLeaves 已提交
1814
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
        getData()
    `
    // 节日数据  
    const response = await webview.evaluateJavaScript(getData, false);
    console.log(`🚀 农历数据:${JSON.stringify(response)}`);
    this.logDivider();
    return response
  }

  /**
   * 节假日信息
   * @returns 节假日信息
   */
  holidayInfo = async () => {
    let holiday = { isHoliday: false, lunarDate: '', holiday_cn: '' };
    const url = 'https://api.apihubs.cn/holiday/get?cn=1&size=31';
    const holidayJsonData = await this.httpGet(url);
    if (holidayJsonData.code === 0) {
      const dateStr = getDateStr(new Date(), 'yyyyMMdd');
      const list = holidayJsonData.data.list;
      list.forEach(element => {
        let lunar_date_cn = element.lunar_date_cn;
        let index = lunar_date_cn.lastIndexOf('') + 1;
        holiday.lunarDate = lunar_date_cn.slice(index);
        holiday.holiday_cn = element.holiday_cn;
        if (element.date == dateStr) {
          holiday.isHoliday = element.workday == 2;
        }
      });
    }
    console.log(`🚀 节假日信息:${JSON.stringify(holiday)}`);
    this.logDivider();
    return holiday;
  }
  // ***************************************************

  // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  async getAppViewOptions() {
    return {};
  }

  async run() {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
1858
    const viewOptions = await this.getAppViewOptions();
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1859
    if (config.runsInWidget) {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
1860
      await this.providerWidget(viewOptions.widgetProvider);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1861
    } else {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
1862
      this.renderAppView(viewOptions);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    }
  }

  // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  dismissLoading = (webView) => {
    webView.evaluateJavaScript(
      'window.dispatchEvent(new CustomEvent(\'JWeb\', { detail: { code: \'finishLoading\' } }))',
      false
    );
  }

  insertTextByElementId = (webView, elementId, text) => {
    webView.evaluateJavaScript(
      'document.getElementById("' + elementId + '").innerText="' + text + '"',
      false
    );
  }

  async renderAppView(options = {}) {
    this.logDivider();
AndroidLeaves's avatar
AndroidLeaves 已提交
1884
    console.log(`👉 组件主界面渲染 👇`);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1885 1886 1887 1888
    this.logDivider();
    const {
      isChildLevel = false, // 是否是二级菜单
      subTitle = '', // 二级菜单名称
AndroidLeaves's avatar
AndroidLeaves 已提交
1889
      needLocation = false, // 是否需要定位
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1890 1891 1892 1893 1894 1895
      settingItemFontSize = 16,
      authorNameFontSize = 20,
      authorDescFontSize = 12,
      widgetProvider = { defaultBgType: '2', small: true, medium: true, large: true },
      settingItems = [],
      onItemClick,
AndroidLeaves's avatar
AndroidLeaves 已提交
1896
      onCheckedChange,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1897
      authorAvatar = 'https://gitcode.net/enoyee/scriptable/-/raw/master/img/ic_avatar_lsp.jpg',
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
      authorName = '杂货万事屋',
      authorDesc = '点击查看/添加Scriptable小组件订阅',
      homePage = 'https://gitcode.net/enoyee/scriptable/-/tree/master',
    } = options;
    // 组件配置缓存
    const widgetSetting = this.readWidgetSetting();
    let bgType = widgetSetting.bgType ?? widgetProvider.defaultBgType ?? defaultConfig.bgType;
    // ================== 配置界面样式 ===================
    const style = `
    :root {
AndroidLeaves's avatar
AndroidLeaves 已提交
1908 1909 1910 1911 1912 1913 1914 1915 1916
      --color-primary: #007aff;
      --divider-color: rgba(60,60,67,0.16);
      --card-background: #fff;
      --card-radius: 8px;
      --list-header-color: rgba(60,60,67,0.6);
    }
    * {
      -webkit-user-select: none;
      user-select: none;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
1917 1918
    }
    body {
AndroidLeaves's avatar
AndroidLeaves 已提交
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
      margin: 10px 0;
      -webkit-font-smoothing: antialiased;
      font-family: "SF Pro Display","SF Pro Icons","Helvetica Neue","Helvetica","Arial",sans-serif;
      accent-color: var(--color-primary);
      background: #f6f6f6;
    }
    .list {
      margin: 15px;
    }
    .list__header {
      margin: 0 18px;
      color: var(--list-header-color);
      font-size: 13px;
    }
    .list__body {
      margin-top: 10px;
      background: var(--card-background);
      border-radius: var(--card-radius);
      overflow: hidden;
    }
    .form-item-auth {
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-height: 4em;
      padding: 0.5em 18px;
      position: relative;
    }
    .form-item-auth-name {
      margin: 0px 12px;
      font-size: ${authorNameFontSize}px;
      font-weight: 430;
    }
    .form-item-auth-desc {
      margin: 0px 12px;
      font-size: ${authorDescFontSize}px;
      font-weight: 400;
    }
    .form-label-author-avatar {
      width: 62px;
      height: 62px;
      border-radius:50%;
      border: 1px solid #fb8500;
    }
    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: ${settingItemFontSize}px;
      font-weight: 400;
      min-height: 2.2em;
      padding: 0.5em 18px;
      position: relative;
    }
    .form-label {
      display: flex;
      align-items: center;
    }
    .form-label-img {
      height: 30;
    }
    .form-label-title {
      margin-left: 8px
    }
    .bottom-bg {
      margin: 30px 15px 15px 15px;
    }
    .form-item--link .icon-arrow-right {
      color: #86868b;
    }
    .form-item-right-desc {
      font-size: 13px;
      color: #86868b;
      margin-right: 4px;
    }
    .form-item + .form-item::before {
      content: "";
      position: absolute;
      top: 0;
      left: 20px;
      right: 0;
      border-top: 0.5px solid var(--divider-color);
    }
    .form-item input[type="checkbox"] {
      width: 2em;
      height: 2em;
    }
    input[type='checkbox'][role='switch'] {
      position: relative;
      display: inline-block;
      appearance: none;
      width: 40px;
      height: 24px;
      border-radius: 24px;
      background: #ccc;
      transition: 0.3s ease-in-out;
    }
    input[type='checkbox'][role='switch']::before {
      content: '';
      position: absolute;
      left: 2px;
      top: 2px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #fff;
      transition: 0.3s ease-in-out;
    }
    input[type='checkbox'][role='switch']:checked {
      background: var(--color-primary);
    }
    input[type='checkbox'][role='switch']:checked::before {
      transform: translateX(16px);
    }
    .copyright {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 15px;
      font-size: 10px;
      color: #86868b;
    }
    .copyright a {
      color: #515154;
      text-decoration: none;
    }
    .preview.loading {
      pointer-events: none;
    }
    .icon-loading {
      display: inline-block;
      animation: 1s linear infinite spin;
    }
    .normal-loading {
      display: inline-block;
      animation: 20s linear infinite spin;
    }
    @keyframes spin {
      0% {
        transform: rotate(0);
      }
      100% {
        transform: rotate(1turn);
      }
AndroidLeaves's avatar
AndroidLeaves 已提交
2063
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
    @media (prefers-color-scheme: dark) {
      :root {
        --divider-color: rgba(84,84,88,0.65);
        --card-background: #1c1c1e;
        --list-header-color: rgba(235,235,245,0.6);
      }
      body {
        background: #000;
        color: #fff;
      }
    }`;
AndroidLeaves's avatar
AndroidLeaves 已提交
2075

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2076 2077 2078 2079
    // 组件背景Icon
    const widgetBgIco = await this.loadSF2B64('text.below.photo.fill', '#2176ff');
    // 系统通知Icon
    const notifyIco = await this.loadSF2B64('bell.fill', '#FD2953');
AndroidLeaves's avatar
AndroidLeaves 已提交
2080
    // 系统定位Icon
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2081
    const locationIco = await this.loadSF2B64('location.fill', '#07beb8');
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    // 刷新间隔
    const refresIntervalIco = await this.loadSF2B64('clock.arrow.circlepath', '#30C758');
    // 组件更新
    const widgetUpdateIco = await this.loadSF2B64('icloud.and.arrow.down', '#3a86ff');
    // 清理缓存
    const cleanDataIco = await this.loadSF2B64('trash', '#FF7F50');
    // 小号预览
    const smallPreviewIco = await this.loadSF2B64('app', '#504ED5');
    // 中号预览
    const mediumPreviewIco = await this.loadSF2B64('rectangle', '#504ED5');
    // 大号预览
    const largePreviewIco = await this.loadSF2B64('rectangle.portrait', '#504ED5');
    // icon转换
    for (let index = 0; index < settingItems.length; index++) {
      const item = settingItems[index];
      const icon = item.icon;
      const { name, color } = icon;
      if (typeof icon !== 'string') {
        item.icon = await this.loadSF2B64(name, color);
      }
AndroidLeaves's avatar
AndroidLeaves 已提交
2102
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2103 2104

    const js = `
AndroidLeaves's avatar
AndroidLeaves 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    (() => {
      const settings = JSON.parse('${JSON.stringify(widgetSetting)}')
      const settingItems = JSON.parse('${JSON.stringify(settingItems)}')

      window.invoke = (code, data) => {
        window.dispatchEvent(
          new CustomEvent(
            'JBridge',
            { detail: { code, data } }
          )
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2115 2116 2117
        )
      }

AndroidLeaves's avatar
AndroidLeaves 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
      const notify = document.querySelector('input[name="notify"]')
      notify.checked = settings.notify ?? true
      notify.addEventListener('change', (e) => {
        formData['notify'] = e.target.checked
        invoke('changeSettings', formData)
      })
      
      const location = document.querySelector('input[name="location"]')
      location.checked = settings.location ?? true
      location.addEventListener('change', (e) => {
        formData['location'] = e.target.checked
        invoke('changeSettings', formData)
      })
      
      const formData = {};
      const fragment = document.createDocumentFragment()
      for (const item of settingItems) {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2135
        const value = item.desc ?? settings[item.name] ?? item.default ?? null
AndroidLeaves's avatar
AndroidLeaves 已提交
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
        if(value && item.type != 'cell') {
          formData[item.name] = value;
        }
        const label = document.createElement("label");
        label.className = "form-item";
    
        const divLabel = document.createElement("div");
        divLabel.className = 'form-label';
        label.appendChild(divLabel);
    
        const img = document.createElement("img");
        img.src = item.icon;
        img.className = 'form-label-img';
        divLabel.appendChild(img);
    
        const divTitle = document.createElement("div");
        divTitle.className = 'form-label-title';
        divTitle.innerText = item.label;
        divLabel.appendChild(divTitle);
    
        if (item.type === 'select') {
          const select = document.createElement('select')
          select.className = 'form-item__input'
          select.name = item.name
          select.value = value
          for (const opt of (item.options || [])) {
            const option = document.createElement('option')
            option.value = opt.value
            option.innerText = opt.label
            option.selected = value === opt.value
            select.appendChild(option)
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2167
          }
AndroidLeaves's avatar
AndroidLeaves 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
          select.addEventListener('change', (e) => {
            formData[item.name] = e.target.value
            invoke('changeSettings', formData)
          })
          label.appendChild(select)
        } else if (item.type === 'cell') {
          label.classList.add('form-item--link')

          const divLabel2 = document.createElement("div");
          divLabel2.className = 'form-label';
          label.appendChild(divLabel2);

          const descDiv = document.createElement("div");
          descDiv.setAttribute('id', item.name);
          descDiv.className = 'form-item-right-desc';
          if(item.showDesc != false) {
            descDiv.innerText = value ?? '';
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2185
          }
AndroidLeaves's avatar
AndroidLeaves 已提交
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
          divLabel2.appendChild(descDiv);

          const icon = document.createElement('i')
          icon.className = 'iconfont icon-arrow-right'
          divLabel2.appendChild(icon)
          label.addEventListener('click', (e) => {
            if(item.needLoading) {
              toggleIcoLoading(e);
            }
            let openWeb = item.openWeb
            if(openWeb) {
              invoke('safari', openWeb)
            } else {
              invoke('itemClick', item)
            }
          })
        } else {
          const input = document.createElement("input")
          input.className = 'form-item__input'
          input.name = item.name
          input.type = item.type || "text";
          input.enterKeyHint = 'done'
          input.value = value
          
          if (item.type === 'switch') {
            input.type = 'checkbox'
            input.role = 'switch'
            input.checked = value
          }
    
          if (item.type === 'number') {
            input.inputMode = 'decimal'
          }
    
          if (input.type === 'text') {
            input.size = 12
          }
          
          input.addEventListener("change", (e) => {
            formData[item.name] =
              item.type === 'switch'
              ? e.target.checked
              : item.type === 'number'
              ? Number(e.target.value)
              : e.target.value;
            invoke('changeSettings', formData)
          });
          label.appendChild(input);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2234
        }
AndroidLeaves's avatar
AndroidLeaves 已提交
2235
        fragment.appendChild(label);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2236
      }
AndroidLeaves's avatar
AndroidLeaves 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
      document.getElementById('form').appendChild(fragment)
    
      // 切换ico的loading效果
      const toggleIcoLoading = (e) => {
          const target = e.currentTarget
          target.classList.add('loading')
          const icon = e.currentTarget.querySelector('.iconfont')
          const className = icon.className
          icon.className = 'iconfont icon-loading'
          const listener = (event) => {
            const { code } = event.detail
            if (code === 'finishLoading') {
              target.classList.remove('loading')
              icon.className = className
              window.removeEventListener('JWeb', listener);
            }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2253
          }
AndroidLeaves's avatar
AndroidLeaves 已提交
2254 2255
          window.addEventListener('JWeb', listener)
      };
AndroidLeaves's avatar
AndroidLeaves 已提交
2256

AndroidLeaves's avatar
AndroidLeaves 已提交
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
      for (const btn of document.querySelectorAll('.preview')) {
          btn.addEventListener('click', (e) => {
            toggleIcoLoading(e);
            invoke('preview', e.currentTarget.dataset.size);
          })
      }
    
      document.getElementById('author').addEventListener('click', (e) => {
          toggleIcoLoading(e);
          invoke('author', formData);
      })
      document.getElementById('widgetBg').addEventListener('click', (e) => {
          toggleIcoLoading(e);
          invoke('widgetBg', formData);
      })
      document.getElementById('refreshTime').addEventListener('click', () => invoke('refreshInterval', formData))
      document.getElementById('widgetUpdate').addEventListener('click', (e) => {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2274
          toggleIcoLoading(e);
AndroidLeaves's avatar
AndroidLeaves 已提交
2275 2276 2277 2278
          invoke('widgetUpdate', formData);
      })
      document.getElementById('cleanData').addEventListener('click', () => invoke('cleanData', formData))
    })()`;
AndroidLeaves's avatar
AndroidLeaves 已提交
2279

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2280
    const html = `
AndroidLeaves's avatar
AndroidLeaves 已提交
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
    <html>
      <head>
        <meta name='viewport' content='width=device-width, user-scalable=no'>
        <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3791881_bf011w225k4.css" type="text/css">
        <style>${style}</style>
      </head>
      <body>
      <!--头部个人信息-->  
      <div class="list" style="display:${!isChildLevel ? '' : 'none'}">
        <form class="list__body" action="javascript:void(0);">
          <label id="author" class="form-item-auth form-item--link">
            <div class="form-label">
              <img class="form-label-author-avatar normal-loading" src="${authorAvatar}"/>
              <div>
                <div class="form-item-auth-name">${authorName}</div>
                <div class="form-item-auth-desc">${authorDesc}</div>
              </div>
            </div>
            <i class="iconfont icon-arrow-right"></i>
          </label>
        </form>
      </div>
      <!--组件设置-->  
      <div class="list">
        <div class="list__header">${subTitle ? subTitle : '组件设置'}</div>
        <form id="form" class="list__body" action="javascript:void(0);">
          <label id="widgetBg" class="form-item form-item--link" style="display:${!isChildLevel ? '' : 'none'}">
            <div class="form-label">
              <img class="form-label-img" src="${widgetBgIco}"/>
              <div class="form-label-title">组件背景</div>
            </div>
            <div class="form-label">
              <div id="bgType" class="form-item-right-desc">${this.bgType2Text(bgType)}</div>
              <i class="iconfont icon-arrow-right"></i>
            </div>
          </label>
        </form>
      </div>
      <!--通用设置-->  
      <div class="list" style="display:${!isChildLevel ? '' : 'none'}">
        <div class="list__header">通用设置</div>
        <form class="list__body" action="javascript:void(0);">
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2323
          <label id="notify" class="form-item form-item--link" class="form-item form-item--link">
AndroidLeaves's avatar
AndroidLeaves 已提交
2324 2325 2326 2327 2328 2329
            <div class="form-label">
              <img class="form-label-img" src="${notifyIco}"/>
              <div class="form-label-title">系统通知</div>
            </div>
            <input name="notify" type="checkbox" role="switch" />
          </label>
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2330
          <label id="location" class="form-item form-item--link" style="display:${needLocation ? '' : 'none'}">
AndroidLeaves's avatar
AndroidLeaves 已提交
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
            <div class="form-label">
              <img class="form-label-img" src="${locationIco}"/>
              <div class="form-label-title">自动定位</div>
            </div>
            <input name="location" type="checkbox" role="switch" />
          </label>
          <label id="refreshTime" class="form-item form-item--link">
            <div class="form-label">
              <img class="form-label-img" src="${refresIntervalIco}"/>
              <div class="form-label-title">刷新间隔</div>
            </div>
            <div class="form-label">
              <div id="refreshInterval" class="form-item-right-desc">${widgetSetting.refreshInterval} min</div>
              <i class="iconfont icon-arrow-right"></i>
            </div>
          </label>
          <label id="widgetUpdate" class="form-item form-item--link">
            <div class="form-label">
              <img class="form-label-img" src="${widgetUpdateIco}"/>
              <div class="form-label-title">组件更新</div>
            </div>
            <i class="iconfont icon-arrow-right"></i>
          </label>
          <label id="cleanData" class="form-item form-item--link">
            <div class="form-label">
              <img class="form-label-img" src="${cleanDataIco}"/>
              <div class="form-label-title">清理缓存</div>
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2358 2359
            </div>
            <i class="iconfont icon-arrow-right"></i>
AndroidLeaves's avatar
AndroidLeaves 已提交
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
          </label>
        </form>
      </div>
      <!--组件预览-->  
      <div class="list" style="display:${!isChildLevel ? '' : 'none'}">
        <div class="list__header">组件预览</div>
        <form id="form_preview" class="list__body" action="javascript:void(0);">
          <!--小号组件-->
          <label style="display:${widgetProvider.small ? '' : 'none'}" id="previewSmall" data-size="small" class="preview form-item form-item--link">
            <div class="form-label item-none">
              <img class="form-label-img" class="form-label-img" src="${smallPreviewIco}"/>
              <div class="form-label-title" data-size="small">小尺寸</div>
            </div>
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2373
            <i class="iconfont icon-arrow-right"></i>
AndroidLeaves's avatar
AndroidLeaves 已提交
2374 2375 2376 2377 2378 2379
          </label>
          <!--中号组件-->  
          <label style="display:${widgetProvider.medium ? '' : 'none'}" id="previewMedium" data-size="medium" class="preview form-item form-item--link">
            <div class="form-label">
              <img class="form-label-img" src="${mediumPreviewIco}"/>
              <div class="form-label-title" data-size="medium">中尺寸</div>
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2380
            </div>
AndroidLeaves's avatar
AndroidLeaves 已提交
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
            <i class="iconfont icon-arrow-right"></i>
          </label>
          <!--大号组件-->  
          <label style="display:${widgetProvider.large ? '' : 'none'}" id="previewLarge" data-size="large" class="preview form-item form-item--link">
            <div class="form-label">
              <img class="form-label-img" src="${largePreviewIco}"/>
              <div class="form-label-title" data-size="large">大尺寸</div>
              </div>
            <i class="iconfont icon-arrow-right"></i>
          </label>
        </form>
      </div>
      <footer style="display:${!isChildLevel ? '' : 'none'}">
        <div class="copyright"><div> </div><div>© 界面样式修改自 <a href="javascript:invoke('safari', 'https://www.imarkr.com');">@iMarkr.</a></div></div>
      </footer>
        <script>${js}</script>
      </body>
    </html>`;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2399 2400 2401 2402 2403 2404 2405 2406

    // 预览web
    const previewWebView = new WebView();
    await previewWebView.loadHTML(html, homePage);

    const injectListener = async () => {
      const event = await previewWebView.evaluateJavaScript(
        `(() => {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
          try {
            const controller = new AbortController()
            const listener = (e) => {
              completion(e.detail)
              controller.abort()
            }
            window.addEventListener(
              'JBridge',
              listener,
              { signal: controller.signal }
            )
          } catch (e) {
              alert("预览界面出错:" + e);
              throw new Error("界面处理出错: " + e);
              return;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2422 2423 2424
          }
        })()`, true).catch((err) => {
          console.error(err);
AndroidLeaves's avatar
AndroidLeaves 已提交
2425
          this.ERRS.push(err);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2426 2427 2428 2429 2430
          if (!config.runsInApp) {
            this.notify('APP主界面', `🚫 ${err}`);
          } else {
            throw err
          }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
        });
      ////////////////////////////////////
      let widgetSetting = this.readWidgetSetting();
      let {
        bgType = widgetProvider.defaultBgType ?? widgetSetting.bgType ?? defaultConfig.bgType,
        refreshInterval = defaultConfig.refreshInterval,
        backgroundGradientColor = defaultConfig.backgroundGradientColor,
        backgroundGradientAngle = defaultConfig.backgroundGradientAngle,
      } = widgetSetting;
      const { code, data } = event;
      switch (code) {
        case 'author':
          await this.presentSubscribeWidget();
          this.dismissLoading(previewWebView);
          break

        case 'widgetBg':
          try {
            const index = await this.presentSheet({
              title: '组件背景设置',
              message: '⊱设置该组件背景相关效果⊰',
              options: [
                { name: '透明背景' },
                { name: '在线背景' },
                { name: '颜色背景' },
              ],
            });
            switch (index) {
              case 0:
                const result = await this.transparentBg();
                if (result) {
                  const backgroundImage = this.useFileManager().readImgCache(this.scriptName);
                  if (backgroundImage) {
                    widgetSetting = this.readWidgetSetting();
                    widgetSetting.backgroundImagePath = this.scriptName;
                    bgType = '0';
                  }
                  this.logDivider();
                }
                break;

              case 1:
                await this.generateInputAlert({
                  title: '在线图片背景',
                  message: '填入图片链接设置为组件背景图\n系统自动裁剪中间部分图片使用',
                  options: [{ hint: '🔗 请输入图片链接', value: '' }]
                }, async (inputArr) => {
                  const imgUrl = inputArr[0].value;
                  // 保存配置
                  widgetSetting = this.readWidgetSetting();
                  widgetSetting.backgroundImageUrl = imgUrl;
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2482
                  widgetSetting.backgroundImagePath = this.scriptName;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
                  bgType = '1';
                  this.logDivider();
                  await this.generateAlert('背景设置', '已成功设置组件图片背景\n运行预览即可查看效果', ['确定']);
                });
                break;

              case 2:
                await this.generateInputAlert({
                  title: '颜色背景',
                  message: '各颜色值之间以英文逗号分隔\n自行搜寻对应颜色值(Hex颜色)\n单个颜色则为纯色\n多个颜色则按角度渐变',
                  options: [
                    { hint: '请输入颜色组', value: backgroundGradientColor },
                    { hint: '请输入渐变角度 0~180', value: backgroundGradientAngle },
                  ]
                }, async (inputArr) => {
                  widgetSetting = this.readWidgetSetting();
                  widgetSetting.backgroundGradientColor = inputArr[0].value;
                  widgetSetting.backgroundGradientAngle = inputArr[1].value;
                  delete widgetSetting.backgroundImagePath;
                  delete widgetSetting.backgroundImageUrl;
                  bgType = '2';
                  this.logDivider();
                  await this.generateAlert('背景设置', '已成功设置组件颜色背景\n运行预览即可查看效果', ['确定']);
                });
                break;
            }
            this.writeWidgetSetting({ ...widgetSetting, bgType });
            this.insertTextByElementId(previewWebView, 'bgType', this.bgType2Text(bgType));
          } catch (error) {
            console.error(error);
AndroidLeaves's avatar
AndroidLeaves 已提交
2513
            this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2514 2515 2516 2517 2518
            if (!config.runsInApp) {
              await this.notify('背景处理', `🚫 ${error}`);
            } else {
              throw error
            }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2519 2520 2521
          }
          this.dismissLoading(previewWebView);
          break
AndroidLeaves's avatar
AndroidLeaves 已提交
2522

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
        case 'refreshInterval':
          await this.generateInputAlert({
            title: '刷新间隔',
            message: '设置小组件刷新的时间间距(单位:分钟)\n系统不一定会按照这个时间进行刷新\n该时间内网络请求数据读取缓存反显',
            options: [
              { hint: '⏰ 请输入时间数字', value: refreshInterval },
            ]
          }, async (inputArr) => {
            refreshInterval = inputArr[0].value;
            // 保存配置
            widgetSetting = this.readWidgetSetting();
            widgetSetting.refreshInterval = refreshInterval;
            this.logDivider();
            await this.generateAlert('刷新间隔', '已成功设置组件刷新时间间距', ['确定']);
          });
          // 写入配置缓存
          this.writeWidgetSetting({ ...widgetSetting });
          this.insertTextByElementId(previewWebView, 'refreshInterval', `${refreshInterval} min`);
          break

        case 'widgetUpdate':
          await this.downloadUpdate(
            this.scriptName,
            `https://gitcode.net/enoyee/scriptable/-/raw/master/${encodeURIComponent(this.scriptName)}.js`
          );
          this.dismissLoading(previewWebView);
          break

        case 'cleanData':
          let res = await this.generateAlert('⚠️ 清理缓存', '组件缓存文件(包括组件配置)全部清空\n相当于重置小组件效果', ['取消', '清除']);
          if (res) {
            this.removeWidgetSetting();
            await this.generateAlert('清理缓存', '清理缓存成功\n请重新运行小组件', ['确定']);
            this.rerunWidget();
          }
          break

        case 'preview': {
          widgetSetting = this.readWidgetSetting();
          const widget = await this.render({ widgetSetting, family: data });
          await this.widgetBaseSetting(widget, widgetSetting, bgType);
          // 结束loading
          this.dismissLoading(previewWebView);
          // 预览
          widget[`present${data.replace(data[0], data[0].toUpperCase())}`]();
          break
        }
AndroidLeaves's avatar
AndroidLeaves 已提交
2570

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2571 2572 2573 2574 2575 2576
        case 'safari':
          Safari.openInApp(data, false);
          break

        case 'changeSettings':
          widgetSetting = this.readWidgetSetting();
AndroidLeaves's avatar
AndroidLeaves 已提交
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
          if (data.location == false) {
            await this.generateInputAlert({
              title: '定位信息',
              message: '关闭自动定位需要自己输入定位信息',
              options: [
                { hint: '请输入经度', value: '' },
                { hint: '请输入维度', value: '' },
              ]
            }, async (inputArr) => {
              widgetSetting.longitude = inputArr[0].value;
              widgetSetting.latitude = inputArr[1].value;
            });
          }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2590
          this.writeWidgetSetting({ ...widgetSetting, ...data });
AndroidLeaves's avatar
AndroidLeaves 已提交
2591
          onCheckedChange?.(data, widgetSetting);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2592 2593 2594 2595
          break

        case 'itemClick':
          widgetSetting = this.readWidgetSetting();
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2596
          const { label, name, showDesc, alert, childItems = [] } = data;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
          if (childItems.length > 0) {
            await this.renderAppView({
              isChildLevel: true,
              subTitle: label,
              settingItems: [...childItems]
            });
          } else {
            if (alert) {
              const { title = '', message, options = [] } = alert;
              await this.generateInputAlert({
                title,
                message,
                options
              }, (inputArr) => {
                inputArr.forEach((input, index) => {
                  let value = input.value
                  if (value && value != 'null' && value.length > 0) {
                    let { key } = options[index];
                    widgetSetting[key] = value;
                  }
                });
                this.writeWidgetSetting({ ...widgetSetting });
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2619
                if (options.length == 1 && showDesc) {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
                  this.insertTextByElementId(previewWebView, name, inputArr[0].value);
                }
              });
            }
            ////////////////////////////////////////////////
            const callbackRes = await onItemClick?.(data);
            const { desc, reStart = false } = callbackRes || {};
            if (reStart) {
              rerunWidget();
              return
            }
            if (desc?.value) {
              this.insertTextByElementId(previewWebView, name, desc?.value);
            }
          }
          this.dismissLoading(previewWebView);
          break
      }
      injectListener();
    };
AndroidLeaves's avatar
AndroidLeaves 已提交
2640

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2641 2642
    injectListener().catch((e) => {
      console.error(e);
AndroidLeaves's avatar
AndroidLeaves 已提交
2643
      this.ERRS.push(e);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2644 2645 2646 2647 2648
      if (!config.runsInApp) {
        this.notify('主界面', `🚫 ${e}`);
      } else {
        throw e
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2649
    });
AndroidLeaves's avatar
AndroidLeaves 已提交
2650

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2651
    previewWebView.present();
AndroidLeaves's avatar
AndroidLeaves 已提交
2652 2653
  }

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2654
  // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
AndroidLeaves's avatar
AndroidLeaves 已提交
2655

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2656 2657 2658
  provideDefaultWidget = (family) => {
    //====================================
    const widget = new ListWidget();
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2659
    widget.setPadding(0, 0, 0, 0);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2660 2661
    //====================================
    let stack = widget.addStack();
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
    let tipsTextSpan = stack.addText(`暂不提供『${family}』组件`);
    tipsTextSpan.textColor = Color.black();
    let fontSize = 12;
    if (family != 'small') {
      fontSize = 22
    }
    tipsTextSpan.font = Font.semiboldSystemFont(fontSize);
    tipsTextSpan.shadowColor = new Color('#333');
    tipsTextSpan.shadowRadius = 2;
    tipsTextSpan.shadowOffset = new Point(1, 1);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2672 2673 2674 2675
    stack.centerAlignContent();
    //====================================
    return widget;
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
2676

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2677 2678 2679 2680 2681 2682 2683 2684
  async providerWidget(widgetProvider = {}, family = config.widgetFamily) {
    let widget;
    const widgetSetting = this.readWidgetSetting();
    const { small = true, medium = true, large = true } = widgetProvider;
    switch (family) {
      case 'small':
        if (small) {
          widget = await this.render({ widgetSetting, family });
AndroidLeaves's avatar
AndroidLeaves 已提交
2685
        } else {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2686
          widget = this.provideDefaultWidget(family);
AndroidLeaves's avatar
AndroidLeaves 已提交
2687
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2688
        break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2689

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2690 2691
      case 'medium':
        if (medium) {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2692
          widget = await this.render({ widgetSetting, family });
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2693 2694 2695 2696
        } else {
          widget = this.provideDefaultWidget(family);
        }
        break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2697

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2698 2699
      case 'large':
        if (large) {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2700
          widget = await this.render({ widgetSetting, family });
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2701 2702 2703 2704
        } else {
          widget = this.provideDefaultWidget(family);
        }
        break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2705

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2706 2707 2708 2709
      default:
        widget = this.provideDefaultWidget(family);
        break;
    }
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2710
    await this.widgetBaseSetting(widget, widgetSetting, widgetSetting.bgType);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2711 2712 2713
    Script.setWidget(widget);
    Script.complete();
  }
AndroidLeaves's avatar
AndroidLeaves 已提交
2714

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2715 2716 2717 2718 2719 2720 2721 2722
  widgetBaseSetting = async (widget, widgetSetting, bgType) => {
    try {
      // 背景效果
      const {
        refreshInterval,
        backgroundImagePath,
        backgroundImageUrl,
        shadowColor,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2723 2724 2725
        blur = false,
        darkBlur = true,
        blurRadius = 30,
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
        shadowColorAlpha = '0',
        backgroundGradientColor,
        backgroundGradientAngle
      } = widgetSetting;
      let bgImg;
      switch (bgType) {
        case '0':
          bgImg = this.useFileManager().readImgCache(backgroundImagePath);
          if (bgImg) {
            widget.backgroundImage = bgImg;
          }
          break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2738

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2739 2740
        case '1':
          if (backgroundImageUrl) {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2741 2742 2743
            bgImg = this.useFileManager().readImgCache(backgroundImagePath);
            if (!bgImg) {
              bgImg = await this.getImageByUrl(backgroundImageUrl);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2744 2745 2746
              if (blur) {
                bgImg = await this.blurImage(bgImg, { w: bgImg.size.width, h: bgImg.size.height, x: 0, y: 0 }, darkBlur ? 'dark' : 'light', blurRadius);
              } else if (shadowColor) {
AndroidLeaves's avatar
fix  
AndroidLeaves 已提交
2747 2748 2749
                bgImg = await this.loadShadowColor2Image(bgImg, new Color(shadowColor, Number(shadowColorAlpha)));
              }
              this.useFileManager().writeImgCache(this.scriptName, bgImg);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2750 2751 2752 2753 2754 2755
            }
          }
          if (bgImg) {
            widget.backgroundImage = bgImg;
          }
          break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2756

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2757 2758 2759
        default:
          widget.backgroundGradient = this.getLinearGradientColor(this.splitColors(backgroundGradientColor), backgroundGradientAngle);
          break;
AndroidLeaves's avatar
AndroidLeaves 已提交
2760
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2761 2762 2763 2764 2765 2766 2767 2768 2769
      // 设置刷新间隔
      widget.refreshAfterDate = new Date(Number(refreshInterval) * 60 * 1000);
      let msg = `${this.bgType2Text(bgType)},刷新间隔:${refreshInterval}min`
      // 日志
      console.log(`🪢🪢 ${msg} 🪢🪢`);
      this.logDivider();
    } catch (error) {
      console.error(error);
      this.ERRS.push(error);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2770 2771 2772 2773 2774
      if (!config.runsInApp) {
        await this.notify('小组件运行出错', `🚫 ${error}`);
      } else {
        throw error
      }
AndroidLeaves's avatar
AndroidLeaves 已提交
2775 2776 2777
    }
  }

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
  // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  fetchEnv = async () => {
    const dependencyURL = "https://gitcode.net/enoyee/scriptable/-/raw/master/_LSP.js";
    const { fm, rootDir } = this.useFileManager({ useICloud: false });
    // 下载
    console.log('🤖 开始更新依赖~');
    this.logDivider();
    let updateResult = false;
    const req = new Request(dependencyURL);
    const moduleJs = await req.load();
    if (moduleJs) {
      updateResult = true;
      fm.write(fm.joinPath(rootDir, '/_LSP.js'), moduleJs);
      console.log('✅ LSP远程依赖环境更新成功!');
      this.logDivider();
AndroidLeaves's avatar
AndroidLeaves 已提交
2794
    } else {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2795 2796
      console.error('🚫 获取依赖环境脚本失败,请重试!');
      this.logDivider();
AndroidLeaves's avatar
AndroidLeaves 已提交
2797
    }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2798
    return updateResult;
AndroidLeaves's avatar
AndroidLeaves 已提交
2799
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817

  downloadUpdate = async (fileName, downloadURL) => {
    let result = await this.fetchEnv();
    if (result) {
      try {
        result = await this.downloadFile2Scriptable({
          moduleName: fileName,
          url: downloadURL,
        });
        if (result) {
          await this.generateAlert('✅ 组件更新', '已同步远程更新', ["重新运行"]);
          this.rerunWidget();
        } else {
          console.error("❌ 组件更新失败,请重试~");
          this.logDivider();
        }
      } catch (error) {
        console.error("❌ 组件更新失败," + error);
AndroidLeaves's avatar
AndroidLeaves 已提交
2818
        await this.generateAlert('❌ 组件更新', '更新失败,请稍后重试', ["好的"]);
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2819 2820 2821 2822 2823
        this.logDivider();
        this.ERRS.push(error);
        throw error
      }
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
2824
  }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846

  // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  renderWidgetTableList = async (data) => {
    // 背景色
    const bgColor = Color.dynamic(
      new Color('#F6F6F6'),
      new Color('#000000')
    );
    const table = new UITable();
    table.showSeparators = true;

    // ===================================
    const topRow = new UITableRow();
    topRow.height = 80 * Device.screenScale();
    const topCell = topRow.addImageAtURL(atob('aHR0cHM6Ly9zd2VpeGluZmlsZS5oaXNlbnNlLmNvbS9tZWRpYS9NMDAvNzEvQzgvQ2g0RnlXT0k2b0NBZjRQMUFFZ0trSzZxVVVrNTQyLmdpZg=='));
    topCell.centerAligned();
    table.addRow(topRow);
    topRow.backgroundColor = bgColor;

    // ===================================
    const { scriptURL } = data;
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2847
    const response = await this.httpGet(scriptURL, { jsonFormat: true });
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
    const { author, icon, apps } = response;
    const headerRow = new UITableRow();
    headerRow.isHeader = true;
    headerRow.height = 60;
    headerRow.cellSpacing = 10;
    // -----------------------------------
    let avatarImg = headerRow.addImageAtURL(icon);
    avatarImg.leftAligned();
    avatarImg.widthWeight = 100;
    const headText = headerRow.addText(`@${author}`, '点击对应列表项即可下载安装小组件');
    headText.titleFont = Font.semiboldSystemFont(17);
    headText.titleColor = new Color('#444');
    headText.widthWeight = 900;
    headText.leftAligned();
    // -----------------------------------
    table.addRow(headerRow);
    // -----------------------------------

    // ===================================
    const titleDividerRow = new UITableRow();
    titleDividerRow.height = 10;
    table.addRow(titleDividerRow);
    titleDividerRow.backgroundColor = bgColor;

    // ===================================
    apps.forEach((item, index) => {
      let { title, description, thumb } = item;
      const itemRow = new UITableRow();
      itemRow.height = 80;
      itemRow.cellSpacing = 30;
      // -----------------------------------
      let itemText = itemRow.addText(`${index + 1}. ${title} `);
      itemText.titleFont = Font.blackSystemFont(14);
      itemText.titleColor = new Color('#444');
      itemText.leftAligned();
      itemText.widthWeight = 300;
      // -----------------------------------
      let itemDescText = itemRow.addText(`${description}`);
      itemDescText.titleFont = Font.mediumSystemFont(13);
      itemDescText.titleColor = new Color('#666');
      itemDescText.leftAligned();
      itemDescText.widthWeight = 470;
      // -----------------------------------
      let itemImg = itemRow.addImageAtURL(thumb);
      itemImg.widthWeight = 160;
      itemImg.rightAligned();
      // -----------------------------------
      itemRow.dismissOnSelect = false;
      itemRow.onSelect = async () => {
        await this.notify("下载提示", `开始下载小组件『${item.title}』`);
        if (item.depend) {
          try {
            for (let index = 0; index < item.depend.length; index++) {
              const relyItem = item.depend[index];
              const _isWrite = await this.downloadFile2Scriptable({
                moduleName: relyItem.name,
                url: relyItem.scriptURL,
              });
              if (_isWrite) {
                await this.notify("下载提示", `依赖插件:『${relyItem.name}』下载/更新成功`);
              }
AndroidLeaves's avatar
AndroidLeaves 已提交
2909
            }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2910 2911 2912
          } catch (e) {
            console.error(e);
            this.ERRS.push(e);
AndroidLeaves's avatar
AndroidLeaves 已提交
2913
            throw e
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2914
          }
AndroidLeaves's avatar
AndroidLeaves 已提交
2915
        }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
        const isWrite = await this.downloadFile2Scriptable({
          moduleName: item.name,
          url: item.scriptURL,
        });
        if (isWrite) {
          await this.notify("下载提示", `小组件:『${item.title}』 下载/更新成功`);
        }
      };
      // -----------------------------------
      table.addRow(itemRow);
    });
    //
    QuickLook.present(table, false);
  }

  presentSubscribeWidget = async () => {
    const cacheKey = `${this.scriptName}_subscribe_list`;
    // 默认订阅列表
    const defaultSubscribeList = [{
      author: 'LSP-杂货万事屋',
      scriptURL: 'https://gitcode.net/enoyee/scriptable/-/raw/master/install/package.json'
    }]
    const subscribeList = JSON.parse(this.keyGet(cacheKey, JSON.stringify(defaultSubscribeList)));
    // 弹窗
    const mainAlert = new Alert();
    mainAlert.title = "小组件订阅列表";
    mainAlert.message = "可自行添加订阅地址";
    const _actions = [];
    subscribeList.forEach((data) => {
      const { author } = data;
      mainAlert.addAction(author);
      _actions.push(async () => {
        try {
          await this.renderWidgetTableList(data);
        } catch (error) {
          console.error(error);
          this.ERRS.push(error);
AndroidLeaves's avatar
AndroidLeaves 已提交
2953
          throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
        }
      });
    });
    _actions.push(async () => {
      await this.generateInputAlert({
        title: '订阅地址',
        options: [
          { hint: '🔗 请输入订阅地址', value: 'https://gitcode.net/enoyee/scriptable/-/raw/master/install/package.json' },
        ]
      }, async (inputArr) => {
        const scriptURL = inputArr[0].value;
        try {
          const response = await new Request(scriptURL).loadJSON();
          const newList = [];
          let notifyText = '';
          let needPush = true;
          for (let item of subscribeList) {
            if (response.author === item.author) {
              needPush = false;
              notifyText = '订阅源更新成功';
              newList.push({ author: response.author, scriptURL });
            } else {
              notifyText = '订阅源添加成功';
              newList.push(item);
            }
          }
          if (needPush) newList.push({ author: response.author, scriptURL });
          this.keySave(cacheKey, JSON.stringify(newList));
          notifyText ? await this.notify('小组件订阅', notifyText) : null;
          await this.presentSubscribeWidget();
        } catch (error) {
          await this.notify('订阅出错', '订阅源格式不符合要求~')
          console.error(error);
          this.ERRS.push(error);
AndroidLeaves's avatar
AndroidLeaves 已提交
2988
          throw error
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
        }
      })
    });
    _actions.push(async () => {
      this.keySave(cacheKey, JSON.stringify(defaultSubscribeList));
      await this.notify('小组件订阅', '订阅源重置成功');
      await this.presentSubscribeWidget();
    });
    mainAlert.addDestructiveAction("添加订阅");
    mainAlert.addDestructiveAction("重置订阅源");
    mainAlert.addCancelAction("取消操作");
    const _actionsIndex = await mainAlert.presentSheet();
    if (_actions[_actionsIndex]) {
      await _actions[_actionsIndex]();
    }
  }

AndroidLeaves's avatar
AndroidLeaves 已提交
3006
}
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3007 3008
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
AndroidLeaves's avatar
AndroidLeaves 已提交
3009

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
class CustomFont {
  constructor(webview, config) {
    this.webview = webview || new WebView()
    this.fontFamily = config.fontFamily || 'customFont'
    this.fontUrl = 'url(' + config.fontUrl + ')'
    this.timeout = config.timeout || 20000
  }

  async load() { // 加载字体
    return await this.webview.evaluateJavaScript(`
        const customFont = new FontFace("${this.fontFamily}", "${this.fontUrl}");
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let baseHeight,extendHeight;
        log('🚀 开始加载自定义字体.');
        customFont.load().then((font) => {
            document.fonts.add(font);
            completion(true);
            log('✅ 自定义字体加载成功.');
            log('----------------------------------------')
        });
        setTimeout(()=>{
            log('🚫 自定义字体加载超时');
            log('----------------------------------------')
            completion(false);
        },${this.timeout});
        null`, true)
  }

  async drawText(text, config) {
    try {
      // 配置
      const fontSize = config.fontSize || 20
      const textWidth = config.textWidth || 300
      const align = config.align || 'left' // left、right、center
      const lineLimit = config.lineLimit || 99
      const rowSpacing = config.rowSpacing || 0
      const textColor = config.textColor || 'white'
      const textArray = await this.cutText(text, fontSize, textWidth)
      const scale = config.scale || 1

      let script = ''
      for (let i in textArray) {
        let content = textArray[i].str
        let length = textArray[i].len

        if (i >= lineLimit) break
        if (i == lineLimit - 1 && i < textArray.length - 1)
          content = content.replace(/(.{1})$/, '')

        let x = 0, y = Number(i) * fontSize
        if (rowSpacing > 0 && i > 0) y = y + rowSpacing
        if (i > 0) {
          if (align === 'right') {
            x = textWidth - length
          } else if (align === 'center') {
            x = (textWidth - length) / 2
          }
        }
        script = script + `ctx.fillText("${content}", ${x}, ${y});`
AndroidLeaves's avatar
AndroidLeaves 已提交
3070
      }
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133

      const realWidth = textArray.length > 1 ? textWidth : textArray[0].len
      const lineCount = lineLimit < textArray.length ? lineLimit : textArray.length
      const returnValue = await this.webview.evaluateJavaScript(`
            canvas.width=${realWidth}*${scale};
            ctx.font = "${fontSize}px ${this.fontFamily}";
            ctx.textBaseline= "hanging";
            baseHeight= ${(fontSize + rowSpacing) * (lineCount - 1)};
            extendHeight= ctx.measureText('qypgj').actualBoundingBoxDescent;
            canvas.height= (baseHeight + extendHeight)*${scale};
            ctx.scale(${scale}, ${scale});
        
            ctx.font = "${fontSize}px ${this.fontFamily}";
            ctx.fillStyle = "${textColor}";
            ctx.textBaseline= "hanging";
            ${script}
            canvas.toDataURL()`, false)

      const imageDataString = returnValue.slice(22)
      const imageData = Data.fromBase64String(imageDataString)
      return Image.fromData(imageData)
    } catch (error) {
      console.error(error);
    }
  }

  async cutText(text, fontSize, textWidth) { // 处理文本
    try {
      return await this.webview.evaluateJavaScript(`
            function cutText(textWidth, text){
                ctx.font = "${fontSize}px ${this.fontFamily}";
                ctx.textBaseline= "hanging";
        
                let textArray=[];
                let len=0,str='';
                for(let i=0;i<text.length;i++){
                    const char=text[i]
                    const width=ctx.measureText(char).width;
                    if(len < textWidth){
                        str=str+char;
                        len=len+width;
                    }
                    if(len == textWidth){
                        textArray.push({str:str,len:len,});
                        str='';len=0;
                    }
                    if(len > textWidth){
                        textArray.push({
                        str:str.substring(0,str.length-1),
                        len:len-width,});
                        str=char;len=width;
                    }
                    if(i==text.length-1 && str){
                        textArray.push({str:str,len:len,});
                    }
                }
                return textArray
            }
            cutText(${textWidth},"${text}")
        `)
    } catch (error) {
      console.error(error);
    }
AndroidLeaves's avatar
AndroidLeaves 已提交
3134 3135 3136
  }
}

AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3137
//================================
AndroidLeaves's avatar
AndroidLeaves 已提交
3138
module.exports = {
AndroidLeaves's avatar
update  
AndroidLeaves 已提交
3139 3140 3141
  BaseWidget,
}
//================================