soar-package 0.2.2

Package format handling for soar package manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Common package integration utilities.
//!
//! This module provides functions for desktop integration including
//! icon handling, desktop file creation, and portable directory setup.

use std::{
    env,
    ffi::OsStr,
    fs::{self, File},
    io::{BufReader, BufWriter, Write},
    path::{Path, PathBuf},
};

use image::{imageops::FilterType, DynamicImage, GenericImageView};
use regex::Regex;
use soar_config::config::{get_config, is_system_mode};
use soar_utils::{
    fs::{create_symlink, walk_dir},
    path::{desktop_dir, icons_dir},
};
use tracing::{debug, trace};

use super::{
    appimage::integrate_appimage, get_file_type, wrappe::setup_wrappe_portable_dir, PackageFormat,
};
use crate::{
    error::{ErrorContext, PackageError, Result},
    traits::PackageExt,
};

/// Supported icon dimensions for desktop integration.
const SUPPORTED_DIMENSIONS: &[(u32, u32)] = &[
    (16, 16),
    (24, 24),
    (32, 32),
    (48, 48),
    (64, 64),
    (72, 72),
    (80, 80),
    (96, 96),
    (128, 128),
    (192, 192),
    (256, 256),
    (512, 512),
];

fn find_nearest_supported_dimension(width: u32, height: u32) -> (u32, u32) {
    SUPPORTED_DIMENSIONS
        .iter()
        .min_by_key(|&&(w, h)| {
            let width_diff = (w as i32 - width as i32).abs();
            let height_diff = (h as i32 - height as i32).abs();
            width_diff + height_diff
        })
        .cloned()
        .unwrap_or((width, height))
}

fn normalize_image(image: DynamicImage) -> DynamicImage {
    let (width, height) = image.dimensions();
    let (new_width, new_height) = find_nearest_supported_dimension(width, height);

    if (width, height) != (new_width, new_height) {
        image.resize(new_width, new_height, FilterType::Lanczos3)
    } else {
        image
    }
}

/// Creates a symlink for an icon in the appropriate icons directory.
///
/// The icon is normalized to a supported dimension and symlinked to
/// `~/.local/share/icons/{WxH}/apps/{name}-soar.{ext}`.
///
/// # Arguments
///
/// * `real_path` - Path to the actual icon file
///
/// # Returns
///
/// The path to the created symlink.
///
/// # Errors
///
/// Returns [`PackageError`] if image processing or symlink creation fails.
pub fn symlink_icon<P: AsRef<Path>>(real_path: P) -> Result<PathBuf> {
    let real_path = real_path.as_ref();
    trace!(path = %real_path.display(), "creating icon symlink");
    let icon_name = real_path.file_stem().unwrap();
    let ext = real_path.extension();

    let (w, h) = if ext == Some(OsStr::new("svg")) {
        (128, 128)
    } else {
        let image = image::open(real_path)?;
        let (orig_w, orig_h) = image.dimensions();

        let normalized_image = normalize_image(image);
        let (w, h) = normalized_image.dimensions();

        if (w, h) != (orig_w, orig_h) {
            normalized_image.save(real_path)?;
        }

        (w, h)
    };

    let final_path = icons_dir(is_system_mode())
        .join(format!("{w}x{h}"))
        .join("apps")
        .join(format!(
            "{}-soar.{}",
            icon_name.to_string_lossy(),
            ext.unwrap_or_default().to_string_lossy()
        ));

    if final_path.is_symlink() {
        fs::remove_file(&final_path)
            .with_context(|| format!("removing existing symlink at {}", final_path.display()))?;
    }

    create_symlink(real_path, &final_path)?;
    debug!(icon = %final_path.display(), "icon symlink created");
    Ok(final_path)
}

/// Creates a symlink for a desktop file with modified fields.
///
/// Updates the Icon, Exec, and TryExec fields in the desktop file to point
/// to the installed package, then creates a symlink in the applications
/// directory.
///
/// # Arguments
///
/// * `real_path` - Path to the desktop file
/// * `package` - Package metadata
///
/// # Returns
///
/// The path to the created symlink.
///
/// # Errors
///
/// Returns [`PackageError`] if file operations fail.
pub fn symlink_desktop<P: AsRef<Path>, T: PackageExt>(
    real_path: P,
    package: &T,
) -> Result<PathBuf> {
    let pkg_name = package.pkg_name();
    let real_path = real_path.as_ref();
    trace!(path = %real_path.display(), pkg_name = pkg_name, "creating desktop file symlink");
    let content = fs::read_to_string(real_path)
        .with_context(|| format!("reading content of desktop file: {}", real_path.display()))?;
    let file_name = real_path.file_stem().unwrap();

    let bin_path = get_config().get_bin_path()?;

    let final_content = {
        let re = Regex::new(r"(?m)^(Icon|Exec|TryExec)=(.*)").unwrap();

        re.replace_all(&content, |caps: &regex::Captures| {
            match &caps[1] {
                "Icon" => format!("Icon={}-soar", file_name.to_string_lossy()),
                "Exec" | "TryExec" => {
                    let value = &caps[0];
                    let new_value = format!("{}/{}", &bin_path.display(), pkg_name);

                    if value.contains("{{pkg_path}}") {
                        value.replace("{{pkg_path}}", &new_value)
                    } else {
                        format!("{}={}", &caps[1], new_value)
                    }
                }
                _ => unreachable!(),
            }
        })
        .to_string()
    };

    let mut writer = BufWriter::new(
        File::create(real_path)
            .with_context(|| format!("creating desktop file {}", real_path.display()))?,
    );
    writer
        .write_all(final_content.as_bytes())
        .with_context(|| format!("writing desktop file to {}", real_path.display()))?;

    let final_path =
        desktop_dir(is_system_mode()).join(format!("{}-soar.desktop", file_name.to_string_lossy()));

    if final_path.is_symlink() {
        fs::remove_file(&final_path)
            .with_context(|| format!("removing existing symlink at {}", final_path.display()))?;
    }

    create_symlink(real_path, &final_path)?;
    debug!(desktop = %final_path.display(), "desktop file symlink created");
    Ok(final_path)
}

/// Creates a portable link for package data directories.
///
/// # Arguments
///
/// * `portable_path` - Base path for portable data
/// * `real_path` - Path to link to
/// * `pkg_name` - Package name
/// * `extension` - Extension for the portable directory (e.g., "home", "config")
///
/// # Errors
///
/// Returns [`PackageError`] if directory creation or symlink fails.
pub fn create_portable_link<P: AsRef<Path>>(
    portable_path: P,
    real_path: P,
    pkg_name: &str,
    extension: &str,
) -> Result<()> {
    let base_dir = env::current_dir()
        .map_err(|_| PackageError::Custom("Error retrieving current directory".into()))?;
    let portable_path = portable_path.as_ref();
    let portable_path = if portable_path.is_absolute() {
        portable_path
    } else {
        &base_dir.join(portable_path)
    };
    let portable_path = portable_path.join(pkg_name).with_extension(extension);

    fs::create_dir_all(&portable_path)
        .with_context(|| format!("creating directory {}", portable_path.display()))?;
    create_symlink(&portable_path, real_path)?;
    Ok(())
}

/// Sets up portable directories for a package.
///
/// Creates symlinks for home, config, share, and cache directories based
/// on the provided portable path options.
///
/// # Arguments
///
/// * `bin_path` - Path to the package binary
/// * `package` - Package metadata
/// * `portable` - Base portable path (overrides all individual paths)
/// * `portable_home` - Path for home directory
/// * `portable_config` - Path for config directory
/// * `portable_share` - Path for share directory
/// * `portable_cache` - Path for cache directory
///
/// # Errors
///
/// Returns [`PackageError`] if directory creation or symlink fails.
pub fn setup_portable_dir<P: AsRef<Path>, T: PackageExt>(
    bin_path: P,
    package: &T,
    portable: Option<&str>,
    portable_home: Option<&str>,
    portable_config: Option<&str>,
    portable_share: Option<&str>,
    portable_cache: Option<&str>,
) -> Result<()> {
    let portable_dir_base = get_config().get_portable_dirs()?.join(format!(
        "{}-{}",
        package.pkg_name(),
        package.pkg_id()
    ));
    let bin_path = bin_path.as_ref();

    let pkg_name = package.pkg_name();
    let pkg_config = bin_path.with_extension("config");
    let pkg_home = bin_path.with_extension("home");
    let pkg_share = bin_path.with_extension("share");
    let pkg_cache = bin_path.with_extension("cache");

    let (portable_home, portable_config, portable_share, portable_cache) =
        if let Some(portable) = portable {
            (
                Some(portable),
                Some(portable),
                Some(portable),
                Some(portable),
            )
        } else {
            (
                portable_home,
                portable_config,
                portable_share,
                portable_cache,
            )
        };

    for (opt, target, kind) in [
        (portable_home, &pkg_home, "home"),
        (portable_config, &pkg_config, "config"),
        (portable_share, &pkg_share, "share"),
        (portable_cache, &pkg_cache, "cache"),
    ] {
        if let Some(val) = opt {
            let base = if val.is_empty() {
                &portable_dir_base
            } else {
                Path::new(val)
            };
            create_portable_link(base, target, pkg_name, kind)?;
        }
    }

    Ok(())
}

/// Integrates a package with the desktop environment.
///
/// This function handles format-specific integration including:
/// - Desktop file symlinking
/// - Icon symlinking with dimension normalization
/// - AppImage resource extraction
/// - Portable directory setup
///
/// # Arguments
///
/// * `install_dir` - Directory where the package is installed
/// * `package` - Package metadata
/// * `bin_path` - Optional path to the actual binary (if None, uses install_dir/pkg_name)
/// * `portable` - Base portable path
/// * `portable_home` - Path for home directory
/// * `portable_config` - Path for config directory
/// * `portable_share` - Path for share directory
/// * `portable_cache` - Path for cache directory
///
/// # Errors
///
/// Returns [`PackageError`] if integration fails.
#[allow(clippy::too_many_arguments)]
pub async fn integrate_package<P: AsRef<Path>, T: PackageExt>(
    install_dir: P,
    package: &T,
    bin_path: Option<&Path>,
    portable: Option<&str>,
    portable_home: Option<&str>,
    portable_config: Option<&str>,
    portable_share: Option<&str>,
    portable_cache: Option<&str>,
) -> Result<()> {
    let install_dir = install_dir.as_ref();
    let pkg_name = package.pkg_name();
    debug!(pkg_name = pkg_name, install_dir = %install_dir.display(), "integrating package with desktop environment");
    let bin_path = bin_path
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| install_dir.join(pkg_name));

    let mut has_desktop = false;
    let mut has_icon = false;
    let mut symlink_action = |path: &Path| -> Result<()> {
        let ext = path.extension();
        if ext == Some(OsStr::new("desktop")) {
            has_desktop = true;
            symlink_desktop(path, package)?;
        }
        Ok(())
    };
    walk_dir(install_dir, &mut symlink_action)?;

    let mut symlink_action = |path: &Path| -> Result<()> {
        let ext = path.extension();
        if ext == Some(OsStr::new("png")) || ext == Some(OsStr::new("svg")) {
            has_icon = true;
            symlink_icon(path)?;
        }
        Ok(())
    };
    walk_dir(install_dir, &mut symlink_action)?;

    let mut reader = BufReader::new(
        File::open(&bin_path).with_context(|| format!("opening {}", bin_path.display()))?,
    );
    let file_type = get_file_type(&mut reader)?;

    trace!(file_type = ?file_type, "detected package format");
    match file_type {
        PackageFormat::AppImage | PackageFormat::RunImage => {
            if matches!(file_type, PackageFormat::AppImage) {
                trace!("integrating AppImage resources");
                let _ = integrate_appimage(install_dir, &bin_path, package, has_icon, has_desktop)
                    .await;
            }
            trace!("setting up portable directories");
            setup_portable_dir(
                bin_path,
                package,
                portable,
                portable_home,
                portable_config,
                portable_share,
                portable_cache,
            )?;
        }
        PackageFormat::FlatImage => {
            trace!("setting up FlatImage portable config");
            setup_portable_dir(
                format!("{}/.{}", bin_path.parent().unwrap().display(), pkg_name),
                package,
                None,
                None,
                portable_config,
                None,
                None,
            )?;
        }
        PackageFormat::Wrappe => {
            trace!("setting up Wrappe portable directory");
            setup_wrappe_portable_dir(&bin_path, pkg_name, portable)?;
        }
        _ => {}
    }

    debug!(
        pkg_name = pkg_name,
        has_desktop = has_desktop,
        has_icon = has_icon,
        "package integration completed"
    );
    Ok(())
}