Versión Alfa — Odorou desktop pet app

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
remaster 2026-05-13 18:39:16 -06:00
commit 6f244ef4a7
32 changed files with 2436 additions and 0 deletions

22
.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
# Xcode user data
xcuserdata/
*.xcuserstate
*.xccheckout
*.moved-aside
# macOS
.DS_Store
.AppleDouble
.LSOverride
# Build products
DerivedData/
build/
Products/
# Swift Package Manager
.build/
*.resolved
# CocoaPods
Pods/

View file

@ -0,0 +1,332 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXFileReference section */
2FC0616E2FA496520046B792 /* Odorou.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Odorou.app; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
2FC061702FA496520046B792 /* Odorou */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = Odorou;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
2FC0616B2FA496520046B792 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2FC061652FA496520046B792 = {
isa = PBXGroup;
children = (
2FC061702FA496520046B792 /* Odorou */,
2FC0616F2FA496520046B792 /* Products */,
);
sourceTree = "<group>";
};
2FC0616F2FA496520046B792 /* Products */ = {
isa = PBXGroup;
children = (
2FC0616E2FA496520046B792 /* Odorou.app */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
2FC0616D2FA496520046B792 /* Odorou */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2FC061792FA496520046B792 /* Build configuration list for PBXNativeTarget "Odorou" */;
buildPhases = (
2FC0616A2FA496520046B792 /* Sources */,
2FC0616B2FA496520046B792 /* Frameworks */,
2FC0616C2FA496520046B792 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
2FC061702FA496520046B792 /* Odorou */,
);
name = Odorou;
packageProductDependencies = (
);
productName = Odorou;
productReference = 2FC0616E2FA496520046B792 /* Odorou.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
2FC061662FA496520046B792 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 2640;
LastUpgradeCheck = 2640;
TargetAttributes = {
2FC0616D2FA496520046B792 = {
CreatedOnToolsVersion = 26.4.1;
};
};
};
buildConfigurationList = 2FC061692FA496520046B792 /* Build configuration list for PBXProject "Odorou" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 2FC061652FA496520046B792;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = 2FC0616F2FA496520046B792 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
2FC0616D2FA496520046B792 /* Odorou */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
2FC0616C2FA496520046B792 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
2FC0616A2FA496520046B792 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
2FC061772FA496520046B792 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.4;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
2FC061782FA496520046B792 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.4;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
};
name = Release;
};
2FC0617A2FA496520046B792 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "$(SRCROOT)/Odorou/Odorou.entitlements";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_APP_SANDBOX = YES;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SELECTED_FILES = readonly;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = cc.waifus.Odorou;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
2FC0617B2FA496520046B792 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "$(SRCROOT)/Odorou/Odorou.entitlements";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_APP_SANDBOX = YES;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SELECTED_FILES = readonly;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = cc.waifus.Odorou;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
2FC061692FA496520046B792 /* Build configuration list for PBXProject "Odorou" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2FC061772FA496520046B792 /* Debug */,
2FC061782FA496520046B792 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2FC061792FA496520046B792 /* Build configuration list for PBXNativeTarget "Odorou" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2FC0617A2FA496520046B792 /* Debug */,
2FC0617B2FA496520046B792 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 2FC061662FA496520046B792 /* Project object */;
}

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View file

@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View file

@ -0,0 +1,68 @@
{
"images" : [
{
"filename" : "logo_16.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"filename" : "logo_32.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"filename" : "logo_32.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"filename" : "logo_64.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"filename" : "logo_128.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"filename" : "logo_256.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"filename" : "logo_256.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"filename" : "logo_512.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"filename" : "logo_512.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"filename" : "logo_1024.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 883 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

View file

@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View file

@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "logo.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 KiB

View file

@ -0,0 +1,22 @@
{
"images" : [
{
"filename" : "odorou_1x.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "odorou_2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

View file

@ -0,0 +1,162 @@
import Foundation
import ImageIO
import CoreGraphics
import UniformTypeIdentifiers
import simd
/// Removes solid-color backgrounds from animated GIF files using per-frame pixel comparison.
enum BackgroundRemover {
enum RemovalError: LocalizedError {
case loadFailed, noFrames, createFailed, writeFailed
var errorDescription: String? {
switch self {
case .loadFailed: return "No se pudo cargar el GIF."
case .noFrames: return "El GIF no tiene frames."
case .createFailed: return "No se pudo crear el archivo de destino."
case .writeFailed: return "Error al guardar el GIF procesado."
}
}
}
/// Processes `sourceURL` and overwrites it with a version that has the background removed.
/// - Parameter tolerance: 0..1 color distance threshold. 0.20 works well for solid anime backgrounds.
static func removeBackground(from sourceURL: URL, tolerance: Float = 0.20) throws {
guard let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil) else {
throw RemovalError.loadFailed
}
let frameCount = CGImageSourceGetCount(source)
guard frameCount > 0 else { throw RemovalError.noFrames }
// Preserve loop count
let srcGlobalProps = CGImageSourceCopyProperties(source, nil) as? [CFString: Any]
let loopCount = (srcGlobalProps?[kCGImagePropertyGIFDictionary] as? [CFString: Any])?[kCGImagePropertyGIFLoopCount] as? Int ?? 0
// Build output into a temp file, then replace the original atomically
let tempURL = sourceURL.deletingLastPathComponent()
.appendingPathComponent("__tmp_\(UUID().uuidString).gif")
guard let destination = CGImageDestinationCreateWithURL(
tempURL as CFURL,
"com.compuserve.gif" as CFString,
frameCount,
nil
) else { throw RemovalError.createFailed }
CGImageDestinationSetProperties(destination, [
kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: loopCount] as [CFString: Any]
] as CFDictionary)
// Sample background color from the first frame's corners
guard let firstFrame = CGImageSourceCreateImageAtIndex(source, 0, nil) else {
throw RemovalError.loadFailed
}
let bgColor = sampleCornerColor(from: firstFrame)
for i in 0..<frameCount {
guard let frame = CGImageSourceCreateImageAtIndex(source, i, nil) else { continue }
let frameProps = CGImageSourceCopyPropertiesAtIndex(source, i, nil) as? [CFString: Any]
let gifDict = frameProps?[kCGImagePropertyGIFDictionary] as? [CFString: Any]
let delay = gifDict?[kCGImagePropertyGIFUnclampedDelayTime] as? Double
?? gifDict?[kCGImagePropertyGIFDelayTime] as? Double
?? 0.08
let processed = applyRemoval(to: frame, bgColor: bgColor, tolerance: tolerance) ?? frame
CGImageDestinationAddImage(destination, processed, [
kCGImagePropertyGIFDictionary: [
kCGImagePropertyGIFUnclampedDelayTime: delay
] as [CFString: Any]
] as CFDictionary)
}
guard CGImageDestinationFinalize(destination) else {
try? FileManager.default.removeItem(at: tempURL)
throw RemovalError.writeFailed
}
// Atomically replace the source file
_ = try FileManager.default.replaceItemAt(sourceURL, withItemAt: tempURL)
}
// MARK: - Private helpers
private static func sampleCornerColor(from image: CGImage) -> SIMD3<Float> {
let w = image.width, h = image.height
guard let pixels = renderPixels(image) else { return SIMD3(1, 1, 1) }
// Indices for the 4 corners in the flat pixel buffer
let offsets = [
0,
(w - 1) * 4,
(h - 1) * w * 4,
((h - 1) * w + (w - 1)) * 4
]
let samples = offsets.map { colorAt($0, pixels) }
let avg = samples.reduce(SIMD3<Float>.zero, +) / Float(samples.count)
// Use average only when all corners are similar (solid background)
let allSimilar = samples.allSatisfy { simd_distance($0, avg) < 0.12 }
return allSimilar ? avg : samples[0]
}
private static func applyRemoval(to image: CGImage, bgColor: SIMD3<Float>, tolerance: Float) -> CGImage? {
let w = image.width, h = image.height
guard var pixels = renderPixels(image) else { return nil }
for i in 0..<(w * h) {
let offset = i * 4
let pixel = colorAt(offset, pixels)
if simd_distance(pixel, bgColor) < tolerance {
pixels[offset] = 0
pixels[offset + 1] = 0
pixels[offset + 2] = 0
pixels[offset + 3] = 0 // fully transparent
}
}
return makeImage(&pixels, w, h)
}
private static func renderPixels(_ image: CGImage) -> [UInt8]? {
let w = image.width, h = image.height
var pixels = [UInt8](repeating: 0, count: w * h * 4)
let drawn = pixels.withUnsafeMutableBytes { ptr -> Bool in
guard let ctx = CGContext(
data: ptr.baseAddress,
width: w, height: h,
bitsPerComponent: 8,
bytesPerRow: w * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else { return false }
ctx.draw(image, in: CGRect(x: 0, y: 0, width: CGFloat(w), height: CGFloat(h)))
return true
}
return drawn ? pixels : nil
}
private static func makeImage(_ pixels: inout [UInt8], _ w: Int, _ h: Int) -> CGImage? {
pixels.withUnsafeMutableBytes { ptr in
guard let ctx = CGContext(
data: ptr.baseAddress,
width: w, height: h,
bitsPerComponent: 8,
bytesPerRow: w * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else { return nil }
return ctx.makeImage()
}
}
private static func colorAt(_ offset: Int, _ pixels: [UInt8]) -> SIMD3<Float> {
SIMD3(
Float(pixels[offset]) / 255,
Float(pixels[offset + 1]) / 255,
Float(pixels[offset + 2]) / 255
)
}
}

460
Odorou/ContentView.swift Normal file
View file

@ -0,0 +1,460 @@
import SwiftUI
import UniformTypeIdentifiers
struct ContentView: View {
@State private var library = GIFLibraryManager.shared
@State private var petManager = PetWindowManager.shared
@State private var selectedEdge: ScreenEdge = .bottomRight
@State private var isImporting = false
@State private var isImportingPreset = false
@State private var showingSettings = false
@State private var globalSizeRatio: Double = 0.15
@State private var isDragTargeted = false
@State private var searchText = ""
@AppStorage("hasSeenOnboarding") private var hasSeenOnboarding = false
// URL import states
@State private var showURLImport = false
@State private var urlImportText = ""
@State private var urlImportError: String?
@State private var isDownloadingURL = false
private let columns = [GridItem(.adaptive(minimum: 170), spacing: 12)]
private var filteredEntries: [GIFEntry] {
searchText.isEmpty ? library.entries
: library.entries.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
}
var body: some View {
NavigationSplitView {
sidebar
.navigationTitle("Activas (\(petManager.activePets.count))")
} detail: {
VStack(spacing: 0) {
if library.entries.isEmpty {
emptyState
} else {
libraryGrid
}
Divider()
toolbar
}
.navigationTitle("Biblioteca")
}
.searchable(text: $searchText, prompt: "Buscar mascota…")
.frame(minWidth: 720, minHeight: 500)
.onDrop(of: [.fileURL], isTargeted: $isDragTargeted, perform: handleDrop)
.overlay(alignment: .center) {
if isDragTargeted {
RoundedRectangle(cornerRadius: 16)
.stroke(Color.accentColor, lineWidth: 3)
.padding(8)
.allowsHitTesting(false)
}
}
.fileImporter(isPresented: $isImportingPreset, allowedContentTypes: [.json]) { result in
if case .success(let url) = result { try? petManager.importPreset(from: url) }
}
.sheet(isPresented: $showURLImport) {
urlImportSheet
}
.overlay {
if !hasSeenOnboarding {
onboardingOverlay
}
}
}
// MARK: Sidebar — active pets + global size slider
private var sidebar: some View {
VStack(spacing: 0) {
List {
if petManager.activePets.isEmpty {
ContentUnavailableView(
"Sin mascotas",
systemImage: "figure.dance",
description: Text("Activa un GIF desde la biblioteca")
)
} else {
ForEach(petManager.activePets) { pet in
if let entry = library.entries.first(where: { $0.id == pet.gifID }) {
HStack(spacing: 10) {
GIFPlayerView(gifURL: library.gifURL(for: entry), isPaused: true)
.frame(width: 46, height: 46)
.clipShape(RoundedRectangle(cornerRadius: 7))
.overlay(
RoundedRectangle(cornerRadius: 7)
.strokeBorder(.separator, lineWidth: 0.5)
)
VStack(alignment: .leading, spacing: 2) {
Text(entry.name)
.font(.caption)
.lineLimit(1)
Text("\(Int(pet.sizeRatio * 100))%")
.font(.caption2.monospacedDigit())
.foregroundStyle(.secondary)
Text("Opacidad: \(Int(pet.opacity * 100))%")
.font(.caption2.monospacedDigit())
.foregroundStyle(.secondary)
}
Spacer()
Button {
petManager.removePet(pet)
} label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
}
.padding(.vertical, 3)
}
}
}
}
if !petManager.activePets.isEmpty {
Divider()
VStack(spacing: 4) {
HStack {
Text("Tamaño global")
.font(.caption).foregroundStyle(.secondary)
Spacer()
Text("\(Int(globalSizeRatio * 100))%")
.font(.caption.monospacedDigit()).foregroundStyle(.secondary)
}
Slider(value: $globalSizeRatio, in: 0.05...0.50, step: 0.01)
.onChange(of: globalSizeRatio) { _, v in petManager.setGlobalSize(v) }
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
}
}
}
// MARK: Library grid
private var libraryGrid: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(filteredEntries) { entry in
GIFLibraryCard(
entry: entry,
gifURL: library.gifURL(for: entry),
onActivate: { petManager.addPet(gifEntry: entry, edge: selectedEdge) },
onDelete: { library.deleteEntry(entry) },
onRename: { library.renameEntry(entry, to: $0) }
)
}
}
.padding()
}
}
// MARK: Empty state
private var emptyState: some View {
VStack(spacing: 16) {
Image(systemName: "photo.on.rectangle.angled")
.font(.system(size: 64))
.foregroundStyle(.tertiary)
Text("Biblioteca vacía")
.font(.title2.bold())
Text("Importa GIFs/WebP o arrastra archivos aquí")
.foregroundStyle(.secondary)
importButton
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: Bottom toolbar
private var toolbar: some View {
HStack(spacing: 12) {
Label("Posición:", systemImage: "location")
.font(.callout)
.foregroundStyle(.secondary)
Picker("", selection: $selectedEdge) {
ForEach(ScreenEdge.allCases, id: \.self) { edge in
Text(edge.label).tag(edge)
}
}
.labelsHidden()
.frame(width: 160)
Spacer()
Text("\(library.entries.count) archivo\(library.entries.count == 1 ? "" : "s")")
.font(.caption)
.foregroundStyle(.secondary)
Button { showingSettings.toggle() } label: {
Image(systemName: "gearshape")
}
.buttonStyle(.borderless)
.help("Ajustes")
.popover(isPresented: $showingSettings, arrowEdge: .top) {
SettingsPopover(isImportingPreset: $isImportingPreset)
}
Button { showURLImport = true } label: {
Image(systemName: "link")
}
.buttonStyle(.borderless)
.help("Importar desde URL")
importButton
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(.bar)
}
private var importButton: some View {
Button { isImporting = true } label: {
Label("Importar", systemImage: "plus")
}
.buttonStyle(.borderedProminent)
.fileImporter(
isPresented: $isImporting,
allowedContentTypes: [UTType.gif,
UTType(filenameExtension: "webp", conformingTo: .image) ?? .data],
allowsMultipleSelection: true
) { result in
if case .success(let urls) = result { urls.forEach { library.importGIF(from: $0) } }
}
}
// MARK: URL import sheet
private var urlImportSheet: some View {
VStack(alignment: .leading, spacing: 16) {
Text("Importar desde URL")
.font(.headline)
TextField("https://ejemplo.com/mascota.gif", text: $urlImportText)
.textFieldStyle(.roundedBorder)
.frame(minWidth: 340)
if let err = urlImportError {
Text(err)
.font(.caption)
.foregroundStyle(.red)
}
HStack {
Spacer()
Button("Cancelar") {
showURLImport = false
urlImportText = ""
urlImportError = nil
}
.keyboardShortcut(.cancelAction)
Button {
importFromURL()
} label: {
if isDownloadingURL {
ProgressView()
.progressViewStyle(.circular)
.scaleEffect(0.7)
} else {
Text("Descargar")
}
}
.buttonStyle(.borderedProminent)
.disabled(urlImportText.trimmingCharacters(in: .whitespaces).isEmpty || isDownloadingURL)
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(minWidth: 380)
}
// MARK: Drag & drop
private func handleDrop(_ providers: [NSItemProvider]) -> Bool {
for provider in providers {
provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
let url: URL?
if let data = item as? Data { url = URL(dataRepresentation: data, relativeTo: nil) }
else { url = item as? URL }
guard let url, ["gif", "webp"].contains(url.pathExtension.lowercased()) else { return }
DispatchQueue.main.async { library.importGIF(from: url) }
}
}
return true
}
// MARK: Import from URL
private func importFromURL() {
guard let url = URL(string: urlImportText.trimmingCharacters(in: .whitespaces)) else {
urlImportError = "URL no válida"; return
}
isDownloadingURL = true; urlImportError = nil
Task {
do {
let (data, response) = try await URLSession.shared.data(from: url)
guard let ext = imageExtension(for: data, response: response) else {
await MainActor.run { urlImportError = "Solo se admiten GIF y WebP"; isDownloadingURL = false }
return
}
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + "." + ext)
try data.write(to: tempURL)
await MainActor.run {
library.importGIF(from: tempURL)
isDownloadingURL = false; showURLImport = false; urlImportText = ""
}
} catch {
await MainActor.run { urlImportError = error.localizedDescription; isDownloadingURL = false }
}
}
}
/// Determines the file extension from the URL path, Content-Type header, or magic bytes — in that order.
private func imageExtension(for data: Data, response: URLResponse) -> String? {
// 1. Path extension from the final URL
let finalURL = (response as? HTTPURLResponse)?.url ?? response.url
let pathExt = finalURL?.pathExtension.lowercased() ?? ""
if ["gif", "webp"].contains(pathExt) { return pathExt }
// 2. Content-Type header
if let mime = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Type")?.lowercased() {
if mime.contains("image/gif") { return "gif" }
if mime.contains("image/webp") { return "webp" }
}
// 3. Magic bytes: GIF89a / GIF87a → "GIF"; RIFF….WEBP → "webp"
if data.count >= 6 {
let header = data.prefix(6)
if header.prefix(3).elementsEqual([0x47, 0x49, 0x46]) { return "gif" } // GIF
}
if data.count >= 12 {
let riff = data.prefix(4)
let webp = data.dropFirst(8).prefix(4)
if riff.elementsEqual([0x52, 0x49, 0x46, 0x46]) &&
webp.elementsEqual([0x57, 0x45, 0x42, 0x50]) { return "webp" }
}
return nil
}
// MARK: - Onboarding overlay
private var onboardingOverlay: some View {
ZStack {
Color.black.opacity(0.55)
.ignoresSafeArea()
VStack(spacing: 0) {
Image("logo")
.resizable()
.scaledToFit()
.frame(width: 64, height: 64)
.clipShape(RoundedRectangle(cornerRadius: 14))
.padding(.bottom, 12)
Text("Bienvenido a Odorou")
.font(.title2.bold())
Text("Mascotas animadas que viven en tu escritorio")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.top, 4)
.padding(.bottom, 20)
Divider()
.padding(.bottom, 16)
VStack(alignment: .leading, spacing: 14) {
featureRow(icon: "plus.circle.fill",
title: "Importa GIFs y WebP",
desc: "Arrastra archivos a la ventana o usa el botón Importar")
featureRow(icon: "hand.draw",
title: "Arrástralas libremente",
desc: "Muévelas a cualquier borde y rotan de forma automática")
featureRow(icon: "slider.horizontal.3",
title: "Personaliza tamaño y opacidad",
desc: "Clic derecho sobre la mascota para ajustarla al instante")
featureRow(icon: "wand.and.stars",
title: "Elimina el fondo de un GIF",
desc: "El botón de varita mágica recorta el fondo sólido")
featureRow(icon: "magnifyingglass",
title: "Busca en tu biblioteca",
desc: "Filtra tus GIFs por nombre con la barra de búsqueda")
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 24)
Button("¡Empezar!") {
hasSeenOnboarding = true
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
.keyboardShortcut(.defaultAction)
}
.padding(28)
.frame(maxWidth: 420)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 20))
.shadow(color: .black.opacity(0.3), radius: 40, y: 10)
}
}
@ViewBuilder
private func featureRow(icon: String, title: String, desc: String) -> some View {
HStack(alignment: .top, spacing: 12) {
Image(systemName: icon)
.font(.title3)
.foregroundStyle(Color.accentColor)
.frame(width: 28, alignment: .center)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.callout.bold())
Text(desc).font(.caption).foregroundStyle(.secondary)
}
}
}
}
// MARK: - Settings Popover
private struct SettingsPopover: View {
@Binding var isImportingPreset: Bool
@State private var petManager = PetWindowManager.shared
var body: some View {
VStack(alignment: .leading, spacing: 14) {
Text("Ajustes").font(.headline)
Toggle("Iniciar al arrancar el sistema", isOn: Binding(
get: { petManager.isLaunchAtLoginEnabled },
set: { petManager.setLaunchAtLogin($0) }
))
Divider()
HStack(spacing: 8) {
Button("Importar preset…") { isImportingPreset = true }
Button("Exportar preset…") {
let panel = NSSavePanel()
panel.allowedContentTypes = [.json]
panel.nameFieldStringValue = "odorou_preset"
panel.begin { r in
guard r == .OK, let url = panel.url else { return }
try? petManager.exportPreset(to: url)
}
}
}
}
.padding()
.frame(width: 260)
}
}
#Preview {
ContentView()
}

145
Odorou/GIFLibraryCard.swift Normal file
View file

@ -0,0 +1,145 @@
import SwiftUI
struct GIFLibraryCard: View {
let entry: GIFEntry
let gifURL: URL
let onActivate: () -> Void
let onDelete: () -> Void
let onRename: (String) -> Void
@State private var isHovered = false
@State private var isRemovingBackground = false
@State private var gifRefreshID = 0
@State private var errorMessage: String?
@State private var isRenaming = false
@State private var pendingName = ""
var body: some View {
VStack(spacing: 6) {
ZStack {
RoundedRectangle(cornerRadius: 14)
.fill(Color(nsColor: .controlBackgroundColor))
.overlay(
RoundedRectangle(cornerRadius: 14)
.strokeBorder(
isHovered ? Color.accentColor : Color.gray.opacity(0.2),
lineWidth: isHovered ? 2 : 1
)
)
GIFPlayerView(gifURL: gifURL)
.frame(width: 130, height: 130)
.clipShape(RoundedRectangle(cornerRadius: 10))
.id(gifRefreshID)
if isHovered && !isRemovingBackground {
RoundedRectangle(cornerRadius: 10)
.fill(.black.opacity(0.38))
.frame(width: 130, height: 130)
.transition(.opacity)
HStack(spacing: 16) {
Button(action: removeBackground) {
Image(systemName: "wand.and.stars")
.font(.title3.weight(.semibold))
.foregroundStyle(.white)
.opacity(gifURL.pathExtension.lowercased() == "gif" ? 1 : 0.35)
}
.buttonStyle(.plain)
.disabled(gifURL.pathExtension.lowercased() != "gif")
.help(gifURL.pathExtension.lowercased() == "gif" ? "Eliminar fondo sólido" : "Solo disponible para GIF")
Button(action: onDelete) {
Image(systemName: "trash")
.font(.title3.weight(.semibold))
.foregroundStyle(.white)
}
.buttonStyle(.plain)
.help("Eliminar")
}
.transition(.opacity)
}
if isRemovingBackground {
RoundedRectangle(cornerRadius: 10)
.fill(.black.opacity(0.45))
.frame(width: 130, height: 130)
ProgressView()
.progressViewStyle(.circular)
.tint(.white)
.scaleEffect(0.8)
}
}
.frame(width: 150, height: 150)
.shadow(
color: .black.opacity(isHovered ? 0.18 : 0.07),
radius: isHovered ? 10 : 4,
y: isHovered ? 4 : 2
)
if isRenaming {
TextField("", text: $pendingName)
.textFieldStyle(.roundedBorder)
.font(.caption)
.frame(maxWidth: 134)
.onSubmit { commitRename() }
.onExitCommand { isRenaming = false }
} else {
Text(entry.name)
.font(.caption)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: 134)
.onTapGesture(count: 2) {
pendingName = entry.name
isRenaming = true
}
}
if let msg = errorMessage {
Text(msg)
.font(.caption2)
.foregroundStyle(.red)
.multilineTextAlignment(.center)
.frame(maxWidth: 134)
}
Button(action: onActivate) {
Label("Activar", systemImage: "plus.circle.fill")
.font(.caption)
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.controlSize(.small)
.frame(maxWidth: 134)
}
.padding(10)
.scaleEffect(isHovered ? 1.03 : 1.0)
.animation(.spring(response: 0.2, dampingFraction: 0.75), value: isHovered)
.onHover { isHovered = $0 }
}
private func commitRename() {
onRename(pendingName.isEmpty ? entry.name : pendingName)
isRenaming = false
}
private func removeBackground() {
isRemovingBackground = true
errorMessage = nil
Task.detached(priority: .userInitiated) {
do {
try await BackgroundRemover.removeBackground(from: gifURL)
await MainActor.run {
gifRefreshID += 1
isRemovingBackground = false
}
} catch {
await MainActor.run {
errorMessage = error.localizedDescription
isRemovingBackground = false
}
}
}
}
}

View file

@ -0,0 +1,79 @@
import Foundation
import Observation
import AppKit
@Observable
class GIFLibraryManager {
static let shared = GIFLibraryManager()
var entries: [GIFEntry] = []
private var gifsDirectory: URL {
appSupportBase.appendingPathComponent("gifs", isDirectory: true)
}
private var metadataURL: URL {
appSupportBase.appendingPathComponent("library.json")
}
private var appSupportBase: URL {
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
return base.appendingPathComponent("Odorou", isDirectory: true)
}
private init() {
createDirectories()
loadEntries()
}
func gifURL(for entry: GIFEntry) -> URL {
gifsDirectory.appendingPathComponent(entry.filename)
}
func importGIF(from sourceURL: URL) {
let ext = sourceURL.pathExtension.lowercased()
guard ["gif", "webp"].contains(ext) else { return }
let accessing = sourceURL.startAccessingSecurityScopedResource()
defer { if accessing { sourceURL.stopAccessingSecurityScopedResource() } }
let filename = UUID().uuidString + "." + ext
let destURL = gifsDirectory.appendingPathComponent(filename)
do {
try FileManager.default.copyItem(at: sourceURL, to: destURL)
let name = sourceURL.deletingPathExtension().lastPathComponent
let entry = GIFEntry(id: UUID(), filename: filename, name: name, dateAdded: Date())
entries.append(entry)
saveEntries()
} catch {
print("Error al importar: \(error)")
}
}
func deleteEntry(_ entry: GIFEntry) {
try? FileManager.default.removeItem(at: gifURL(for: entry))
entries.removeAll { $0.id == entry.id }
saveEntries()
}
func renameEntry(_ entry: GIFEntry, to name: String) {
guard let idx = entries.firstIndex(where: { $0.id == entry.id }) else { return }
entries[idx].name = name
saveEntries()
}
private func createDirectories() {
try? FileManager.default.createDirectory(at: gifsDirectory, withIntermediateDirectories: true)
}
private func loadEntries() {
guard let data = try? Data(contentsOf: metadataURL),
let loaded = try? JSONDecoder().decode([GIFEntry].self, from: data) else { return }
entries = loaded
}
private func saveEntries() {
guard let data = try? JSONEncoder().encode(entries) else { return }
try? data.write(to: metadataURL)
}
}

View file

@ -0,0 +1,46 @@
import AppKit
import SwiftUI
struct GIFPlayerView: NSViewRepresentable {
let gifURL: URL
var isPaused: Bool = false
// Coordinator tracks the last loaded URL so we don't reload on every state update
// (reloading restarts the animation from frame 0).
class Coordinator {
var loadedURL: URL?
}
func makeCoordinator() -> Coordinator { Coordinator() }
func makeNSView(context: Context) -> NSImageView {
let imageView = NonInteractiveImageView()
imageView.animates = !isPaused
imageView.imageScaling = .scaleProportionallyUpOrDown
imageView.wantsLayer = true
imageView.layer?.backgroundColor = NSColor.clear.cgColor
imageView.layer?.isOpaque = false
load(into: imageView, coordinator: context.coordinator)
return imageView
}
func updateNSView(_ nsView: NSImageView, context: Context) {
if context.coordinator.loadedURL != gifURL {
load(into: nsView, coordinator: context.coordinator)
}
nsView.animates = !isPaused
}
private func load(into imageView: NSImageView, coordinator: Coordinator) {
guard let image = NSImage(contentsOf: gifURL) else { return }
imageView.image = image
coordinator.loadedURL = gifURL
}
}
// Passes all mouse events through so SwiftUI hover tracking and the DraggableHostingView
// above it receive events without interference from NSImageView's own tracking areas.
private class NonInteractiveImageView: NSImageView {
override func hitTest(_ point: NSPoint) -> NSView? { nil }
override var acceptsFirstResponder: Bool { false }
override func updateTrackingAreas() {}
}

88
Odorou/Models.swift Normal file
View file

@ -0,0 +1,88 @@
import Foundation
import CoreGraphics
struct GIFEntry: Codable, Identifiable, Hashable {
let id: UUID
let filename: String
var name: String
var dateAdded: Date
}
struct ActivePet: Codable, Identifiable {
let id: UUID
let gifID: UUID
var position: CGPoint
/// Fraction of the screen's shorter dimension (0.05–0.50).
var sizeRatio: Double
/// Snap rotation in degrees (SwiftUI CW): 0 (bottom), 90 (left/3pm), 180 (top), 270 (right/9pm).
var rotation: Double
/// Index into NSScreen.screens; nil = main screen.
var screenIndex: Int?
/// Window opacity (0.1–1.0).
var opacity: Double
enum CodingKeys: String, CodingKey {
case id, gifID, position, sizeRatio, size, rotation, screenIndex, opacity
}
init(id: UUID, gifID: UUID, position: CGPoint, sizeRatio: Double,
rotation: Double = 0, screenIndex: Int? = nil, opacity: Double = 1.0) {
self.id = id; self.gifID = gifID; self.position = position
self.sizeRatio = sizeRatio; self.rotation = rotation
self.screenIndex = screenIndex; self.opacity = opacity
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(UUID.self, forKey: .id)
gifID = try c.decode(UUID.self, forKey: .gifID)
position = try c.decode(CGPoint.self, forKey: .position)
if let ratio = try? c.decode(Double.self, forKey: .sizeRatio) {
sizeRatio = ratio
} else if let px = try? c.decode(Double.self, forKey: .size) {
sizeRatio = min(max(px / 1080.0, 0.05), 0.50)
} else {
sizeRatio = 0.15
}
rotation = (try? c.decode(Double.self, forKey: .rotation)) ?? 0
screenIndex = try? c.decode(Int.self, forKey: .screenIndex)
opacity = (try? c.decode(Double.self, forKey: .opacity)) ?? 1.0
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(id, forKey: .id)
try c.encode(gifID, forKey: .gifID)
try c.encode(position, forKey: .position)
try c.encode(sizeRatio, forKey: .sizeRatio)
try c.encode(rotation, forKey: .rotation)
try c.encodeIfPresent(screenIndex, forKey: .screenIndex)
try c.encode(opacity, forKey: .opacity)
}
}
struct GlobalSettings: Codable {
var isPaused: Bool = false
var isLocked: Bool = false
var isWallpaperMode: Bool = false
}
enum ScreenEdge: String, CaseIterable, Codable {
case bottom, top, left, right
case bottomLeft, bottomRight, topLeft, topRight
case center
var label: String {
switch self {
case .bottom: return "↓ Abajo"
case .top: return "↑ Arriba"
case .left: return "← Izquierda"
case .right: return "→ Derecha"
case .bottomLeft: return "↙ Abajo izq."
case .bottomRight: return "↘ Abajo der."
case .topLeft: return "↖ Arriba izq."
case .topRight: return "↗ Arriba der."
case .center: return "⊙ Centro"
}
}
}

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
</dict>
</plist>

147
Odorou/OdorouApp.swift Normal file
View file

@ -0,0 +1,147 @@
import SwiftUI
import UserNotifications
@main
struct OdorouApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
// Main library window — id allows openWindow(id:) from the menu bar
WindowGroup("Odorou", id: "library") {
ContentView()
}
.defaultSize(width: 800, height: 580)
.commands {
CommandGroup(replacing: .newItem) {}
}
// Menu bar icon — pre-sized @1x/@2x asset (27×18 / 54×36 pt)
MenuBarExtra {
MenuBarContentView()
} label: {
Image("odorou")
}
.menuBarExtraStyle(.menu)
}
}
// MARK: - AppDelegate
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.accessory)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in }
NotificationCenter.default.addObserver(
self,
selector: #selector(windowWillClose(_:)),
name: NSWindow.willCloseNotification,
object: nil
)
DispatchQueue.main.async {
// Hide (don't close) the window SwiftUI auto-creates on launch.
// We show it on demand so no Dock icon appears at startup.
NSApp.windows
.filter { !($0 is NSPanel) }
.forEach { $0.orderOut(nil) }
PetWindowManager.shared.restoreWindows()
}
}
@objc private func windowWillClose(_ notification: Notification) {
guard let window = notification.object as? NSWindow,
!(window is NSPanel) else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
let hasVisibleRegularWindow = NSApp.windows.contains { !($0 is NSPanel) && $0.isVisible }
if !hasVisibleRegularWindow {
NSApp.setActivationPolicy(.accessory)
}
}
}
// Clicking the Dock icon while running shows the library
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag { Self.showLibrary() }
return true
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
/// Shows the existing hidden library window or creates a new one via openWindow.
/// Using AppKit directly avoids SwiftUI creating duplicate windows.
static func showLibrary() {
NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true)
// Find any existing regular (non-pet) window, hidden or visible
if let window = NSApp.windows.first(where: { !($0 is NSPanel) }) {
window.makeKeyAndOrderFront(nil)
}
}
}
// MARK: - Menu bar content
struct MenuBarContentView: View {
@Environment(\.openWindow) private var openWindow
@State private var petManager = PetWindowManager.shared
@State private var library = GIFLibraryManager.shared
var body: some View {
Button("Mostrar biblioteca") {
if NSApp.windows.contains(where: { !($0 is NSPanel) }) {
AppDelegate.showLibrary()
} else {
NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true)
openWindow(id: "library")
}
}
Divider()
// Active pets submenu
if petManager.activePets.isEmpty {
Text("Sin mascotas activas")
.foregroundStyle(.secondary)
} else {
Menu("Mascotas activas (\(petManager.activePets.count))") {
ForEach(petManager.activePets) { pet in
if let entry = library.entries.first(where: { $0.id == pet.gifID }) {
Button("Quitar \"\(entry.name)\"") {
petManager.removePet(pet)
}
}
}
if petManager.activePets.count > 1 {
Divider()
Button("Quitar todas") {
let all = petManager.activePets
all.forEach { petManager.removePet($0) }
}
}
}
}
Divider()
Button(petManager.isPaused ? "Reanudar animaciones" : "Pausar animaciones") {
petManager.togglePause()
}
Button(petManager.isLocked ? "Desbloquear posición" : "Bloquear posición") {
petManager.toggleLock()
}
Button(petManager.isWallpaperMode ? "Modo flotante (frente)" : "Modo fondo (detrás)") {
petManager.toggleWallpaperMode()
}
Divider()
Button("Salir de Odorou") {
NSApp.terminate(nil)
}
.keyboardShortcut("q")
}
}

View file

@ -0,0 +1,14 @@
import SwiftUI
struct PetOverlayView: View {
let gifURL: URL
let petID: UUID
@State private var manager = PetWindowManager.shared
var body: some View {
let rotation = manager.activePets.first(where: { $0.id == petID })?.rotation ?? 0
GIFPlayerView(gifURL: gifURL, isPaused: manager.isPaused)
.rotationEffect(.degrees(rotation))
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}

View file

@ -0,0 +1,390 @@
import AppKit
import SwiftUI
// MARK: - PetWindowController
class PetWindowController: NSWindowController {
init(pet: ActivePet, gifURL: URL) {
let screen: NSScreen
if let si = pet.screenIndex, si < NSScreen.screens.count {
screen = NSScreen.screens[si]
} else {
screen = NSScreen.main ?? NSScreen.screens[0]
}
let px = PetWindowManager.pixelSize(for: pet.sizeRatio, on: screen)
let rect = NSRect(x: pet.position.x, y: pet.position.y, width: px, height: px)
let panel = PetPanel(
contentRect: rect,
styleMask: [.borderless, .nonactivatingPanel],
backing: .buffered,
defer: false
)
panel.petID = pet.id
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = false
panel.level = PetWindowManager.shared.isWallpaperMode
? NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.desktopWindow)) + 1)
: .floating
panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
panel.isMovable = false
panel.ignoresMouseEvents = PetWindowManager.shared.isLocked
panel.alphaValue = CGFloat(pet.opacity)
let hostingView = DraggableHostingView(
rootView: AnyView(PetOverlayView(gifURL: gifURL, petID: pet.id)),
petID: pet.id,
initialRotation: pet.rotation,
gifURL: gifURL
)
hostingView.frame = NSRect(origin: .zero, size: CGSize(width: px, height: px))
panel.contentView = hostingView
super.init(window: panel)
}
required init?(coder: NSCoder) { fatalError() }
// MARK: External control
func applyRotation(_ degrees: Double) {
(window?.contentView as? DraggableHostingView)?.applyRotation(degrees)
}
func setLocked(_ locked: Bool) {
window?.ignoresMouseEvents = locked
}
func setWallpaperMode(_ wallpaper: Bool) {
window?.level = wallpaper
? NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.desktopWindow)) + 1)
: .floating
}
func setOpacity(_ opacity: Double) {
window?.alphaValue = CGFloat(opacity)
}
func updateSize(sizeRatio: Double) {
guard let window, let panel = window as? PetPanel else { return }
let screen = window.screen ?? NSScreen.main ?? NSScreen.screens[0]
let newPx = PetWindowManager.pixelSize(for: sizeRatio, on: screen)
let (newFrame, _) = PetWindowController.anchoredFrame(
current: window.frame, newPx: newPx, in: screen.visibleFrame)
window.setFrame(newFrame, display: true, animate: false)
window.contentView?.frame = NSRect(origin: .zero, size: newFrame.size)
(window.contentView as? DraggableHostingView)?.updateTrackingAreas()
PetWindowManager.shared.updatePosition(petID: panel.petID, position: newFrame.origin)
}
/// Computes a new square window frame centered on the current center, clamped to screen bounds.
static func anchoredFrame(current cf: NSRect, newPx: CGFloat, in sf: NSRect)
-> (frame: NSRect, origin: CGPoint) {
let rawX = cf.midX - newPx / 2
let rawY = cf.midY - newPx / 2
let x = max(sf.minX, min(rawX, sf.maxX - newPx))
let y = max(sf.minY, min(rawY, sf.maxY - newPx))
let origin = CGPoint(x: x, y: y)
return (NSRect(origin: origin, size: CGSize(width: newPx, height: newPx)), origin)
}
}
// MARK: - PetPanel
class PetPanel: NSPanel {
var petID: UUID = UUID()
override var canBecomeKey: Bool { false }
override var canBecomeMain: Bool { false }
}
// MARK: - DraggableHostingView
class DraggableHostingView: NSHostingView<AnyView> {
private var petID: UUID = UUID()
private var dragStartScreenLocation: CGPoint?
private var windowStartOrigin: CGPoint?
private var initialRotation: Double = 0
private var cachedImageSize: CGSize?
private var currentRotationDegrees: Double = 0
init(rootView: AnyView, petID: UUID, initialRotation: Double = 0, gifURL: URL? = nil) {
super.init(rootView: rootView)
self.petID = petID
self.initialRotation = initialRotation
self.currentRotationDegrees = initialRotation
wantsLayer = true
if let url = gifURL, let image = NSImage(contentsOf: url) {
cachedImageSize = image.size
}
}
@MainActor required init(rootView: AnyView) {
super.init(rootView: rootView)
wantsLayer = true
}
@MainActor required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Rect occupied by the scaled image, accounting for aspect ratio and current rotation.
// For 90°/270° rotations the image dimensions are transposed to match the visual footprint.
private var displayedImageRect: NSRect {
guard let imageSize = cachedImageSize,
imageSize.width > 0, imageSize.height > 0 else { return bounds }
let rot = abs(currentRotationDegrees).truncatingRemainder(dividingBy: 360)
let transposed = abs(rot - 90) < 1 || abs(rot - 270) < 1
let w = transposed ? imageSize.height : imageSize.width
let h = transposed ? imageSize.width : imageSize.height
let imageAspect = w / h
let viewAspect = bounds.width / bounds.height
let scaledWidth: CGFloat
let scaledHeight: CGFloat
if imageAspect > viewAspect {
scaledWidth = bounds.width
scaledHeight = bounds.width / imageAspect
} else {
scaledWidth = bounds.height * imageAspect
scaledHeight = bounds.height
}
let x = (bounds.width - scaledWidth) / 2
let y = (bounds.height - scaledHeight) / 2
return NSRect(x: x, y: y, width: scaledWidth, height: scaledHeight)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
layer?.backgroundColor = NSColor.clear.cgColor
layer?.isOpaque = false
applyRotation(initialRotation)
}
func applyRotation(_ degrees: Double) {
currentRotationDegrees = degrees
updateTrackingAreas()
}
// Only accept events within the actual displayed (possibly rotated) image area.
override func hitTest(_ point: NSPoint) -> NSView? {
return displayedImageRect.contains(point) ? self : nil
}
// MARK: Cursor
override func updateTrackingAreas() {
super.updateTrackingAreas()
for area in trackingAreas { removeTrackingArea(area) }
addTrackingArea(NSTrackingArea(
rect: displayedImageRect,
options: [.cursorUpdate, .mouseEnteredAndExited, .activeAlways],
owner: self,
userInfo: nil
))
}
override func cursorUpdate(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked else { return }
NSCursor.openHand.set()
}
// MARK: Dragging
override func mouseDown(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked else { return }
dragStartScreenLocation = NSEvent.mouseLocation
windowStartOrigin = window?.frame.origin
NSCursor.closedHand.set()
}
override func mouseDragged(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked,
let startLoc = dragStartScreenLocation,
let startOrigin = windowStartOrigin,
let window else { return }
let cur = NSEvent.mouseLocation
let rawOrigin = CGPoint(
x: startOrigin.x + (cur.x - startLoc.x),
y: startOrigin.y + (cur.y - startLoc.y)
)
// Keep at least 60pt of the pet visible on some screen so it can always be retrieved.
guard !NSScreen.screens.isEmpty else { return }
let allScreens = NSScreen.screens.dropFirst().reduce(NSScreen.screens[0].frame) { $0.union($1.frame) }
let minVisible: CGFloat = 60
let pw = window.frame.width
let ph = window.frame.height
let clampedOrigin = CGPoint(
x: max(allScreens.minX - pw + minVisible, min(rawOrigin.x, allScreens.maxX - minVisible)),
y: max(allScreens.minY - ph + minVisible, min(rawOrigin.y, allScreens.maxY - minVisible))
)
window.setFrameOrigin(clampedOrigin)
PetWindowManager.shared.updatePosition(petID: petID, position: clampedOrigin)
}
override func mouseUp(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked else { return }
dragStartScreenLocation = nil
windowStartOrigin = nil
snapToEdgeIfNeeded()
NSCursor.openHand.set()
}
// MARK: Edge snap + auto-rotate
private func snapToEdgeIfNeeded() {
guard let window, let screen = window.screen ?? NSScreen.main else { return }
let sf = screen.visibleFrame
let wf = window.frame
let threshold: CGFloat = 80
let distBottom = wf.minY - sf.minY
let distTop = sf.maxY - wf.maxY
let distLeft = wf.minX - sf.minX
let distRight = sf.maxX - wf.maxX
let minDist = min(distBottom, distTop, distLeft, distRight)
guard minDist < threshold else { return }
var newOrigin = wf.origin
var newRotation: Double
if distBottom == minDist {
newOrigin.y = sf.minY; newRotation = 0
} else if distTop == minDist {
newOrigin.y = sf.maxY - wf.height; newRotation = 180
} else if distLeft == minDist {
newOrigin.x = sf.minX; newRotation = 90 // 90° CW: head points right (3pm)
} else {
newOrigin.x = sf.maxX - wf.width; newRotation = 270 // 270° CW: head points left (9pm)
}
// Clamp both axes so the pet is fully on screen after snapping.
newOrigin.x = max(sf.minX, min(newOrigin.x, sf.maxX - wf.width))
newOrigin.y = max(sf.minY, min(newOrigin.y, sf.maxY - wf.height))
window.setFrameOrigin(newOrigin)
PetWindowManager.shared.updatePosition(petID: petID, position: newOrigin)
applyRotation(newRotation)
PetWindowManager.shared.updateRotation(petID: petID, rotation: newRotation)
PetWindowManager.shared.controller(for: petID)?.applyRotation(newRotation)
}
// MARK: Right-click context menu
override func rightMouseDown(with event: NSEvent) {
let menu = NSMenu()
menu.autoenablesItems = false
let titleItem = NSMenuItem(title: "Mascota Odorou", action: nil, keyEquivalent: "")
titleItem.isEnabled = false
menu.addItem(titleItem)
menu.addItem(.separator())
let smallerItem = NSMenuItem(title: "Más pequeña (−5%)", action: #selector(makePetSmaller), keyEquivalent: "")
smallerItem.target = self; smallerItem.isEnabled = true
menu.addItem(smallerItem)
let biggerItem = NSMenuItem(title: "Más grande (+5%)", action: #selector(makePetBigger), keyEquivalent: "")
biggerItem.target = self; biggerItem.isEnabled = true
menu.addItem(biggerItem)
// Multi-monitor: show only when more than one screen is available
if NSScreen.screens.count > 1 {
menu.addItem(.separator())
for (i, s) in NSScreen.screens.enumerated() {
let res = "\(Int(s.frame.width))×\(Int(s.frame.height))"
let item = NSMenuItem(title: "Mover a pantalla \(i + 1) (\(res))",
action: #selector(moveToPetScreen(_:)),
keyEquivalent: "")
item.tag = i; item.target = self; item.isEnabled = true
menu.addItem(item)
}
}
menu.addItem(.separator())
let lessOpaqueItem = NSMenuItem(title: "Más transparente (−10%)", action: #selector(makePetLessOpaque), keyEquivalent: "")
lessOpaqueItem.target = self; lessOpaqueItem.isEnabled = true
menu.addItem(lessOpaqueItem)
let moreOpaqueItem = NSMenuItem(title: "Más opaca (+10%)", action: #selector(makePetMoreOpaque), keyEquivalent: "")
moreOpaqueItem.target = self; moreOpaqueItem.isEnabled = true
menu.addItem(moreOpaqueItem)
menu.addItem(.separator())
let removeItem = NSMenuItem(title: "Quitar mascota", action: #selector(removePet), keyEquivalent: "")
removeItem.target = self; removeItem.isEnabled = true
menu.addItem(removeItem)
NSMenu.popUpContextMenu(menu, with: event, for: self)
}
@objc func removePet() {
guard let pet = PetWindowManager.shared.activePets.first(where: { $0.id == petID }) else { return }
PetWindowManager.shared.removePet(pet)
}
@objc func makePetSmaller() { resizePet(delta: -0.05) }
@objc func makePetBigger() { resizePet(delta: +0.05) }
@objc func moveToPetScreen(_ sender: NSMenuItem) {
PetWindowManager.shared.movePet(petID: petID, toScreenIndex: sender.tag)
}
private func resizePet(delta: Double) {
guard let window,
let pet = PetWindowManager.shared.activePets.first(where: { $0.id == petID }) else { return }
let newRatio = max(0.05, min(0.50, pet.sizeRatio + delta))
PetWindowManager.shared.updateSize(petID: petID, sizeRatio: newRatio)
let screen = window.screen ?? NSScreen.main ?? NSScreen.screens[0]
let newPx = PetWindowManager.pixelSize(for: newRatio, on: screen)
let sf = screen.visibleFrame
let cf = window.frame
let (newFrame, newOrigin) = PetWindowController.anchoredFrame(
current: cf, newPx: newPx, in: sf)
window.setFrame(newFrame, display: true, animate: false)
self.frame = NSRect(origin: .zero, size: newFrame.size)
updateTrackingAreas()
PetWindowManager.shared.updatePosition(petID: petID, position: newOrigin)
}
// MARK: Opacity
@objc func makePetLessOpaque() { changeOpacity(delta: -0.1) }
@objc func makePetMoreOpaque() { changeOpacity(delta: +0.1) }
private func changeOpacity(delta: Double) {
guard let pet = PetWindowManager.shared.activePets.first(where: { $0.id == petID }) else { return }
let newOpacity = max(0.1, min(1.0, pet.opacity + delta))
PetWindowManager.shared.updateOpacity(petID: petID, opacity: newOpacity)
window?.alphaValue = CGFloat(newOpacity)
}
// MARK: Mouse proximity effect
override func mouseEntered(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked,
let window, window.alphaValue < 0.99 else { return }
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = 0.2
window.animator().alphaValue = 1.0
}
}
override func mouseExited(with event: NSEvent) {
guard !PetWindowManager.shared.isLocked else { return }
if let pet = PetWindowManager.shared.activePets.first(where: { $0.id == petID }) {
let target = CGFloat(pet.opacity)
guard let window, abs(window.alphaValue - target) > 0.01 else { return }
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = 0.3
window.animator().alphaValue = target
}
}
}
}

View file

@ -0,0 +1,247 @@
import AppKit
import Observation
import ServiceManagement
import UserNotifications
@Observable
class PetWindowManager {
static let shared = PetWindowManager()
var activePets: [ActivePet] = []
var isPaused: Bool = false
var isLocked: Bool = false
var isWallpaperMode: Bool = false
var isLaunchAtLoginEnabled: Bool = false
private var controllers: [UUID: PetWindowController] = [:]
private var appSupportBase: URL {
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
return base.appendingPathComponent("Odorou", isDirectory: true)
}
private var persistenceURL: URL { appSupportBase.appendingPathComponent("active_pets.json") }
private var settingsURL: URL { appSupportBase.appendingPathComponent("settings.json") }
private init() {
loadGlobalSettings()
loadPets()
isLaunchAtLoginEnabled = SMAppService.mainApp.status == .enabled
}
// MARK: Window lifecycle
func restoreWindows() {
for pet in activePets {
if let entry = GIFLibraryManager.shared.entries.first(where: { $0.id == pet.gifID }) {
openWindow(for: pet, gifURL: GIFLibraryManager.shared.gifURL(for: entry))
}
}
}
func addPet(gifEntry: GIFEntry, edge: ScreenEdge = .bottomRight) {
let ratio: Double = 0.15
let position = defaultPosition(for: edge, sizeRatio: ratio)
let rotation = defaultRotation(for: edge)
let pet = ActivePet(id: UUID(), gifID: gifEntry.id, position: position,
sizeRatio: ratio, rotation: rotation)
activePets.append(pet)
savePets()
openWindow(for: pet, gifURL: GIFLibraryManager.shared.gifURL(for: gifEntry))
notifyPetAdded(gifEntry)
}
func removePet(_ pet: ActivePet) {
controllers[pet.id]?.close()
controllers.removeValue(forKey: pet.id)
activePets.removeAll { $0.id == pet.id }
savePets()
}
// MARK: Per-pet updates
func updatePosition(petID: UUID, position: CGPoint) {
guard let idx = activePets.firstIndex(where: { $0.id == petID }) else { return }
activePets[idx].position = position
savePets()
}
func updateSize(petID: UUID, sizeRatio: Double) {
guard let idx = activePets.firstIndex(where: { $0.id == petID }) else { return }
activePets[idx].sizeRatio = sizeRatio
savePets()
}
func updateRotation(petID: UUID, rotation: Double) {
guard let idx = activePets.firstIndex(where: { $0.id == petID }) else { return }
activePets[idx].rotation = rotation
savePets()
}
func updateOpacity(petID: UUID, opacity: Double) {
guard let idx = activePets.firstIndex(where: { $0.id == petID }) else { return }
activePets[idx].opacity = opacity
savePets()
}
func movePet(petID: UUID, toScreenIndex screenIndex: Int) {
guard screenIndex < NSScreen.screens.count,
let idx = activePets.firstIndex(where: { $0.id == petID }) else { return }
let screen = NSScreen.screens[screenIndex]
let sf = screen.visibleFrame
let px = PetWindowManager.pixelSize(for: activePets[idx].sizeRatio, on: screen)
let newPos = CGPoint(x: sf.midX - px / 2, y: sf.midY - px / 2)
activePets[idx].position = newPos
activePets[idx].screenIndex = screenIndex
controllers[petID]?.window?.setFrameOrigin(newPos)
savePets()
}
// MARK: Global controls
func setGlobalSize(_ ratio: Double) {
for i in activePets.indices {
activePets[i].sizeRatio = ratio
controllers[activePets[i].id]?.updateSize(sizeRatio: ratio)
}
savePets()
}
func togglePause() {
isPaused.toggle()
saveGlobalSettings()
// Animation state is updated via @Observable in PetOverlayView → GIFPlayerView
}
func toggleLock() {
isLocked.toggle()
controllers.values.forEach { $0.setLocked(isLocked) }
saveGlobalSettings()
}
func toggleWallpaperMode() {
isWallpaperMode.toggle()
controllers.values.forEach { $0.setWallpaperMode(isWallpaperMode) }
saveGlobalSettings()
}
func setLaunchAtLogin(_ enabled: Bool) {
do {
if enabled { try SMAppService.mainApp.register() }
else { try SMAppService.mainApp.unregister() }
isLaunchAtLoginEnabled = enabled
} catch {
print("Launch at login error: \(error)")
}
}
// MARK: Preset export / import
func exportPreset(to url: URL) throws {
let preset = Preset(pets: activePets, isPaused: isPaused,
isLocked: isLocked, isWallpaperMode: isWallpaperMode)
try JSONEncoder().encode(preset).write(to: url)
}
func importPreset(from url: URL) throws {
let preset = try JSONDecoder().decode(Preset.self, from: Data(contentsOf: url))
controllers.values.forEach { $0.close() }
controllers.removeAll()
activePets = preset.pets
isPaused = preset.isPaused
isLocked = preset.isLocked
isWallpaperMode = preset.isWallpaperMode
savePets()
saveGlobalSettings()
restoreWindows()
}
// MARK: Helpers
static func pixelSize(for ratio: Double, on screen: NSScreen) -> CGFloat {
let dim = min(screen.visibleFrame.width, screen.visibleFrame.height)
return CGFloat(ratio) * dim
}
/// Exposes the controller for a given pet ID (used by DraggableHostingView for snap+rotate).
func controller(for petID: UUID) -> PetWindowController? {
controllers[petID]
}
// MARK: Private
private struct Preset: Codable {
let pets: [ActivePet]
let isPaused: Bool
let isLocked: Bool
let isWallpaperMode: Bool
}
private func openWindow(for pet: ActivePet, gifURL: URL) {
let controller = PetWindowController(pet: pet, gifURL: gifURL)
controllers[pet.id] = controller
controller.window?.orderFront(nil)
}
private func defaultPosition(for edge: ScreenEdge, sizeRatio: Double) -> CGPoint {
guard let screen = NSScreen.main else { return .zero }
let f = screen.visibleFrame
let size = PetWindowManager.pixelSize(for: sizeRatio, on: screen)
// 2px margin so the window edge lands just flush against the screen edge.
let m: CGFloat = 2
switch edge {
case .bottom: return CGPoint(x: f.midX - size / 2, y: f.minY + m)
case .top: return CGPoint(x: f.midX - size / 2, y: f.maxY - size - m)
case .left: return CGPoint(x: f.minX + m, y: f.midY - size / 2)
case .right: return CGPoint(x: f.maxX - size - m, y: f.midY - size / 2)
case .bottomLeft: return CGPoint(x: f.minX + m, y: f.minY + m)
case .bottomRight: return CGPoint(x: f.maxX - size - m, y: f.minY + m)
case .topLeft: return CGPoint(x: f.minX + m, y: f.maxY - size - m)
case .topRight: return CGPoint(x: f.maxX - size - m, y: f.maxY - size - m)
case .center: return CGPoint(x: f.midX - size / 2, y: f.midY - size / 2)
}
}
private func defaultRotation(for edge: ScreenEdge) -> Double {
switch edge {
case .top, .topLeft, .topRight: return 180
case .left: return 90 // 90° CW → head right (3pm)
case .right: return 270 // 270° CW → head left (9pm)
default: return 0
}
}
private func savePets() {
try? FileManager.default.createDirectory(at: appSupportBase, withIntermediateDirectories: true)
guard let data = try? JSONEncoder().encode(activePets) else { return }
try? data.write(to: persistenceURL)
}
private func loadPets() {
guard let data = try? Data(contentsOf: persistenceURL),
let loaded = try? JSONDecoder().decode([ActivePet].self, from: data) else { return }
activePets = loaded
}
private func saveGlobalSettings() {
try? FileManager.default.createDirectory(at: appSupportBase, withIntermediateDirectories: true)
let s = GlobalSettings(isPaused: isPaused, isLocked: isLocked, isWallpaperMode: isWallpaperMode)
guard let data = try? JSONEncoder().encode(s) else { return }
try? data.write(to: settingsURL)
}
private func loadGlobalSettings() {
guard let data = try? Data(contentsOf: settingsURL),
let s = try? JSONDecoder().decode(GlobalSettings.self, from: data) else { return }
isPaused = s.isPaused; isLocked = s.isLocked; isWallpaperMode = s.isWallpaperMode
}
private func notifyPetAdded(_ entry: GIFEntry) {
let content = UNMutableNotificationContent()
content.title = "¡Nueva mascota!"
content.body = "\(entry.name) ahora habita en tu escritorio ✨"
content.sound = .default
UNUserNotificationCenter.current().add(
UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
)
}
}

BIN
Odorou/nlogo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 KiB

BIN
Odorou/odorou.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

157
README.md Normal file
View file

@ -0,0 +1,157 @@
# Odorou
A macOS desktop-pet app that displays animated GIFs and WebP images as transparent floating windows on your screen. Pets live on top of (or behind) your other windows, snap to screen edges, and persist across relaunches.
---
## Features
- **Import** GIFs and WebP via file picker, drag & drop onto the library window, or direct URL download
- **Animated playback** with pause/resume, preserving frame timing
- **Transparent borderless windows** — pets float over all apps with no chrome
- **Drag freely** — snap to any screen edge with automatic rotation (head always faces inward)
- **Per-pet controls** via right-click menu:
- Resize ±5% (`sizeRatio` 5 %–50 % of the shortest screen dimension)
- Opacity ±10 % (10 %–100 %)
- Move to a specific monitor (multi-display)
- **Global controls** in the menu bar:
- Pause / resume all animations
- Lock / unlock pet positions
- Wallpaper mode (send pets behind all windows)
- Remove individual pets or all at once
- **Background removal** — one-click tool strips solid-color backgrounds from GIFs using corner color sampling and per-frame pixel comparison
- **Library management**: rename (double-click name), search, delete
- **Preset export / import** — save and restore the full pet layout as a JSON file
- **Launch at login** via `SMAppService`
- **Local notifications** when a new pet is added
- **First-launch onboarding** overlay (dismissed once, stored in `@AppStorage`)
---
## Architecture
```
OdorouApp (SwiftUI App + MenuBarExtra)
├── AppDelegate NSApplicationDelegate — activation policy, window lifecycle
├── ContentView Main library window (NavigationSplitView)
│ ├── Sidebar Active pets list + global size slider
│ ├── LibraryGrid GIFLibraryCard grid (filterable)
│ └── Toolbar Edge picker, URL import, settings popover
│
├── GIFLibraryManager @Observable singleton — library CRUD + file persistence
├── GIFLibraryCard Card view — thumbnail, hover overlay (wand/trash), inline rename
├── GIFPlayerView NSViewRepresentable wrapping NSImageView for GIF/WebP playback
│
├── PetWindowManager @Observable singleton — pet lifecycle, global controls, persistence
├── PetWindowController NSWindowController per pet — owns the transparent NSPanel
│ ├── DraggableHostingView NSHostingView<AnyView> — drag, snap, hit-test, cursor, menus
│ └── PetOverlayView SwiftUI view rendered inside each pet window
│
├── BackgroundRemover Removes solid backgrounds from GIFs (CoreGraphics + simd)
└── Models GIFEntry, ActivePet, GlobalSettings, ScreenEdge
```
---
## Key Files
| File | Responsibility |
|---|---|
| `OdorouApp.swift` | App entry point, `MenuBarExtra`, `AppDelegate` |
| `ContentView.swift` | Library window UI, URL import, onboarding overlay |
| `GIFLibraryManager.swift` | Import, delete, rename GIFs; JSON persistence |
| `GIFPlayerView.swift` | `NSImageView` wrapper that animates GIF/WebP frames |
| `PetWindowManager.swift` | Create/remove/update pet windows; global state |
| `PetWindowController.swift` | `NSPanel` + `DraggableHostingView` per pet |
| `PetOverlayView.swift` | Renders `GIFPlayerView` with `rotationEffect` inside each pet panel |
| `BackgroundRemover.swift` | Frame-by-frame alpha keying based on corner color sampling |
| `Models.swift` | `GIFEntry`, `ActivePet`, `GlobalSettings`, `ScreenEdge` |
---
## Data Persistence
All data lives under `~/Library/Application Support/Odorou/`:
| Path | Content |
|---|---|
| `gifs/` | Imported GIF / WebP files (renamed to `<UUID>.<ext>`) |
| `library.json` | `[GIFEntry]` — id, filename, display name, date added |
| `active_pets.json` | `[ActivePet]` — position, size ratio, rotation, opacity, screen index |
| `settings.json` | `GlobalSettings` — isPaused, isLocked, isWallpaperMode |
`@AppStorage("hasSeenOnboarding")` in `UserDefaults` controls first-launch onboarding.
---
## Pet Window Internals
Each pet is a **square** `NSPanel` sized to `sizeRatio × min(screenWidth, screenHeight)`:
```
NSPanel (PetPanel)
└── DraggableHostingView : NSHostingView<AnyView>
└── PetOverlayView (SwiftUI)
└── GIFPlayerView
.rotationEffect(.degrees(rotation))
.frame(maxWidth: .infinity, maxHeight: .infinity)
```
**Why square windows?**
SwiftUI's `.rotationEffect` is cosmetic — it rotates rendering but not layout bounds. A square window ensures the GIF can be displayed at any rotation angle (0°, 90°, 180°, 270°) without clipping, with `NSImageView.scaleProportionallyUpOrDown` inscribing the image correctly.
**Rotation convention (SwiftUI CW, Y-down):**
| Edge | Degrees | Head direction |
|---|---|---|
| Bottom | 0° | Up (12pm) |
| Top | 180° | Down (6pm) |
| Left | 90° | Right (3pm) |
| Right | 270° | Left (9pm) |
**Hit testing** uses `displayedImageRect` — the aspect-ratio-correct image bounds inside the square window, with dimensions transposed for 90°/270° rotations — so clicks in the transparent letterbox/pillarbox areas pass through to windows below.
---
## Snap to Edge
On `mouseUp`, `snapToEdgeIfNeeded()` fires if any window edge is within 80 pt of the screen's `visibleFrame`. The closest edge wins; the window is repositioned flush and the pet rotates to face inward. Both axes are clamped so the pet stays fully on screen.
---
## Background Removal
`BackgroundRemover.removeBackground(from:tolerance:)`:
1. Samples the four corners of frame 0 to determine background color (as `SIMD3<Float>`)
2. If all corners agree within a threshold, uses the average; otherwise uses the top-left corner
3. For each frame, pixels within `tolerance` Euclidean distance of the background color are set fully transparent (`alpha = 0`)
4. Writes the result to a temp file then atomically replaces the source via `FileManager.replaceItemAt`
Default `tolerance` is `0.20`, which works well for solid anime-style backgrounds.
---
## Entitlements
| Entitlement | Reason |
|---|---|
| `com.apple.security.app-sandbox` | App is sandboxed |
| `com.apple.security.network.client` | URL import (download GIFs from arbitrary URLs) |
| `com.apple.security.files.user-selected.read-only` | File importer (`fileImporter` modifier) |
---
## Requirements
- macOS 15+ (uses `@Observable`, `ContentUnavailableView`, `MenuBarExtra`)
- Xcode 16+
- Swift 5.10+
---
## Build & Run
Open `Odorou.xcodeproj` in Xcode and press **⌘R**. No external dependencies — all frameworks are system-provided.
The app runs as a **menu bar accessory** (no Dock icon at startup). Click the menu bar icon to show the library window.