🐛 fix(emoji): track recently used emojis and ensure order

This commit is contained in:
sankalp committed 2025-06-22 14:55:53 +05:45
1 parent 519f273d20
commit a2994abb16
1 file changed
+78 -9
+78 -9
View File
@@ -6,11 +6,14 @@ Provides quick access to emojis with search functionality.
import json import json
import os import os
import subprocess import subprocess
import time
from typing import Dict, List from typing import Dict, List
from collections import OrderedDict
from fabric.utils import get_relative_path from fabric.utils import get_relative_path
from modules.launcher.plugin_base import PluginBase from modules.launcher.plugin_base import PluginBase
from modules.launcher.result import Result from modules.launcher.result import Result
import config.data as data
class EmojiPlugin(PluginBase): class EmojiPlugin(PluginBase):
@@ -26,10 +29,16 @@ class EmojiPlugin(PluginBase):
self.emoji_data = {} self.emoji_data = {}
self.emoji_path = get_relative_path("../../../config/json/emoji.json") self.emoji_path = get_relative_path("../../../config/json/emoji.json")
# Use cache directory for recent emojis (save directly in cache dir)
self.recent_emoji_path = os.path.join(data.CACHE_DIR, "recent_emoji.json")
self.recent_emojis = OrderedDict()
self.max_recent_emojis = 20 # Maximum number of recent emojis to track
def initialize(self): def initialize(self):
"""Initialize the emoji plugin.""" """Initialize the emoji plugin."""
self.set_triggers(["emoji", "emoji ", ";", "; "]) self.set_triggers(["emoji", "emoji ", ";", "; "])
self._load_emoji_data() self._load_emoji_data()
self._load_recent_emojis()
def cleanup(self): def cleanup(self):
"""Cleanup the emoji plugin.""" """Cleanup the emoji plugin."""
@@ -46,8 +55,52 @@ class EmojiPlugin(PluginBase):
except Exception as e: except Exception as e:
print(f"Error loading emoji data: {e}") print(f"Error loading emoji data: {e}")
def _load_recent_emojis(self):
"""Load recently used emojis from JSON file."""
try:
if os.path.exists(self.recent_emoji_path):
with open(self.recent_emoji_path, "r", encoding="utf-8") as f:
recent_data = json.load(f)
# Convert to OrderedDict to maintain order
self.recent_emojis = OrderedDict(recent_data)
else:
# Create empty recent emojis file
self.recent_emojis = OrderedDict()
self._save_recent_emojis()
except Exception as e:
print(f"Error loading recent emoji data: {e}")
self.recent_emojis = OrderedDict()
def _save_recent_emojis(self):
"""Save recently used emojis to JSON file."""
try:
# Ensure the cache directory exists
os.makedirs(data.CACHE_DIR, exist_ok=True)
with open(self.recent_emoji_path, "w", encoding="utf-8") as f:
json.dump(dict(self.recent_emojis), f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error saving recent emoji data: {e}")
def _add_to_recent(self, emoji: str):
"""Add an emoji to the recent list."""
# Remove if already exists (to move it to front)
if emoji in self.recent_emojis:
del self.recent_emojis[emoji]
# Add to front with current timestamp
self.recent_emojis[emoji] = time.time()
# Keep only the most recent emojis
while len(self.recent_emojis) > self.max_recent_emojis:
# Remove the oldest item
self.recent_emojis.popitem(last=False)
# Save to file
self._save_recent_emojis()
def _copy_to_clipboard(self, emoji: str): def _copy_to_clipboard(self, emoji: str):
"""Copy emoji to clipboard.""" """Copy emoji to clipboard and track usage."""
try: try:
# Try Wayland first # Try Wayland first
try: try:
@@ -59,6 +112,10 @@ class EmojiPlugin(PluginBase):
input=emoji.encode(), input=emoji.encode(),
check=True, check=True,
) )
# Track this emoji as recently used
self._add_to_recent(emoji)
except Exception as e: except Exception as e:
print(f"Failed to copy to clipboard: {e}") print(f"Failed to copy to clipboard: {e}")
@@ -67,13 +124,21 @@ class EmojiPlugin(PluginBase):
results = [] results = []
query = query_string.lower().strip() query = query_string.lower().strip()
# If no query, show some popular emojis # If no query, show recently used emojis
if not query: if not query:
popular_emojis = ["😀", "👍", "❤️", "🎉", "🔥", "✨", "🚀", "🌈"] if self.recent_emojis:
for emoji in popular_emojis: # Show recent emojis in reverse order (most recent first)
if emoji in self.emoji_data: for emoji in reversed(list(self.recent_emojis.keys())):
emoji_info = self.emoji_data[emoji] if emoji in self.emoji_data:
results.append(self._create_emoji_result(emoji, emoji_info, 1.0)) emoji_info = self.emoji_data[emoji]
results.append(self._create_emoji_result(emoji, emoji_info, 1.0))
else:
# If no recent emojis, show some popular ones as fallback
popular_emojis = ["😀", "👍", "❤️", "🎉", "🔥", "✨", "🚀", "🌈"]
for emoji in popular_emojis:
if emoji in self.emoji_data:
emoji_info = self.emoji_data[emoji]
results.append(self._create_emoji_result(emoji, emoji_info, 1.0))
return results return results
# Search by name, group, or the emoji itself # Search by name, group, or the emoji itself
@@ -108,12 +173,16 @@ class EmojiPlugin(PluginBase):
name = info.get("name", "") name = info.get("name", "")
group = info.get("group", "") group = info.get("group", "")
# Check if this is a recently used emoji
is_recent = emoji in self.recent_emojis
subtitle = f"{group}" + (" • Recently used" if is_recent else "")
return Result( return Result(
title=name, # Show only the name, not the emoji title=name, # Show only the name, not the emoji
subtitle=f"{group}", subtitle=subtitle,
icon_markup=emoji, # Use the emoji itself as the icon icon_markup=emoji, # Use the emoji itself as the icon
action=lambda e=emoji: self._copy_to_clipboard(e), action=lambda e=emoji: self._copy_to_clipboard(e),
relevance=relevance, relevance=relevance,
plugin_name=self.display_name, plugin_name=self.display_name,
data={"emoji": emoji, "name": name, "group": group}, data={"emoji": emoji, "name": name, "group": group, "recent": is_recent},
) )