Skip to content

Commit

Permalink
Fix overwritting and add proper logging
Browse files Browse the repository at this point in the history
  • Loading branch information
blopker committed Nov 3, 2024
1 parent 75eaab7 commit e17a283
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 32 deletions.
20 changes: 14 additions & 6 deletions lib/compressor.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'dart:io';

import 'package:alic/imagefiles.dart';
import 'package:alic/log.dart';
import 'package:alic/src/rust/api/compressor.dart';
import 'package:alic/workqueue.dart';
import 'package:flutter/foundation.dart';

import './config.dart';

Expand Down Expand Up @@ -44,8 +44,7 @@ void compressor(ImageFile imageFile, void Function(ImageFile) callback) {
timer.stop();
}

debugPrint(
'Compressed ${imageFile.file} in ${timer.elapsedMilliseconds}ms');
log.d('Compressed ${imageFile.file} in ${timer.elapsedMilliseconds}ms');

final outFile = File(result.outPath);
final sizeAfterOptimization = await outFile.length();
Expand All @@ -59,14 +58,23 @@ void compressor(ImageFile imageFile, void Function(ImageFile) callback) {
return;
}
// Success!
if (!config.enablePostfix && config.convertExtension == null) {
// If postfix is disabled (and no conversion is needed), replace the original file with the optimized one
if (!config.enablePostfix) {
// If postfix is disabled, replace the original file with the optimized one
File(imageFile.path).delete();
outFile.rename(imageFile.path);
outFile.rename(replaceLast(outFile.path, config.postfix, ''));
}
callback(imageFile.copyWith(
sizeAfterOptimization: sizeAfterOptimization,
status: ImageFileStatus.success,
));
});
}

String replaceLast(String string, String from, String to) {
final lastIndex = string.lastIndexOf(from);
if (lastIndex < 0) return string;

return string.substring(0, lastIndex) +
to +
string.substring(lastIndex + from.length);
}
5 changes: 3 additions & 2 deletions lib/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:alic/log.dart';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:signals/signals.dart' as signals;
Expand Down Expand Up @@ -47,15 +48,15 @@ class Config {
static void init() {
signal.value = readConfig();
signals.effect(() {
debugPrint('Config changed: ${signal.value}');
log.d('Config changed: ${signal.value}');
writeConfig(signal.value);
});
}

static ConfigData readConfig() {
ensureConfigExists();
var configData = configFile.readAsStringSync();
debugPrint('Read config: $configData');
log.d('Read config: $configData');
return ConfigData.fromJson(jsonDecode(configData));
}

Expand Down
9 changes: 5 additions & 4 deletions lib/dropper.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io';

import 'package:alic/log.dart';
import 'package:alic/imagefiles.dart';
import 'package:flutter/material.dart';
import 'package:super_clipboard/super_clipboard.dart';
Expand Down Expand Up @@ -64,7 +65,7 @@ class _ImageDropRegionState extends State<ImageDropRegion> {
formats: Formats.standardFormats,
hitTestBehavior: HitTestBehavior.opaque,
onDropOver: (event) {
debugPrint('onDropOver');
log.d('onDropOver');
for (var item in event.session.items) {
for (var format in formats) {
if (item.canProvide(format)) {
Expand All @@ -75,15 +76,15 @@ class _ImageDropRegionState extends State<ImageDropRegion> {
return DropOperation.none;
},
onDropEnter: (event) {
debugPrint('onDropEnter');
log.d('onDropEnter');
showOverlay();
},
onDropLeave: (event) {
debugPrint('onDropLeave');
log.d('onDropLeave');
hideOverlay();
},
onPerformDrop: (event) async {
debugPrint('onPerformDrop');
log.d('onPerformDrop');
final items = event.session.items;
final mixedPaths = <String>[];
for (var item in items) {
Expand Down
3 changes: 2 additions & 1 deletion lib/imagefiles.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io';

import 'package:alic/log.dart';
import 'package:alic/compressor.dart';
import 'package:flutter/material.dart';
import 'package:signals/signals.dart' as signals;
Expand Down Expand Up @@ -181,7 +182,7 @@ class ImageFiles {

static void compress(ImageFile file) {
compressor(file, (p0) {
debugPrint('Update: $p0');
log.d('Update: $p0');
update(p0);
});
}
Expand Down
3 changes: 3 additions & 0 deletions lib/log.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import 'package:logger/logger.dart';

final log = Logger();
3 changes: 2 additions & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:alic/imagefiles.dart';
import 'package:alic/settings.dart';
import 'package:alic/src/rust/frb_generated.dart';
import 'package:alic/table.dart';
import 'package:alic/log.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:signals/signals_flutter.dart';
Expand Down Expand Up @@ -63,7 +64,7 @@ class _HomePageState extends State<HomePage> {
body: MacMenuBar(
child: ImageDropRegion(
onDrop: (files) {
debugPrint('Dropped: $files');
log.d('Dropped: $files');
ImageFiles.add(files);
},
dropOverlay: Container(
Expand Down
3 changes: 2 additions & 1 deletion lib/table.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:open_file_macos/open_file_macos.dart';
import 'package:signals/signals_flutter.dart';
import 'package:alic/log.dart';

final _openFileMacosPlugin = OpenFileMacos();

Expand All @@ -20,7 +21,7 @@ class _FilesTableState extends State<FilesTable> with SignalsMixin {

@override
void initState() {
debugPrint('initState');
log.d('initState');
super.initState();
createEffect(() {
setState(() {
Expand Down
7 changes: 4 additions & 3 deletions lib/update.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:alic/log.dart';

import 'strings.dart';

Expand Down Expand Up @@ -52,16 +53,16 @@ Future<Update?> checkForUpdate({bool force = false}) async {

// 3. Compare
if (latestBuildNumber > currentBuildNumber || force) {
debugPrint('Update available: ${update.version}');
log.d('Update available: ${update.version}');
return update;
} else {
debugPrint('You have the latest version');
log.d('You have the latest version');
return null;
}
}

void main() async {
final buildNumber = await getLatestBuildNumber();
// ignore: avoid_print
print('Latest Build Number: $buildNumber');
log.d('Latest Build Number: $buildNumber');
}
5 changes: 3 additions & 2 deletions lib/workqueue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:alic/log.dart';

class _WorkQueue {
int _maxWorkers = max(2, Platform.numberOfProcessors - 2);
Expand Down Expand Up @@ -46,9 +47,9 @@ void main(List<String> args) {
var queue = _WorkQueue(maxWorkers: 4);
for (var i = 0; i < 10; i++) {
queue.add(() async {
print('Running $i');
log.d('Running $i');
await Future.delayed(const Duration(seconds: 1));
print('Done $i');
log.d('Done $i');
});
}
queue.join();
Expand Down
2 changes: 1 addition & 1 deletion macos/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: f0c21717cb7ee9112f915044c74bfceb5b12e02a

COCOAPODS: 1.15.2
COCOAPODS: 1.16.2
24 changes: 16 additions & 8 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,10 @@ packages:
dependency: transitive
description:
name: cli_util
sha256: c05b7406fdabc7a49a3929d4af76bcaccbbffcbcdcf185b082e1ae07da323d19
sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
url: "https://pub.dev"
source: hosted
version: "0.4.1"
version: "0.4.2"
clock:
dependency: transitive
description:
Expand All @@ -178,10 +178,10 @@ packages:
dependency: transitive
description:
name: code_builder
sha256: f692079e25e7869c14132d39f223f8eec9830eb76131925143b2129c4bb01b37
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
url: "https://pub.dev"
source: hosted
version: "4.10.0"
version: "4.10.1"
collection:
dependency: transitive
description:
Expand Down Expand Up @@ -596,6 +596,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
logger:
dependency: "direct main"
description:
name: logger
sha256: "697d067c60c20999686a0add96cf6aba723b3aa1f83ecf806a8097231529ec32"
url: "https://pub.dev"
source: hosted
version: "2.4.0"
logging:
dependency: transitive
description:
Expand Down Expand Up @@ -1004,10 +1012,10 @@ packages:
dependency: transitive
description:
name: url_launcher_android
sha256: "0dea215895a4d254401730ca0ba8204b29109a34a99fb06ae559a2b60988d2de"
sha256: "6fc2f56536ee873eeb867ad176ae15f304ccccc357848b351f6f0d8d4a40d193"
url: "https://pub.dev"
source: hosted
version: "6.3.13"
version: "6.3.14"
url_launcher_ios:
dependency: transitive
description:
Expand Down Expand Up @@ -1124,10 +1132,10 @@ packages:
dependency: transitive
description:
name: win32
sha256: e1d0cc62e65dc2561f5071fcbccecf58ff20c344f8f3dc7d4922df372a11df1f
sha256: "84ba388638ed7a8cb3445a320c8273136ab2631cd5f2c57888335504ddab1bc2"
url: "https://pub.dev"
source: hosted
version: "5.7.1"
version: "5.8.0"
win32_registry:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies:
http: ^1.2.1
url_launcher: ^6.2.6
custom_sliding_segmented_control: ^1.8.3
logger: ^2.4.0

dev_dependencies:
flutter_test:
Expand Down
20 changes: 17 additions & 3 deletions rust/src/api/compressor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ pub fn process_img(parameters: Parameters) -> Result<CompressResult, String> {
let out_path = get_out_path(&parameters, new_image_type);

let csparams = create_csparameters(&parameters, img.width(), img.height());
drop(img);

let should_convert = new_image_type != original_image_type;

let result = if should_convert {
convert_image(&parameters.path, &out_path, csparams)?
convert_image(&parameters.path, &out_path, csparams, new_image_type)?
} else {
compress_image(&parameters.path, &out_path, csparams)?
};
Expand Down Expand Up @@ -146,13 +147,26 @@ fn compress_image(path: &str, out_path: &str, mut params: CSParameters) -> Resul
}
}

fn convert_image(path: &str, out_path: &str, mut params: CSParameters) -> Result<String, String> {
fn convert_image(
path: &str,
out_path: &str,
mut params: CSParameters,
image_type: ImageType,
) -> Result<String, String> {
let supported_type = match image_type {
ImageType::JPEG => caesium::SupportedFileTypes::Jpeg,
ImageType::PNG => caesium::SupportedFileTypes::Png,
ImageType::WEBP => caesium::SupportedFileTypes::WebP,
ImageType::GIF => caesium::SupportedFileTypes::Gif,
ImageType::TIFF => caesium::SupportedFileTypes::Tiff,
};
let result = caesium::convert(
path.to_string(),
out_path.to_string(),
&mut params,
caesium::SupportedFileTypes::WebP,
supported_type,
);

match result {
Ok(_) => Ok("Success".to_string()),
Err(err) => Err(format!("Error: {}", err)),
Expand Down

0 comments on commit e17a283

Please sign in to comment.