Fix: An issue that would cause Matugen colors to not apply. (#929)

* Eslint updates

* linter fixes

* Type fixes

* More type fixes

* Fix isvis

* More type fixes

* Type Fixes

* Consolidate logic to manage options

* Linter fixes

* Package lock update

* Update configs

* Version checker

* Debug pipeline

* Package lock update

* Update ci

* Strict check

* Revert ci

* Eslint

* Remove rule since it causes issues in CI

* Actual matugen fix
This commit is contained in:
Jas Singh
2025-05-11 23:01:55 -07:00
committed by GitHub
parent 0c82ce9704
commit 2bb1449fb6
275 changed files with 4363 additions and 2505 deletions

View File

@@ -2,15 +2,15 @@ import { exec, GObject, monitorFile, property, readFileAsync, register } from 'a
import { sh } from 'src/lib/utils';
const get = (args: string): number => Number(exec(`brightnessctl ${args}`));
const screen = exec(`bash -c "ls -w1 /sys/class/backlight | head -1"`);
const kbd = exec(`bash -c "ls -w1 /sys/class/leds | grep '::kbd_backlight$' | head -1"`);
const screen = exec('bash -c "ls -w1 /sys/class/backlight | head -1"');
const kbd = exec('bash -c "ls -w1 /sys/class/leds | grep \'::kbd_backlight$\' | head -1"');
@register({ GTypeName: 'Brightness' })
export default class Brightness extends GObject.Object {
static instance: Brightness;
public static instance: Brightness;
static get_default(): Brightness {
if (!Brightness.instance) {
public static get_default(): Brightness {
if (Brightness.instance === undefined) {
Brightness.instance = new Brightness();
}
return Brightness.instance;
@@ -22,16 +22,16 @@ export default class Brightness extends GObject.Object {
#screen = screen?.length ? get(`--device ${screen} get`) / (get(`--device ${screen} max`) || 1) : 0;
@property(Number)
get kbd(): number {
public get kbd(): number {
return this.#kbd;
}
@property(Number)
get screen(): number {
public get screen(): number {
return this.#screen;
}
set kbd(value: number) {
public set kbd(value: number) {
if (value < 0 || value > this.#kbdMax || !kbd?.length) return;
sh(`brightnessctl -d ${kbd} s ${value} -q`).then(() => {
@@ -40,15 +40,17 @@ export default class Brightness extends GObject.Object {
});
}
set screen(percent: number) {
public set screen(percent: number) {
if (!screen?.length) return;
if (percent < 0) percent = 0;
let brightnessPct = percent;
if (percent > 1) percent = 1;
if (percent < 0) brightnessPct = 0;
sh(`brightnessctl set ${Math.round(percent * 100)}% -d ${screen} -q`).then(() => {
this.#screen = percent;
if (percent > 1) brightnessPct = 1;
sh(`brightnessctl set ${Math.round(brightnessPct * 100)}% -d ${screen} -q`).then(() => {
this.#screen = brightnessPct;
this.notify('screen');
});
}

View File

@@ -5,20 +5,25 @@ import GTop from 'gi://GTop';
import { FunctionPoller } from 'src/lib/poller/FunctionPoller';
class Cpu {
private updateFrequency = Variable(2000);
private previousCpuData = new GTop.glibtop_cpu();
private cpuPoller: FunctionPoller<number, []>;
private _updateFrequency = Variable(2000);
private _previousCpuData = new GTop.glibtop_cpu();
private _cpuPoller: FunctionPoller<number, []>;
public cpu = Variable(0);
constructor() {
GTop.glibtop_get_cpu(this.previousCpuData);
GTop.glibtop_get_cpu(this._previousCpuData);
this.calculateUsage = this.calculateUsage.bind(this);
this.cpuPoller = new FunctionPoller<number, []>(this.cpu, [], bind(this.updateFrequency), this.calculateUsage);
this._cpuPoller = new FunctionPoller<number, []>(
this.cpu,
[],
bind(this._updateFrequency),
this.calculateUsage,
);
this.cpuPoller.initialize();
this._cpuPoller.initialize();
}
public calculateUsage(): number {
@@ -26,26 +31,26 @@ class Cpu {
GTop.glibtop_get_cpu(currentCpuData);
// Calculate the differences from the previous to current data
const totalDiff = currentCpuData.total - this.previousCpuData.total;
const idleDiff = currentCpuData.idle - this.previousCpuData.idle;
const totalDiff = currentCpuData.total - this._previousCpuData.total;
const idleDiff = currentCpuData.idle - this._previousCpuData.idle;
const cpuUsagePercentage = totalDiff > 0 ? ((totalDiff - idleDiff) / totalDiff) * 100 : 0;
this.previousCpuData = currentCpuData;
this._previousCpuData = currentCpuData;
return cpuUsagePercentage;
}
public updateTimer(timerInMs: number): void {
this.updateFrequency.set(timerInMs);
this._updateFrequency.set(timerInMs);
}
public stopPoller(): void {
this.cpuPoller.stop();
this._cpuPoller.stop();
}
public startPoller(): void {
this.cpuPoller.start();
this._cpuPoller.start();
}
}

View File

@@ -2,25 +2,25 @@
import { bind, exec, Variable } from 'astal';
import { FunctionPoller } from 'src/lib/poller/FunctionPoller';
import { GPUStat } from 'src/lib/types/gpustat';
import { GPUStat } from 'src/lib/types/gpustat.types';
class Gpu {
private updateFrequency = Variable(2000);
private gpuPoller: FunctionPoller<number, []>;
private _updateFrequency = Variable(2000);
private _gpuPoller: FunctionPoller<number, []>;
public gpuUsage = Variable<number>(0);
constructor() {
this.calculateUsage = this.calculateUsage.bind(this);
this.gpuPoller = new FunctionPoller<number, []>(
this._gpuPoller = new FunctionPoller<number, []>(
this.gpuUsage,
[],
bind(this.updateFrequency),
bind(this._updateFrequency),
this.calculateUsage,
);
this.gpuPoller.initialize();
this._gpuPoller.initialize();
}
public calculateUsage(): number {
@@ -38,7 +38,7 @@ class Gpu {
return acc + gpu['utilization.gpu'];
}, 0) / data.gpus.length;
return this.divide([totalGpu, usedGpu]);
return this._divide([totalGpu, usedGpu]);
} catch (error) {
if (error instanceof Error) {
console.error('Error getting GPU stats:', error.message);
@@ -49,20 +49,20 @@ class Gpu {
}
}
private divide([total, free]: number[]): number {
private _divide([total, free]: number[]): number {
return free / total;
}
updateTimer(timerInMs: number): void {
this.updateFrequency.set(timerInMs);
public updateTimer(timerInMs: number): void {
this._updateFrequency.set(timerInMs);
}
public stopPoller(): void {
this.gpuPoller.stop();
this._gpuPoller.stop();
}
public startPoller(): void {
this.gpuPoller.start();
this._gpuPoller.start();
}
}

View File

@@ -2,32 +2,32 @@
import { bind, GLib, Variable } from 'astal';
import { FunctionPoller } from 'src/lib/poller/FunctionPoller';
import { GenericResourceData } from 'src/lib/types/customModules/generic';
import { GenericResourceData } from 'src/lib/types/customModules/generic.types';
class Ram {
private updateFrequency = Variable(2000);
private shouldRound = false;
private ramPoller: FunctionPoller<GenericResourceData, []>;
private _updateFrequency = Variable(2000);
private _shouldRound = false;
private _ramPoller: FunctionPoller<GenericResourceData, []>;
public ram = Variable<GenericResourceData>({ total: 0, used: 0, percentage: 0, free: 0 });
constructor() {
this.calculateUsage = this.calculateUsage.bind(this);
this.ramPoller = new FunctionPoller<GenericResourceData, []>(
this._ramPoller = new FunctionPoller<GenericResourceData, []>(
this.ram,
[],
bind(this.updateFrequency),
bind(this._updateFrequency),
this.calculateUsage,
);
this.ramPoller.initialize('ram');
this._ramPoller.initialize('ram');
}
public calculateUsage(): GenericResourceData {
try {
const [success, meminfoBytes] = GLib.file_get_contents('/proc/meminfo');
if (!success || !meminfoBytes) {
if (!success || meminfoBytes === undefined) {
throw new Error('Failed to read /proc/meminfo or file content is null.');
}
@@ -47,7 +47,7 @@ class Ram {
usedRam = isNaN(usedRam) || usedRam < 0 ? 0 : usedRam;
return {
percentage: this.divide([totalRamInBytes, usedRam]),
percentage: this._divide([totalRamInBytes, usedRam]),
total: totalRamInBytes,
used: usedRam,
free: availableRamInBytes,
@@ -59,29 +59,29 @@ class Ram {
}
public setShouldRound(round: boolean): void {
this.shouldRound = round;
this._shouldRound = round;
}
private divide([total, used]: number[]): number {
private _divide([total, used]: number[]): number {
const percentageTotal = (used / total) * 100;
if (this.shouldRound) {
if (this._shouldRound) {
return total > 0 ? Math.round(percentageTotal) : 0;
}
return total > 0 ? parseFloat(percentageTotal.toFixed(2)) : 0;
}
updateTimer(timerInMs: number): void {
this.updateFrequency.set(timerInMs);
public updateTimer(timerInMs: number): void {
this._updateFrequency.set(timerInMs);
}
public stopPoller(): void {
this.ramPoller.stop();
this._ramPoller.stop();
}
public startPoller(): void {
this.ramPoller.start();
this._ramPoller.start();
}
}

View File

@@ -4,25 +4,25 @@ import { bind, Variable } from 'astal';
import GTop from 'gi://GTop';
import { FunctionPoller } from 'src/lib/poller/FunctionPoller';
import { GenericResourceData } from 'src/lib/types/customModules/generic';
import { GenericResourceData } from 'src/lib/types/customModules/generic.types';
class Storage {
private updateFrequency = Variable(2000);
private shouldRound = false;
private storagePoller: FunctionPoller<GenericResourceData, []>;
private _updateFrequency = Variable(2000);
private _shouldRound = false;
private _storagePoller: FunctionPoller<GenericResourceData, []>;
public storage = Variable<GenericResourceData>({ total: 0, used: 0, percentage: 0, free: 0 });
constructor() {
this.calculateUsage = this.calculateUsage.bind(this);
this.storagePoller = new FunctionPoller<GenericResourceData, []>(
this._storagePoller = new FunctionPoller<GenericResourceData, []>(
this.storage,
[],
bind(this.updateFrequency),
bind(this._updateFrequency),
this.calculateUsage,
);
this.storagePoller.initialize();
this._storagePoller.initialize();
}
public calculateUsage(): GenericResourceData {
@@ -39,7 +39,7 @@ class Storage {
total,
used,
free: available,
percentage: this.divide([total, used]),
percentage: this._divide([total, used]),
};
} catch (error) {
console.error('Error calculating Storage usage:', error);
@@ -48,13 +48,13 @@ class Storage {
}
public setShouldRound(round: boolean): void {
this.shouldRound = round;
this._shouldRound = round;
}
private divide([total, used]: number[]): number {
private _divide([total, used]: number[]): number {
const percentageTotal = (used / total) * 100;
if (this.shouldRound) {
if (this._shouldRound) {
return total > 0 ? Math.round(percentageTotal) : 0;
}
@@ -62,15 +62,15 @@ class Storage {
}
public updateTimer(timerInMs: number): void {
this.updateFrequency.set(timerInMs);
this._updateFrequency.set(timerInMs);
}
public stopPoller(): void {
this.storagePoller.stop();
this._storagePoller.stop();
}
public startPoller(): void {
this.storagePoller.start();
this._storagePoller.start();
}
}

View File

@@ -59,19 +59,19 @@ class Wallpaper extends GObject.Object {
}
}
setWallpaper(path: string): void {
public setWallpaper(path: string): void {
this.#setWallpaper(path);
}
isRunning(): boolean {
public isRunning(): boolean {
return this.#isRunning;
}
@property(String)
declare wallpaper: string;
declare public wallpaper: string;
@signal(Boolean)
declare changed: (event: boolean) => void;
declare public changed: (event: boolean) => void;
constructor() {
super();

View File

@@ -1,90 +1,116 @@
import { defaultColorMap } from '../../lib/types/defaults/options';
import { ColorMapValue, ColorMapKey, HexColor, MatugenColors } from '../../lib/types/options';
import { ColorMapKey, HexColor, MatugenColors } from '../../lib/options/options.types';
import { getMatugenVariations } from './variations';
import { bash, dependencies, Notify, isAnImage } from '../../lib/utils';
import options from '../../options';
import icons from '../../lib/icons/icons';
import Variable from 'astal/variable';
const { scheme_type, contrast } = options.theme.matugen_settings;
const { matugen } = options.theme;
import { defaultColorMap } from 'src/lib/types/defaults/options.types';
const updateOptColor = (color: HexColor, opt: Variable<HexColor>): void => {
opt.set(color);
};
const MATUGEN_ENABLED = options.theme.matugen;
const MATUGEN_SETTINGS = options.theme.matugen_settings;
export async function generateMatugenColors(): Promise<MatugenColors | undefined> {
if (!matugen.get() || !dependencies('matugen')) {
return;
interface SystemDependencies {
checkDependencies(dep: string): boolean;
executeCommand(cmd: string): Promise<string>;
notify(notification: { summary: string; body: string; iconName: string }): void;
isValidImage(path: string): boolean;
}
class DefaultSystemDependencies implements SystemDependencies {
public checkDependencies(dep: string): boolean {
return dependencies(dep);
}
const wallpaperPath = options.wallpaper.image.get();
try {
if (!wallpaperPath.length || !isAnImage(wallpaperPath)) {
Notify({
public async executeCommand(cmd: string): Promise<string> {
return bash(cmd);
}
public notify(notification: { summary: string; body: string; iconName: string }): void {
Notify(notification);
}
public isValidImage(path: string): boolean {
return isAnImage(path);
}
}
class MatugenService {
private _deps: SystemDependencies;
constructor(deps: SystemDependencies = new DefaultSystemDependencies()) {
this._deps = deps;
}
private _normalizeContrast(contrast: number): number {
return Math.max(-1, Math.min(1, contrast));
}
public async generateMatugenColors(): Promise<MatugenColors | undefined> {
if (!MATUGEN_ENABLED.get() || !this._deps.checkDependencies('matugen')) {
return;
}
const wallpaperPath = options.wallpaper.image.get();
if (!wallpaperPath || !this._deps.isValidImage(wallpaperPath)) {
this._deps.notify({
summary: 'Matugen Failed',
body: "Please select a wallpaper in 'Theming > General' first.",
iconName: icons.ui.warning,
});
return;
}
const normalizedContrast = contrast.get() > 1 ? 1 : contrast.get() < -1 ? -1 : contrast.get();
const contents = await bash(
`matugen image --dry-run -q "${wallpaperPath}" -t scheme-${scheme_type.get()} --contrast ${normalizedContrast} --json hex`,
);
await bash(
`matugen image -q "${wallpaperPath}" -t scheme-${scheme_type.get()} --contrast ${normalizedContrast}`,
);
try {
const normalizedContrast = this._normalizeContrast(MATUGEN_SETTINGS.contrast.get());
const schemeType = MATUGEN_SETTINGS.scheme_type.get();
const mode = MATUGEN_SETTINGS.mode.get();
return JSON.parse(contents).colors[options.theme.matugen_settings.mode.get()];
} catch (error) {
const errMsg = `An error occurred while generating matugen colors: ${error}`;
console.error(errMsg);
return;
const baseCommand = `matugen image -q "${wallpaperPath}" -t scheme-${schemeType} --contrast ${normalizedContrast}`;
const jsonResult = await this._deps.executeCommand(`${baseCommand} --dry-run --json hex`);
await this._deps.executeCommand(baseCommand);
const parsedResult = JSON.parse(jsonResult);
return parsedResult?.colors?.[mode];
} catch (error) {
this._deps.notify({
summary: 'Matugen Error',
body: `An error occurred: ${error}`,
iconName: icons.ui.info,
});
console.error(`An error occurred while generating matugen colors: ${error}`);
return;
}
}
public isColorKeyValid(color: string): color is ColorMapKey {
return Object.prototype.hasOwnProperty.call(defaultColorMap, color);
}
public getMatugenHex(incomingHex: HexColor, matugenColors?: MatugenColors): HexColor {
if (!MATUGEN_ENABLED.get() || !matugenColors) {
return incomingHex;
}
const variation = MATUGEN_SETTINGS.variation.get();
const matugenVariation = getMatugenVariations(matugenColors, variation);
for (const colorKey of Object.keys(defaultColorMap)) {
if (!this.isColorKeyValid(colorKey)) {
continue;
}
const colorValue = defaultColorMap[colorKey];
if (colorValue === incomingHex) {
return matugenVariation[colorKey] ?? incomingHex;
}
}
return incomingHex;
}
}
const isColorValid = (color: string): color is ColorMapKey => {
return defaultColorMap.hasOwnProperty(color);
};
const matugenService = new MatugenService();
export const replaceHexValues = (incomingHex: HexColor, matugenColors: MatugenColors): HexColor => {
if (!options.theme.matugen.get()) {
return incomingHex;
}
const matugenVariation = getMatugenVariations(matugenColors, options.theme.matugen_settings.variation.get());
updateOptColor(matugenVariation.base, options.theme.bar.menus.menu.media.card.color as Variable<HexColor>);
for (const curColor of Object.keys(defaultColorMap)) {
const currentColor: string = curColor;
if (!isColorValid(currentColor)) {
continue;
}
const curColorValue: ColorMapValue = defaultColorMap[currentColor];
if (curColorValue === incomingHex) {
return matugenVariation[currentColor];
}
}
return incomingHex;
};
export const getMatugenHex = (incomingHex: HexColor, matugenColors: MatugenColors): HexColor => {
const matugenVariation = getMatugenVariations(matugenColors, options.theme.matugen_settings.variation.get());
for (const curColor of Object.keys(defaultColorMap)) {
if (!isColorValid(curColor)) {
continue;
}
const curColorValue: ColorMapValue = defaultColorMap[curColor];
if (curColorValue === incomingHex) {
return matugenVariation[curColor];
}
}
return incomingHex;
};
export { matugenService };

View File

@@ -1,11 +1,14 @@
import { MatugenColors, MatugenVariation, MatugenVariations } from 'src/lib/types/options';
import { MatugenColors, MatugenVariations, MatugenVariation } from 'src/lib/options/options.types';
/*
* NOTE: This maps the values of the default colors to the values generated by Matugen.
* Each of the variations are carefully tested and curated to make sure that colors don't
* have weird luminocity overlaps (light on light, dark on dark).
*/
export const getMatugenVariations = (matugenColors: MatugenColors, variation: MatugenVariations): MatugenVariation => {
export const getMatugenVariations = (
matugenColors: MatugenColors,
variation: MatugenVariations,
): MatugenVariation => {
const matVtns = {
standard_1: {
rosewater: matugenColors.secondary,
@@ -566,5 +569,6 @@ export const getMatugenVariations = (matugenColors: MatugenColors, variation: Ma
crust3: matugenColors.surface_dim,
},
};
return matVtns[variation];
};