electron#Tray JavaScript Examples

The following examples show how to use electron#Tray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: application.js    From razer-macos with GNU General Public License v2.0 6 votes vote down vote up
createTray() {
    if (!this.isDevelopment) {
      if (this.app.dock) {
        this.app.dock.hide();
      }

      if (this.tray != null) {
        this.tray.destroy();
      }
    }

    // Template.png will be automatically inverted by electron: https://www.electronjs.org/docs/api/native-image#template-image
    this.tray = new Tray(path.join(__static, '/assets/iconTemplate.png'));
    this.tray.setToolTip('Razer macOS menu');
    this.tray.on('click', () => {
      if(this.razerApplication.deviceManager.activeRazerDevices != null) {
        this.razerApplication.deviceManager.activeRazerDevices.forEach(device => {
          if (device !== null) {
            device.refresh();
          }
        });
      }
      this.refreshTray();
    });

    this.refreshTray(true);
  }
Example #2
Source File: PageConfig.js    From ntfstool with MIT License 6 votes vote down vote up
openTrayMenu = () => {
    const path = require('path');

    const iconUrl = process.env.NODE_ENV === 'development' ? path.join(__dirname, '../../../static/menu/AINTFS18.png') :
        path.join(__dirname, 'static/menu/AINTFS18.png')

    tray = new Tray(iconUrl);

    tray.setPressedImage(iconUrl);

    tray.setIgnoreDoubleClickEvents(true);//Very important to increase click speed

    tray.on('click', (event, trayBounds) => {
        if (trayPageHandle) {
            if (trayPageHandle.isVisible()) {
                trayPageHandle.hide();
            } else {
                trayPageHandle.setPosition(
                    Math.round(trayBounds.x + (trayBounds.width / 2) - (windowBounds.width / 2)),
                    Math.round(trayBounds.y + trayBounds.height + 4), false)
                trayPageHandle.show()
            }
        } else {
            //Todo log error
            exitAll();
        }
    })
}
Example #3
Source File: background.js    From dev-sidecar with Mozilla Public License 2.0 5 votes vote down vote up
// 隐藏主窗口,并创建托盘,绑定关闭事件
function setTray () {
  // const topMenu = Menu.buildFromTemplate({})
  // Menu.setApplicationMenu(topMenu)
  // 用一个 Tray 来表示一个图标,这个图标处于正在运行的系统的通知区
  // 通常被添加到一个 context menu 上.
  // 系统托盘右键菜单
  const trayMenuTemplate = [

    {
      // 系统托盘图标目录
      label: 'DevTools',
      click: () => {
        win.webContents.openDevTools()
      }
    },
    {
      // 系统托盘图标目录
      label: '退出',
      click: () => {
        log.info('force quit')
        forceClose = true
        quit()
      }
    }
  ]
  // 设置系统托盘图标
  const iconRootPath = path.join(__dirname, '../extra/icons/tray')
  let iconPath = path.join(iconRootPath, 'icon.png')
  const iconWhitePath = path.join(iconRootPath, 'icon-white.png')
  const iconBlackPath = path.join(iconRootPath, 'icon-black.png')
  if (isMac) {
    iconPath = nativeTheme.shouldUseDarkColors ? iconWhitePath : iconBlackPath
  }

  const trayIcon = nativeImage.createFromPath(iconPath)
  const appTray = new Tray(trayIcon)

  // 当桌面主题更新时
  if (isMac) {
    nativeTheme.on('updated', () => {
      console.log('i am changed')
      if (nativeTheme.shouldUseDarkColors) {
        console.log('i am dark.')
        tray.setImage(iconWhitePath)
      } else {
        console.log('i am light.')
        tray.setImage(iconBlackPath)
        // tray.setPressedImage(iconWhitePath)
      }
    })
  }

  // 图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)

  // 设置托盘悬浮提示
  appTray.setToolTip('DevSidecar-开发者边车辅助工具')
  // 单击托盘小图标显示应用
  appTray.on('click', () => {
    // 显示主程序
    showWin()
  })

  appTray.on('right-click', function (event, bounds) {
    setTimeout(function () {
      appTray.popUpContextMenu(contextMenu)
    }, 200)
  })

  return appTray
}
Example #4
Source File: index.js    From passwall-desktop with GNU Affero General Public License v3.0 5 votes vote down vote up
app.on('ready', () => {
  const tray = new Tray(iconPath)

  const mb = menubar({
    browserWindow: { width: 400, height: 400 },
    index: winURL,
    tray
  })

  mb.on('ready', () => {
    console.log('PassWall app is ready.')
  })

  const edit = {
    label: 'Edit',
    submenu: [
      {
        label: 'Undo',
        accelerator: 'CmdOrCtrl+Z',
        selector: 'undo:'
      },
      {
        label: 'Redo',
        accelerator: 'Shift+CmdOrCtrl+Z',
        selector: 'redo:'
      },
      {
        type: 'separator'
      },
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        selector: 'cut:'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        selector: 'copy:'
      },
      {
        label: 'Paste',
        accelerator: 'CmdOrCtrl+V',
        selector: 'paste:'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        selector: 'selectAll:'
      }
    ]
  }

  Menu.setApplicationMenu(Menu.buildFromTemplate([edit]))
})
Example #5
Source File: index.js    From desktop with GNU General Public License v3.0 4 votes vote down vote up
checkService = async () => {
  info("Process ready");

  // ping service
  const servicePing = await ping();
  const timeout = 6000;

  // make sure our path is created
  try {
    const fileExist = fs.existsSync(profilePath());
    if (!fileExist) {
      fs.mkdirSync(profilePath(), { recursive: true });
    }
  } catch (error) {}

  // delete current file
  try {
    fs.unlinkSync(vpnLogPath());
  } catch (error) {}

  // write an empty file
  try {
    fs.closeSync(fs.openSync(vpnLogPath(), "w"));
  } catch (error) {}

  if (!servicePing) {
    warning("can't connect to service... trying to wake up");
    setTimeout(async () => {
      try {
        const servicePing = await ping();
        if (!servicePing) {
          errorLog("unable to connect to service");
          const clickedButton = dialog.showMessageBoxSync(null, {
            type: "warning",
            buttons: ["Exit", "Retry"],
            defaultId: 1,
            title: "VPN.ht - Service Error",
            message:
              "Unable to communicate with helper service, " +
              "try restarting computer"
          });
          if (clickedButton === 0) {
            app.quit();
          }
          if (clickedButton === 1) {
            checkService();
            return;
          }
        }
      } catch (error) {
        errorLog(error);

        if (error.statusCode && error.statusCode === 401) {
          dialog.showMessageBox(
            null,
            {
              type: "warning",
              buttons: ["Exit"],
              title: "VPN.ht - Service Error",
              message:
                "Unable to establish communication with helper " +
                "service, try restarting computer"
            },
            () => {
              app.quit();
            }
          );
        }
      }
    }, timeout);
    return;
  }

  // wake up the service and make sure it's ready to work
  const { statusCode: wakeUpStatusCode, wakeup: isWakeUp } = await wakeup();

  if (wakeUpStatusCode === 401) {
    errorLog("Can't wakeup the service (401)");
    dialog.showMessageBox(
      null,
      {
        type: "warning",
        buttons: ["Exit"],
        title: "VPN.ht - Service Error",
        message:
          "Unable to establish communication with helper " +
          "service, try restarting computer"
      },
      function() {
        app.quit();
      }
    );
    return;
  }

  if (isWakeUp) {
    errorLog("Can't wakeup the service (isWakeUp)");
    app.quit();
    return;
  }

  info("Service ready");

  // subscribe to service events
  const serviceEvents = subscribe();

  serviceEvents.on("message", async data => {
    const evt = JSON.parse(data);
    if (evt.type === "output") {
      try {
        const pathExist = fs.existsSync(profilePath());
        const logPath = vpnLogPath();
        if (!pathExist) {
          fs.mkdirSync(profilePath(), { recursive: true });
        }
        fs.appendFileSync(logPath, evt.data.output + "\n");
      } catch (error) {
        errorLog(error);
      }
    } else if (evt.type === "connected") {
      isConnected = true;
      updateHamburgerMenu();
      buildTrayMenu();
      if (tray) {
        tray.setImage(trayIcons.connected);
      }
    } else if (evt.type === "disconnected") {
      isConnected = false;
      updateHamburgerMenu();
      buildTrayMenu();
      if (tray) {
        tray.setImage(trayIcons.default);
      }
    } else if (evt.type === "wakeup") {
      openMainWin();
    }
  });

  let noMain = false;
  process.argv.forEach(function(val) {
    if (val === "--no-main") {
      noMain = true;
    }
  });

  if (!noMain) {
    openMainWin();
  } else if (process.platform === "linux") {
    app.quit();
    return;
  }

  const vpnStatus = await status();
  isConnected = vpnStatus;
  updateHamburgerMenu();

  if (process.platform !== "linux") {
    tray = new Tray(vpnStatus ? trayIcons.connected : trayIcons.default);
    buildTrayMenu();
  }

  // app menu
  const appMenu = Menu.buildFromTemplate([
    {
      label: "VPN.ht",
      submenu: [
        {
          label: `VPN.ht ${version}`
        },
        {
          label: "Close",
          accelerator: "CmdOrCtrl+Q",
          role: "close"
        },
        {
          label: "Exit",
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: "Edit",
      submenu: [
        {
          label: "Undo",
          accelerator: "CmdOrCtrl+Z",
          role: "undo"
        },
        {
          label: "Redo",
          accelerator: "Shift+CmdOrCtrl+Z",
          role: "redo"
        },
        {
          type: "separator"
        },
        {
          label: "Cut",
          accelerator: "CmdOrCtrl+X",
          role: "cut"
        },
        {
          label: "Copy",
          accelerator: "CmdOrCtrl+C",
          role: "copy"
        },
        {
          label: "Paste",
          accelerator: "CmdOrCtrl+V",
          role: "paste"
        },
        {
          label: "Select All",
          accelerator: "CmdOrCtrl+A",
          role: "selectall"
        }
      ]
    },
    {
      label: "View",
      submenu: [
        {
          label: "Toggle Developer Tools",
          accelerator: "command+alt+i",
          click: () => {
            const webContents = mainWindow.webContents;
            if (webContents.isDevToolsOpened()) {
              webContents.closeDevTools();
            } else {
              webContents.openDevTools({ mode: "detach" });
            }
          }
        }
      ]
    }
  ]);

  Menu.setApplicationMenu(appMenu);
}
Example #6
Source File: electron-main.js    From loa-details with GNU General Public License v3.0 4 votes vote down vote up
function startApplication() {
  tray = new Tray(
    process.env.DEBUGGING
      ? path.resolve(__dirname, "../../src-electron/icons/icon.png")
      : path.resolve(__dirname, "icons/icon.png")
  );

  const contextMenu = Menu.buildFromTemplate([
    {
      label: "Show LOA Details",
      click() {
        mainWindow.show();
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
      },
    },
    {
      label: "Quit",
      click() {
        app.quit();
      },
    },
  ]);

  tray.setToolTip("LOA Details");
  tray.setContextMenu(contextMenu);

  tray.on("click", () => {
    mainWindow.show();
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  });

  setupBridge(appSettings);

  httpServerEventEmitter.on("packet", (value) => {
    logParser.parseLogLine(value);
  });

  httpServerEventEmitter.on("debug", (data) => {
    log.info("debug:", data);
  });

  /*   const dontShowPatreonBox = store.get("dont_show_patreon_box");
  if (!dontShowPatreonBox) {
    const userSelection = dialog.showMessageBoxSync(mainWindow, {
      type: "info",
      title: "Support LOA Details",
      message: "Would you like to support this project by donating on Patreon?",
      buttons: ["No", "Yes"],
      defaultId: 0,
      cancelId: 0,
    });

    if (userSelection === 1) {
      shell.openExternal("https://www.patreon.com/loadetails");
    }

    store.set("dont_show_patreon_box", "true");
  } */

  mainWindow = createMainWindow(appSettings);
  damageMeterWindow = createDamageMeterWindow(logParser, appSettings);

  initializeShortcuts(appSettings);

  shortcutEventEmitter.on("shortcut", (shortcut) => {
    log.debug(shortcut);

    if (shortcut.action === "minimizeDamageMeter") {
      damageMeterWindow.webContents.send(
        "shortcut-action",
        "toggle-minimized-state"
      );
    } else if (shortcut.action === "resetSession") {
      damageMeterWindow.webContents.send("shortcut-action", "reset-session");
    } else if (shortcut.action === "pauseDamageMeter") {
      damageMeterWindow.webContents.send(
        "shortcut-action",
        "pause-damage-meter"
      );
    }
  });
}