Skip to content

Commit

Permalink
fix: show menu/tray icon.
Browse files Browse the repository at this point in the history
  • Loading branch information
timeowilliams committed Nov 2, 2024
1 parent 9f9eba5 commit 54a6394
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 74 deletions.
3 changes: 2 additions & 1 deletion forge.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ const config: ForgeConfig = {
'resources/icon_red.png',
'resources/icon_yellow.png',
'resources/icon_blue.png',
'resources/DOG_MEME.avif'
'resources/DOG_MEME.avif',
'resources/trayIcon.png'
]
},
rebuildConfig: {},
Expand Down
Binary file added resources/trayIcon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
143 changes: 80 additions & 63 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Notification,
Menu,
MenuItemConstructorOptions,
Tray,
nativeImage
} from 'electron'
import { Worker } from 'worker_threads'
Expand All @@ -16,7 +17,15 @@ import fs from 'fs'
import schedule from 'node-schedule'
import dotenv from 'dotenv'
import Store from 'electron-store'
import { StoreSchema, SiteTimeTracker, DeepWorkHours, MessageType, User, AppIcon, TrackerType } from './types'
import {
StoreSchema,
SiteTimeTracker,
DeepWorkHours,
MessageType,
User,
AppIcon,
TrackerType
} from './types'
import {
updateSiteTimeTracker,
getBrowserURL,
Expand Down Expand Up @@ -56,6 +65,7 @@ let currentDeepWork = 0
let user: User | null = null
let iconPath = ''
let mainWindow: BrowserWindow | null = null
let tray: Tray | null = null
log.transports.file.level = 'debug'
log.transports.file.maxSize = 10 * 1024 * 1024

Expand Down Expand Up @@ -93,52 +103,6 @@ function setupEnvironment() {
}
}

export function updateAppMenu() {
createAppMenu()
}

function createAppMenu() {
const totalDeepWorkHours = getDeepWorkHours()

const menuTemplate: MenuItemConstructorOptions[] = [
{
label: 'DeepFocus',
submenu: [
{
label: `Total Deep Work: ${totalDeepWorkHours} hours`,
enabled: false
},
{ type: 'separator' },
{
label: 'Reset Data',
click: () => {
handleDailyReset()
new Notification({
title: 'DeepFocus',
body: 'Daily data has been reset.',
icon: join(resourcesPath, 'icon.png')
}).show()
updateAppMenu()
}
},
{ type: 'separator' },
{
label: 'Quit',
click: () => {
app.quit()
}
}
]
}
]

// Create the menu from the template
const menu = Menu.buildFromTemplate(menuTemplate)

// Set the application menu
Menu.setApplicationMenu(menu)
}

// Store user data in the electron-store and send to worker
export function handleUserData(user: User, store: TypedStore): User {
store.set('user', {
Expand All @@ -161,11 +125,14 @@ export function loadUserData() {
const savedUser: User | null = store.get('user') || null
if (savedUser) {
schedulerWorker.postMessage({ type: MessageType.SET_USER_INFO, user: savedUser })
const iconPath = app.isPackaged
? path.join(process.resourcesPath, 'icon.png')
: path.join(__dirname, '../../resources/icon.png')

new Notification({
title: 'DeepFocus',
body: 'Welcome back, ' + savedUser.firstName,
icon: join(resourcesPath, 'icon.png')
icon: iconPath
}).show()
}
return savedUser
Expand Down Expand Up @@ -269,7 +236,6 @@ export function startActivityMonitoring() {
let URL = ''

if (isBrowser(appName)) {

URL = getBaseURL(await getBrowserURL(appName))
}

Expand Down Expand Up @@ -310,7 +276,8 @@ async function createWindow(): Promise<BrowserWindow> {
preload: path.join(__dirname, 'preload.js'),
nodeIntegrationInWorker: true,
sandbox: false
}
},
icon: iconPath
})
app.dock.setIcon(getIconPath('icon.png', resourcesPath))

Expand All @@ -323,7 +290,6 @@ async function createWindow(): Promise<BrowserWindow> {
return { action: 'deny' }
})


// and load the index.html of the app.
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL)
Expand All @@ -346,6 +312,9 @@ async function createWindow(): Promise<BrowserWindow> {
}

app.whenReady().then(async () => {
const iconPath = app.isPackaged
? path.join(process.resourcesPath, 'trayIcon.png')
: path.join(__dirname, '../../resources/trayIcon.png')
log.info('app is ready. Retrieving currentSiteTimeTrackers and deepWorkHours from store')
currentSiteTimeTrackers = store.get('siteTimeTrackers', [])
deepWorkHours = store.get('deepWorkHours', {
Expand All @@ -364,16 +333,61 @@ app.whenReady().then(async () => {
setupIPCListeners()
user = loadUserData()
setupPeriodicSave()
console.log('updating app menu')
} catch (error) {
console.error('Error during permission check or timeout:', error)

new Notification({
title: 'DeepFocus',
body: `Deep Focus can't function properly without permissions.`,
icon: join(__dirname, 'resources/icon.png')
icon: iconPath
})
}
})
const image = nativeImage.createFromPath(iconPath)
tray = new Tray(image)
tray.setToolTip('Deep Focus. Get more done.')

const trayMenu = Menu.buildFromTemplate([
{
label: 'Total Deep Work',
click: () => {
const today = dayjs().format('dddd') as keyof typeof deepWorkHours
const totalDeepWorkHours = getDeepWorkHours()[today]
new Notification({
title: 'DeepFocus',
body: `Total Deep Work: ${totalDeepWorkHours} hours`,
icon: iconPath
}).show()
}
},
{
label: 'Reset Data',
click: () => {
handleDailyReset() // Replace with your function to reset data
new Notification({
title: 'DeepFocus',
body: 'Daily data has been reset.',
icon: iconPath
}).show()
}
},
{ type: 'separator' },
{
label: 'Quit',
click: () => {
app.quit()
}
}
])

tray.setContextMenu(trayMenu)

tray.on('click', () => {
if (mainWindow) {
mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
}
})
})

app.on('ready', () => {
Expand Down Expand Up @@ -407,10 +421,13 @@ export function handleUserLogout(): void {
store.set('lastResetDate', dayjs().toISOString())
user = null
stopActivityMonitoring()
const iconPath = app.isPackaged
? path.join(process.resourcesPath, 'icon.png')
: path.join(__dirname, '../../resources/icon.png')
new Notification({
title: 'DeepFocus',
body: 'You have been logged out',
icon: join(__dirname, 'resources/icon.png')
icon: iconPath
}).show()
}

Expand Down Expand Up @@ -517,19 +534,19 @@ function setupIPCListeners() {

ipcMain.handle('get-icon', async (_event, iconPath) => {
try {
const image = nativeImage.createFromPath(iconPath);
const image = nativeImage.createFromPath(iconPath)

if (image.isEmpty()) {
console.warn(`Icon at path "${iconPath}" could not be loaded.`);
return null; // Indicate that the icon could not be loaded
console.warn(`Icon at path "${iconPath}" could not be loaded.`)
return null // Indicate that the icon could not be loaded
}
return image.toDataURL();

return image.toDataURL()
} catch (error) {
console.error(`Failed to load icon from path "${iconPath}":`, error);
return null; // Handle error by returning a default fallback
console.error(`Failed to load icon from path "${iconPath}":`, error)
return null // Handle error by returning a default fallback
}
});
})

// Fetch the user's site time trackers
ipcMain.on('fetch-site-trackers', async (event) => {
Expand Down Expand Up @@ -573,7 +590,7 @@ function setupIPCListeners() {
// Update the user's deep work target daily
ipcMain.on('update-deep-work-target', (_event, newTarget: number) => {
store.set('deepWorkTarget', newTarget)
updateAppMenu()
// updateAppMenu()
console.log(`Updated Deep Work Target: ${newTarget}`)
})
// Fetch the user's current deep work hours daily
Expand Down
4 changes: 0 additions & 4 deletions src/productivityUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,7 @@ export function getBrowserURL(browser: string): Promise<string> {
let script = `osascript -e 'tell application "${browser}" to get URL of active tab of front window'`
if (browser === 'Safari') {
script = `osascript -e 'tell application "${browser}" to get URL of front document'`
<<<<<<< HEAD
} else if (browser === 'Firefox' || browser === 'firefox') {
=======
} else if (browser.toLowerCase() === 'firefox') {
>>>>>>> 788e2091b5282f0f9c9fac1d59269704222ef7f8
script = `
osascript -e 'tell application "System Events" to get value of UI element 1 of combo box 1 of toolbar "Navigation" of first group of front window of application process "Firefox"'
`
Expand Down
7 changes: 2 additions & 5 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,11 @@ const App = (props: ComponentProps<typeof Router>) => {
// Initialize the tour for new users
createEffect(() => {
console.log('checking if logged in and new user')
<<<<<<< HEAD
if (
(localStorage.getItem('onboarded') === 'false' || !localStorage.getItem('onboarded')) &&
localStorage.getItem('token') &&
localStorage.getItem('user')
) {
=======
if((localStorage.getItem('onboarded') === 'false' || !localStorage.getItem('onboarded')) && localStorage.getItem('token') && localStorage.getItem('user')) {
>>>>>>> 788e2091b5282f0f9c9fac1d59269704222ef7f8
initializeTour()
localStorage.setItem('onboarded', 'true')
setIsNewUser(false)
Expand All @@ -141,8 +137,9 @@ const App = (props: ComponentProps<typeof Router>) => {
setIsLoggedIn(true)
sendUserToBackend(JSON.parse(user))
setIsNewUser(false)
navigate('/onboarding')
}
// TODO: better navigate user to home page to show Home component
navigate('/')
})

const NavBar = () => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export function updateIconBasedOnProgress(
const isIconPathChanged = iconPath !== newIconPath
if (isIconPathChanged) {
log.info('Comparison of icon paths is ', iconPath, newIconPath)
app.dock.setIcon(iconPath)
// app.dock.setIcon(iconPath)
new Notification({
title: 'DeepFocus',
body: message,
Expand Down

0 comments on commit 54a6394

Please sign in to comment.