Skip to content

Commit

Permalink
singe instance when opening file with exe
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurHeitmann committed Oct 26, 2024
1 parent 507d170 commit ab39f5f
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 10 deletions.
19 changes: 16 additions & 3 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Expand All @@ -11,10 +12,12 @@ import 'background/IdLookup.dart';
import 'background/wemFilesIndexer.dart';
import 'keyboardEvents/globalShortcutsWrapper.dart';
import 'stateManagement/beforeExitCleanup.dart';
import 'stateManagement/hierarchy/FileHierarchy.dart';
import 'stateManagement/openFiles/openFilesManager.dart';
import 'stateManagement/openFiles/types/xml/sync/syncServer.dart';
import 'stateManagement/preferencesData.dart';
import 'utils/assetDirFinder.dart';
import 'utils/fileOpenCommand.dart';
import 'utils/loggingWrapper.dart';
import 'utils/utils.dart';
import 'widgets/EditorLayout.dart';
Expand All @@ -31,6 +34,13 @@ void main(List<String> args) {
}

void init(List<String> args) async {
if (args.isNotEmpty) {
var paths = args.where((arg) => FileSystemEntity.typeSync(arg) != FileSystemEntityType.notFound).toList();
if (await trySendFileArgs(paths)) {
exit(0);
}
}

WidgetsFlutterBinding.ensureInitialized();

runApp(const SplashScreen());
Expand Down Expand Up @@ -88,9 +98,12 @@ void init(List<String> args) async {

runApp(const MyApp());

unawaited(waitForNextFrame().then((_) {
for (var arg in args)
areasManager.openFile(arg);
unawaited(waitForNextFrame().then((_) async {
for (var arg in args) {
await openHierarchyManager.openFile(arg);
if (await canOpenAsFile(arg))
areasManager.openFile(arg);
}
}));
}

Expand Down
56 changes: 49 additions & 7 deletions lib/stateManagement/openFiles/types/xml/sync/syncServer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@ import 'dart:io';

import 'package:flutter/material.dart';

import '../../../../../utils/fileOpenCommand.dart';
import '../../../../events/statusInfo.dart';

const _wsPort = 1547;
const wsPort = 1547;

WebSocket? _activeSocket;
ValueNotifier<bool> canSync = ValueNotifier<bool>(false);
DateTime? serverStartTime;

var _wsMessageStream = StreamController<SyncMessage>.broadcast();
var wsMessageStream = _wsMessageStream.stream;

class SyncMessage {
abstract class WsMessage {
Map toJson();
}
class SyncMessage extends WsMessage {
final String method;
final String uuid;
final Map args;
Expand All @@ -27,6 +32,7 @@ class SyncMessage {
uuid = json["uuid"],
args = json["args"];

@override
Map toJson() {
return {
"method": method,
Expand All @@ -35,6 +41,27 @@ class SyncMessage {
};
}
}
class CustomWsMessage extends WsMessage {
final String method;
final Map json;

CustomWsMessage(this.method, this.json);

CustomWsMessage.fromJson(Map<String, dynamic> json)
: method = json["method"],
json = {
for (var key in json.keys)
if (key != "method") key: json[key]
};

@override
Map toJson() {
return {
"method": method,
...json,
};
}
}

void _handleWebSocket(WebSocket client) {
print("New WebSocket client connected");
Expand All @@ -49,26 +76,41 @@ void _handleWebSocket(WebSocket client) {
_onClientDone();
});
wsSend(SyncMessage("connected", "", {}));
messageLog.add("Connected to Blender");
if (_startupCompleted())
messageLog.add("Connected");
}

void _onClientData(data) {
var message = SyncMessage.fromJson(jsonDecode(data));
var jsonData = jsonDecode(data);
var method = jsonData["method"];
if (method == "openFiles") {
var msg = CustomWsMessage.fromJson(jsonData);
var files = (msg.json["files"] as List).cast<String>();
onFileOpenCommand(files);
return;
}
var message = SyncMessage.fromJson(jsonData);
_wsMessageStream.add(message);
}

void _onClientDone() {
print("WebSocket client disconnected");
_activeSocket = null;
canSync.value = false;
messageLog.add("Disconnected from Blender");
if (_startupCompleted())
messageLog.add("Disconnected");
}

void wsSend(SyncMessage data) {
void wsSend(WsMessage data) {
_activeSocket?.add(jsonEncode(data.toJson()));
}

bool _startupCompleted() {
return DateTime.now().difference(serverStartTime ?? DateTime.now()).inSeconds > 5;
}

void startSyncServer() async {
final server = await HttpServer.bind("localhost", _wsPort);
final server = await HttpServer.bind("localhost", wsPort);
server.transform(WebSocketTransformer()).listen(_handleWebSocket);
serverStartTime = DateTime.now();
}
56 changes: 56 additions & 0 deletions lib/utils/fileOpenCommand.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:window_manager/window_manager.dart';

import '../stateManagement/events/statusInfo.dart';
import '../stateManagement/hierarchy/FileHierarchy.dart';
import '../stateManagement/openFiles/openFilesManager.dart';
import '../stateManagement/openFiles/types/xml/sync/syncServer.dart';
import 'utils.dart';

void onFileOpenCommand(List<String> paths) async {
await Future.wait(paths.map((path) async {
await openHierarchyManager.openFile(path);
if (await canOpenAsFile(path))
areasManager.openFile(path);
}));
await windowManager.focus();
messageLog.add("");
}

Future<bool> trySendFileArgs(List<String> args) async {
if (args.isEmpty)
return false;
var completer = Completer<bool>();
WebSocket? webSocket;
var timeout = Timer(const Duration(milliseconds: 500), () {
completer.complete(false);
webSocket?.close();
});
unawaited(WebSocket.connect("ws://localhost:$wsPort")
.then((ws) {
if (completer.isCompleted) {
ws.close();
return;
}
webSocket = ws;
ws.add(jsonEncode(CustomWsMessage("openFiles", {"files": args})));
ws.listen((data) {
var msg = SyncMessage.fromJson(jsonDecode(data));
if (msg.method == "connected") {
completer.complete(true);
ws.close();
timeout.cancel();
}
});
})
.catchError((e) {
completer.complete(false);
})
);

return completer.future;
}
9 changes: 9 additions & 0 deletions lib/utils/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -861,3 +861,12 @@ void debugOnly(void Function() func) {
return true;
}());
}

const sideBarOnlyExtensions = [...datExtensions, ".pak", ".wai", ".bnk", ".wsp"];

Future<bool> canOpenAsFile(String path) async {
var ext = extension(path);
if (sideBarOnlyExtensions.contains(ext))
return false;
return await File(path).exists();
}

0 comments on commit ab39f5f

Please sign in to comment.