Directly using VirtualBox from Java #5

Merged
NorbiPeti merged 60 commits from directvb into master 2019-04-18 23:29:21 +00:00
14 changed files with 779 additions and 466 deletions
Showing only changes of commit dfc86e8371 - Show all commits

63
.gitattributes vendored Normal file
View file

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

View file

@ -1,116 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.github.NorbiPeti</groupId> <groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId> <artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version> <version>2.0-SNAPSHOT</version>
<build> <build>
<sourceDirectory>src</sourceDirectory> <sourceDirectory>src</sourceDirectory>
<resources> <resources>
<resource> <resource>
<directory>src</directory> <directory>src</directory>
<excludes> <excludes>
<exclude>**/*.java</exclude> <exclude>**/*.java</exclude>
</excludes> </excludes>
</resource> </resource>
<resource> <resource>
<directory>.</directory> <directory>.</directory>
<includes> <includes>
<include>*.dll</include> <include>*.dll</include>
<include>*.yml</include> <include>*.yml</include>
</includes> </includes>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version> <version>3.5.1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version> <version>2.4.2</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<artifactSet> <artifactSet>
<includes> <includes>
<include>org.virtualbox:VirtualBox</include> <include>org.virtualbox:VirtualBox</include>
</includes> </includes>
</artifactSet> </artifactSet>
<pluginExecution> <pluginExecution>
<action> <action>
<execute /> <execute />
</action> </action>
</pluginExecution> </pluginExecution>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository> </repository>
<repository> <repository>
<id>repo</id> <id>repo</id>
<url>file://${basedir}/repo</url> <url>file://${basedir}/repo</url>
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId> <artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version> <version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
<exclusions> <exclusions>
<exclusion> <exclusion>
<artifactId>commons-lang</artifactId> <artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId> <groupId>commons-lang</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
<groupId>com.googlecode.json-simple</groupId> <groupId>com.googlecode.json-simple</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>snakeyaml</artifactId> <artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId> <groupId>org.yaml</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>bungeecord-chat</artifactId> <artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId> <groupId>net.md-5</groupId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId> <artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version> <version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.hynnet</groupId> <groupId>net.java.dev.jna</groupId>
<artifactId>jacob</artifactId> <artifactId>jna</artifactId>
<version>1.18</version> <version>4.4.0</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View file

@ -1,95 +1,96 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.github.NorbiPeti</groupId> <groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId> <artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version> <version>2.0-SNAPSHOT</version>
<build> <build>
<sourceDirectory>src</sourceDirectory> <sourceDirectory>src</sourceDirectory>
<resources> <resources>
<resource> <resource>
<directory>src</directory> <directory>src</directory>
<excludes> <excludes>
<exclude>**/*.java</exclude> <exclude>**/*.java</exclude>
</excludes> </excludes>
</resource> </resource>
<resource> <resource>
<directory>.</directory> <directory>.</directory>
<includes> <includes>
<include>*.dll</include> <include>*.dll</include>
<include>*.yml</include> <include>*.yml</include>
</includes> </includes>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version> <version>3.5.1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version> <version>2.4.2</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<artifactSet> <artifactSet>
<includes> <includes>
<include>org.virtualbox:VirtualBox</include> <include>org.virtualbox:VirtualBox</include>
</includes> </includes>
</artifactSet> </artifactSet>
<pluginExecution> <pluginExecution>
<action> <action>
<execute /> <execute />
</action> </action>
</pluginExecution> </pluginExecution>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository> </repository>
<repository> <repository>
<id>repo</id> <id>repo</id>
<url>file://${basedir}/repo</url> <url>file://${basedir}/repo</url>
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId> <artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version> <version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.virtualbox</groupId> <groupId>org.virtualbox</groupId>
<artifactId>VirtualBox</artifactId> <artifactId>VirtualBox</artifactId>
<version>5.1</version> <version>5.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId> <artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version> <version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.hynnet/jacob --> <!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency> <dependency>
<groupId>com.hynnet</groupId> <groupId>net.java.dev.jna</groupId>
<artifactId>jacob</artifactId> <artifactId>jna</artifactId>
<version>1.18</version> <version>4.4.0</version>
</dependency> </dependency>
</dependencies>
</dependencies>
</project> </project>

View file

@ -2,6 +2,7 @@ package sznp.virtualcomputer;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt; import java.awt.image.DataBufferInt;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.bukkit.World; import org.bukkit.World;
@ -11,11 +12,11 @@ import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView; import org.bukkit.map.MapView;
public class BukkitRenderer extends MapRenderer implements IRenderer { public class BukkitRenderer extends MapRenderer implements IRenderer {
private byte[] allpixels; private ByteBuffer allpixels;
private BufferedImage image; private BufferedImage image;
private int startindex; private int startindex;
public void setAllPixels(byte[] allpixels) { public void setAllPixels(ByteBuffer allpixels) {
this.allpixels = allpixels; this.allpixels = allpixels;
} }
@ -53,9 +54,9 @@ public class BukkitRenderer extends MapRenderer implements IRenderer {
for (int i = startindex, j = 0; i < startindex + 128 * 128; i = i + 4, j++) { for (int i = startindex, j = 0; i < startindex + 128 * 128; i = i + 4, j++) {
int b, g, r; int b, g, r;
b = allpixels[i] & 0xFF; b = allpixels.get(i) & 0xFF;
g = allpixels[i + 1] & 0xFF; g = allpixels.get(i + 1) & 0xFF;
r = allpixels[i + 2] & 0xFF; r = allpixels.get(i + 2) & 0xFF;
a[j] = (r << 16) | (g << 8) | b; a[j] = (r << 16) | (g << 8) | b;
} }

View file

@ -2,6 +2,7 @@ package sznp.virtualcomputer;
import java.awt.Color; import java.awt.Color;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Map; import java.util.Map;
import org.bukkit.World; import org.bukkit.World;
@ -50,11 +51,12 @@ public class DirectRenderer implements IRenderer {
private Exception ex; private Exception ex;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void render(byte[] allpixels, long x, long y, long width, long height) { // TODO public void render(ByteBuffer allpixels, long x, long y, long width, long height) { // TODO
try { try {
for (int i = startindex, j = 0; i < startindex + 128 * 128 && i < allpixels.length for (int i = startindex, j = 0; i < startindex + 128 * 128 && i < allpixels.limit()
&& j < buffer.length; i += 4, j++) && j < buffer.length; i += 4, j++)
buffer[j] = MapPalette.matchColor(new Color(allpixels[i], allpixels[i + 1], allpixels[i + 2])); buffer[j] = MapPalette
.matchColor(new Color(allpixels.get(i), allpixels.get(i + 1), allpixels.get(i + 2)));
final Field field = map.getClass().getField("worldmap"); final Field field = map.getClass().getField("worldmap");
field.setAccessible(true); field.setAccessible(true);
WorldMap wmap = (WorldMap) field.get(map); WorldMap wmap = (WorldMap) field.get(map);

View file

@ -78,8 +78,10 @@ public class MCFrameBuffer implements IFramebuffer {
public void notifyChange(long screenId, long xOrigin, long yOrigin, long width, long height) { public void notifyChange(long screenId, long xOrigin, long yOrigin, long width, long height) {
Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.Instance, () -> { Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.Instance, () -> {
display.querySourceBitmap(0L, holder); // TODO: Test if it crashes here display.querySourceBitmap(0L, holder); // TODO: Test if it crashes here
holder.value.getTypedWrapped().queryBitmapInfo(PluginMain.allpixels, new long[] { width }, byte[] arr = new byte[10];
new long[] { height }, new long[] { getBitsPerPixel() }, new long[] { getBytesPerLine() }, System.out.println("Arr0:" + arr[0]);
holder.value.getTypedWrapped().queryBitmapInfo(arr, new long[] { width }, new long[] { height },
new long[] { getBitsPerPixel() }, new long[] { getBytesPerLine() },
new long[] { getPixelFormat() }); // These are out params but whatever new long[] { getPixelFormat() }); // These are out params but whatever
for (IRenderer r : PluginMain.renderers) for (IRenderer r : PluginMain.renderers)
if (r instanceof BukkitRenderer) if (r instanceof BukkitRenderer)

View file

@ -1,246 +1,256 @@
package sznp.virtualcomputer; package sznp.virtualcomputer;
import java.lang.reflect.Field; import java.io.File;
import java.util.ArrayList; import java.lang.reflect.Field;
import java.util.Arrays; import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.bukkit.Bukkit; import java.util.Arrays;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.command.ConsoleCommandSender;
import org.virtualbox_5_1.*; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import com.google.common.collect.Lists; import org.virtualbox_5_1.*;
public class PluginMain extends JavaPlugin { import com.google.common.collect.Lists;
private IVirtualBox vbox;
private ISession session; public class PluginMain extends JavaPlugin {
private IMachine machine; private IVirtualBox vbox;
private BukkitTask screenupdatetask; private ISession session;
private BukkitTask mousetask; private IMachine machine;
private BukkitTask screenupdatetask;
public static PluginMain Instance; private BukkitTask mousetask;
public static byte[] allpixels = null; // It's set on each change
public static ArrayList<IRenderer> renderers = new ArrayList<>(); public static PluginMain Instance;
public static ByteBuffer allpixels = null; // It's set on each change
// Fired when plugin is first enabled public static ArrayList<IRenderer> renderers = new ArrayList<>();
@Override
public void onEnable() { // Fired when plugin is first enabled
Instance = this; @Override
try { public void onEnable() {
ConsoleCommandSender ccs = getServer().getConsoleSender(); Instance = this;
this.getCommand("computer").setExecutor(new Commands()); try {
ccs.sendMessage("§bInitializing VirtualBox..."); ConsoleCommandSender ccs = getServer().getConsoleSender();
final String vbpath = System.getProperty("os.name").toLowerCase().contains("mac") this.getCommand("computer").setExecutor(new Commands());
? "/Applications/VirtualBox.app/Contents/MacOS" : "/opt/virtualbox"; ccs.sendMessage("§bInitializing VirtualBox...");
if (System.getProperty("vbox.home") == null || System.getProperty("vbox.home").isEmpty()) String vbpath = System.getProperty("os.name").toLowerCase().contains("mac")
System.setProperty("vbox.home", vbpath); ? "/Applications/VirtualBox.app/Contents/MacOS" : "/opt/virtualbox";
if (System.getProperty("sun.boot.library.path") == null File f = new File(vbpath);
|| System.getProperty("sun.boot.library.path").isEmpty()) if (!f.isDirectory() || !Arrays.stream(f.list()).anyMatch(s -> s.contains("xpcom")))
System.setProperty("sun.boot.library.path", vbpath); vbpath = "/usr/lib/virtualbox";
addLibraryPath(vbpath); if (System.getProperty("vbox.home") == null || System.getProperty("vbox.home").isEmpty())
final VirtualBoxManager manager = VirtualBoxManager.createInstance(getDataFolder().getAbsolutePath()); System.setProperty("vbox.home", vbpath);
vbox = manager.getVBox(); if (System.getProperty("sun.boot.library.path") == null
session = manager.getSessionObject(); // TODO: Events || System.getProperty("sun.boot.library.path").isEmpty())
ccs.sendMessage("§bLoading Screen..."); System.setProperty("sun.boot.library.path", vbpath);
try { if (System.getProperty("java.library.path") == null || System.getProperty("java.library.path").isEmpty())
for (short i = 0; i < 20; i++) System.setProperty("java.library.path", vbpath);
renderers.add(new DirectRenderer(i, Bukkit.getWorlds().get(0), i * 128 * 128 * 4)); // TODO: The pixels are selected in a horribly wrong way probably addLibraryPath(vbpath);
ccs.sendMessage("§bUsing Direct Renderer, all good"); final VirtualBoxManager manager = VirtualBoxManager.createInstance(getDataFolder().getAbsolutePath());
} catch (NoClassDefFoundError e) { vbox = manager.getVBox();
for (short i = 0; i < 20; i++) session = manager.getSessionObject(); // TODO: Events
renderers.add(new BukkitRenderer(i, Bukkit.getWorlds().get(0), i * 128 * 128 * 4)); ccs.sendMessage("§bLoading Screen...");
ccs.sendMessage("§6Compability error, using slower renderer"); try {
} for (short i = 0; i < 20; i++)
ccs.sendMessage("§bLoaded!"); renderers.add(new DirectRenderer(i, Bukkit.getWorlds().get(0), i * 128 * 128 * 4)); // TODO: The pixels are selected in a horribly wrong way probably
mousetask = getServer().getScheduler().runTaskTimer(this, new MouseLockerPlayerListener(), 0, 0); ccs.sendMessage("§bUsing Direct Renderer, all good");
} catch (final Exception e) { } catch (NoClassDefFoundError e) {
e.printStackTrace(); for (short i = 0; i < 20; i++)
} renderers.add(new BukkitRenderer(i, Bukkit.getWorlds().get(0), i * 128 * 128 * 4));
} ccs.sendMessage("§6Compability error, using slower renderer");
}
// Fired when plugin is disabled ccs.sendMessage("§bLoaded!");
@Override mousetask = getServer().getScheduler().runTaskTimer(this, new MouseLockerPlayerListener(), 0, 0);
public void onDisable() {
ConsoleCommandSender ccs = getServer().getConsoleSender(); } catch (final Exception e) {
mousetask.cancel(); e.printStackTrace();
if (session.getState() == SessionState.Locked) { }
if (session.getMachine().getState().equals(MachineState.Running)) { }
ccs.sendMessage("§aSaving machine state...");
session.getMachine().saveState().waitForCompletion(10000); // Fired when plugin is disabled
} @Override
session.unlockMachine(); public void onDisable() {
} ConsoleCommandSender ccs = getServer().getConsoleSender();
ccs.sendMessage("§aHuh."); mousetask.cancel();
saveConfig(); if (session.getState() == SessionState.Locked) {
} if (session.getMachine().getState().equals(MachineState.Running)) {
ccs.sendMessage("§aSaving machine state...");
public void Start(CommandSender sender) {// TODO: Add touchscreen support (#2) session.getMachine().saveState().waitForCompletion(10000);
Bukkit.getScheduler().runTaskAsynchronously(this, () -> { }
sender.sendMessage("§eStarting computer..."); session.unlockMachine();
if (machine == null) }
machine = vbox.getMachines().get(0); ccs.sendMessage("§aHuh.");
session.setName("minecraft"); saveConfig();
// machine.launchVMProcess(session, "headless", "").waitForCompletion(10000); - This creates a *process*, we don't want that anymore }
machine.lockMachine(session, LockType.VM); // We want the machine inside *our* process <-- Need the VM type to have console access
sender.sendMessage("A: " + machine.getState().toString()); public void Start(CommandSender sender) {// TODO: Add touchscreen support (#2)
screenupdatetask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
if (session.getState() != SessionState.Locked) // https://www.virtualbox.org/sdkref/_virtual_box_8idl.html#ac82c179a797c0d7c249d1b98a8e3aa8f sender.sendMessage("§eStarting computer...");
return; // "This state also occurs as a short transient state during an IMachine::lockMachine call." if (machine == null)
else { machine = vbox.getMachines().get(0);
screenupdatetask.cancel(); session.setName("minecraft");
screenupdatetask = null; // machine.launchVMProcess(session, "headless", "").waitForCompletion(10000); - This creates a *process*, we don't want that anymore
} machine.lockMachine(session, LockType.VM); // We want the machine inside *our* process <-- Need the VM type to have console access
machine = session.getMachine(); // This is the Machine object we can work with sender.sendMessage("A: " + machine.getState().toString());
sender.sendMessage("B: " + machine.getState().toString()); final Runnable tr = new Runnable() {
final IConsole console = session.getConsole(); public void run() {
sender.sendMessage("1: " + console.getState().toString()); if (session.getState() != SessionState.Locked) { // https://www.virtualbox.org/sdkref/_virtual_box_8idl.html#ac82c179a797c0d7c249d1b98a8e3aa8f
console.powerUp().waitForCompletion(10000); Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.this, this, 5);
sender.sendMessage("2: " + console.getState().toString()); return; // "This state also occurs as a short transient state during an IMachine::lockMachine call."
console.getDisplay().attachFramebuffer(0L, new IFramebuffer(new MCFrameBuffer(console.getDisplay()))); }
sender.sendMessage("3: " + console.getState().toString()); machine = session.getMachine(); // This is the Machine object we can work with
if (screenupdatetask == null) sender.sendMessage("B: " + machine.getState().toString());
screenupdatetask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { final IConsole console = session.getConsole();
sender.sendMessage("4: " + console.getState().toString()); sender.sendMessage("1: " + console.getState().toString());
if (session.getState().equals(SessionState.Locked) // Don't run until the machine is running console.powerUp().waitForCompletion(10000);
&& console.getState().equals(MachineState.Running)) sender.sendMessage("2: " + console.getState().toString());
console.getDisplay().invalidateAndUpdateScreen(0L); console.getDisplay().attachFramebuffer(0L,
if (session.getState().equals(SessionState.Unlocked) // Stop if the machine stopped fully new IFramebuffer(new MCFrameBuffer(console.getDisplay())));
|| console.getState().equals(MachineState.PoweredOff)) { sender.sendMessage("3: " + console.getState().toString());
sender.sendMessage("5: " + console.getState().toString()); if (screenupdatetask == null)
if (session.getState().equals(SessionState.Locked)) { screenupdatetask = Bukkit.getScheduler().runTaskTimerAsynchronously(PluginMain.this, () -> {
session.unlockMachine(); sender.sendMessage("4: " + console.getState().toString());
sender.sendMessage("Computer powered off, released it."); if (session.getState().equals(SessionState.Locked) // Don't run until the machine is running
} && console.getState().equals(MachineState.Running))
screenupdatetask.cancel(); console.getDisplay().invalidateAndUpdateScreen(0L);
screenupdatetask = null; if (session.getState().equals(SessionState.Unlocked) // Stop if the machine stopped fully
} || console.getState().equals(MachineState.PoweredOff)) {
}, 100, 100); // Do a full update every 5 seconds sender.sendMessage("5: " + console.getState().toString());
sender.sendMessage("§eComputer started."); if (session.getState().equals(SessionState.Locked)) {
}, 5, 5); session.unlockMachine();
}); sender.sendMessage("Computer powered off, released it.");
} }
screenupdatetask.cancel();
public static int MouseSpeed = 1; screenupdatetask = null;
}
public void Stop(CommandSender sender) { }, 100, 100); // Do a full update every 5 seconds
if (!checkMachineRunning(sender)) sender.sendMessage("§eComputer started.");
return; }
sender.sendMessage("§eStopping computer..."); };
session.getConsole().powerDown().waitForCompletion(2000); Bukkit.getScheduler().runTaskLaterAsynchronously(this, tr, 5);
session.unlockMachine(); });
sender.sendMessage("§eComputer stopped."); }
}
public static int MouseSpeed = 1;
public void PowerButton(CommandSender sender) {
sender.sendMessage("§ePressing powerbutton..."); public void Stop(CommandSender sender) {
final CommandSender s = sender; if (!checkMachineRunning(sender))
getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { return;
@Override sender.sendMessage("§eStopping computer...");
public void run() { session.getConsole().powerDown().waitForCompletion(2000);
if (session.getState() != SessionState.Locked || session.getMachine() == null) { session.unlockMachine();
Start(sender); sender.sendMessage("§eComputer stopped.");
} else { }
session.getConsole().powerButton();
s.sendMessage("§ePowerbutton pressed."); public void PowerButton(CommandSender sender) {
} sender.sendMessage("§ePressing powerbutton...");
} final CommandSender s = sender;
}); getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {
} @Override
public void run() {
public void Reset(CommandSender sender) { if (session.getState() != SessionState.Locked || session.getMachine() == null) {
if (!checkMachineRunning(sender)) Start(sender);
return; } else {
sender.sendMessage("§eResetting computer..."); session.getConsole().powerButton();
session.getConsole().reset(); s.sendMessage("§ePowerbutton pressed.");
sender.sendMessage("§eComputer reset."); }
} }
});
public void FixScreen(CommandSender sender) { }
if (!checkMachineRunning(sender))
return; public void Reset(CommandSender sender) {
sender.sendMessage("§eFixing screen..."); if (!checkMachineRunning(sender))
session.getConsole().getDisplay().setSeamlessMode(false); return;
session.getConsole().getDisplay().setVideoModeHint(0L, true, false, 0, 0, 640L, 480L, 32L); sender.sendMessage("§eResetting computer...");
sender.sendMessage("§eScreen fixed."); session.getConsole().reset();
} sender.sendMessage("§eComputer reset.");
}
private boolean checkMachineRunning(CommandSender sender) {
if (session.getState() != SessionState.Locked || machine.getState() != MachineState.Running) { public void FixScreen(CommandSender sender) {
sender.sendMessage("§cMachine isn't running."); if (!checkMachineRunning(sender))
return false; return;
} sender.sendMessage("§eFixing screen...");
return true; session.getConsole().getDisplay().setSeamlessMode(false);
} session.getConsole().getDisplay().setVideoModeHint(0L, true, false, 0, 0, 640L, 480L, 32L);
sender.sendMessage("§eScreen fixed.");
public void PressKey(CommandSender sender, String key, String stateorduration) { }
if (!checkMachineRunning(sender))
return; private boolean checkMachineRunning(CommandSender sender) {
int durationorstate; if (session.getState() != SessionState.Locked || machine.getState() != MachineState.Running) {
if (stateorduration.length() == 0) sender.sendMessage("§cMachine isn't running.");
durationorstate = 0; return false;
else if (stateorduration.equalsIgnoreCase("down")) }
durationorstate = -1; return true;
else if (stateorduration.equalsIgnoreCase("up")) }
durationorstate = -2;
else public void PressKey(CommandSender sender, String key, String stateorduration) {
durationorstate = Short.parseShort(stateorduration); if (!checkMachineRunning(sender))
int code = 0; return;
// Release key scan code concept taken from VirtualBox source code (KeyboardImpl.cpp:putCAD()) int durationorstate;
// +128 if (stateorduration.length() == 0)
if (durationorstate != 2) durationorstate = 0;
session.getConsole().getKeyboard().putScancode(code); else if (stateorduration.equalsIgnoreCase("down"))
Runnable sendrelease = () -> session.getConsole().getKeyboard().putScancodes(Lists.newArrayList(code + 128, durationorstate = -1;
Scancode.sc_controlLeft.Code + 128, Scancode.sc_shiftLeft.Code + 128, Scancode.sc_altLeft.Code + 128)); else if (stateorduration.equalsIgnoreCase("up"))
if (durationorstate == 0 || durationorstate == -2) durationorstate = -2;
sendrelease.run(); else
if (durationorstate > 0) { durationorstate = Short.parseShort(stateorduration);
Bukkit.getScheduler().runTaskLaterAsynchronously(this, sendrelease, durationorstate); int code = 0;
} // Release key scan code concept taken from VirtualBox source code (KeyboardImpl.cpp:putCAD())
} // +128
if (durationorstate != 2)
public void UpdateMouse(CommandSender sender, int x, int y, int z, int w, String mbs, boolean down) { session.getConsole().getKeyboard().putScancode(code);
if (!checkMachineRunning(sender)) Runnable sendrelease = () -> session.getConsole().getKeyboard().putScancodes(Lists.newArrayList(code + 128,
return; Scancode.sc_controlLeft.Code + 128, Scancode.sc_shiftLeft.Code + 128, Scancode.sc_altLeft.Code + 128));
int state = 0; if (durationorstate == 0 || durationorstate == -2)
if (mbs.length() > 0 && down) sendrelease.run();
state = Arrays.stream(MouseButtonState.values()).filter(mousebs -> mousebs.name().equalsIgnoreCase(mbs)) if (durationorstate > 0) {
.findAny().orElseThrow(() -> new RuntimeException("Unknown mouse button")).value(); Bukkit.getScheduler().runTaskLaterAsynchronously(this, sendrelease, durationorstate);
session.getConsole().getMouse().putMouseEvent(x, y, z, w, state); }
} }
public void UpdateMouse(CommandSender sender, int x, int y, int z, int w, String mbs) { public void UpdateMouse(CommandSender sender, int x, int y, int z, int w, String mbs, boolean down) {
if (!checkMachineRunning(sender)) if (!checkMachineRunning(sender))
return; return;
UpdateMouse(sender, x, y, z, w, mbs, true); int state = 0;
UpdateMouse(sender, x, y, z, w, mbs, false); if (mbs.length() > 0 && down)
} state = Arrays.stream(MouseButtonState.values()).filter(mousebs -> mousebs.name().equalsIgnoreCase(mbs))
.findAny().orElseThrow(() -> new RuntimeException("Unknown mouse button")).value();
/** session.getConsole().getMouse().putMouseEvent(x, y, z, w, state);
* Adds the specified path to the java library path }
*
* @param pathToAdd public void UpdateMouse(CommandSender sender, int x, int y, int z, int w, String mbs) {
* the path to add if (!checkMachineRunning(sender))
* @throws Exception return;
*/ UpdateMouse(sender, x, y, z, w, mbs, true);
public static void addLibraryPath(String pathToAdd) throws Exception { UpdateMouse(sender, x, y, z, w, mbs, false);
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); }
usrPathsField.setAccessible(true);
/**
// get array of paths * Adds the specified path to the java library path
final String[] paths = (String[]) usrPathsField.get(null); *
* @param pathToAdd
// check if the path to add is already present * the path to add
for (String path : paths) { * @throws Exception
if (path.equals(pathToAdd)) { */
return; public static void addLibraryPath(String pathToAdd) throws Exception {
} final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
} usrPathsField.setAccessible(true);
// add the new path // get array of paths
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1); final String[] paths = (String[]) usrPathsField.get(null);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths); // check if the path to add is already present
} for (String path : paths) {
} if (path.equals(pathToAdd)) {
return;
}
}
// add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
}

View file

@ -0,0 +1,10 @@
package sznp.virtualcomputer;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface WinLib extends Library {
WinLib INSTANCE = Native.loadLibrary("VirtualComputerWin", WinLib.class);
public void init();
}

View file

@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualComputerWindows", "VirtualComputerWindows\VirtualComputerWindows.csproj", "{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|x64.ActiveCfg = Debug|x64
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|x64.Build.0 = Debug|x64
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|x86.ActiveCfg = Debug|x86
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Debug|x86.Build.0 = Debug|x86
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|Any CPU.Build.0 = Release|Any CPU
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|x64.ActiveCfg = Release|x64
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|x64.Build.0 = Release|x64
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|x86.ActiveCfg = Release|x86
{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VirtualBox;
namespace VirtualComputerWindows
{
public static class Exports
{
[DllExport]
public static VirtualBoxClass Init()
{
var vbox = new VirtualBoxClass();
return vbox;
var machine = vbox.Machines.GetValue(0) as IMachine;
}
}
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VirtualComputerWindows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VirtualComputerWindows")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5e734f17-ff74-4187-a6e4-b7e1dab272f8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5E734F17-FF74-4187-A6E4-B7E1DAB272F8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VirtualComputerWindows</RootNamespace>
<AssemblyName>VirtualComputerWindows</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<DllExportNamespace>VirtualComputerWindows</DllExportNamespace>
<DllExportDDNSCecil>true</DllExportDDNSCecil>
<DllExportSkipOnAnyCpu>false</DllExportSkipOnAnyCpu>
<DllExportOrdinalsBase>1</DllExportOrdinalsBase>
<DllExportGenExpLib>false</DllExportGenExpLib>
<DllExportOurILAsm>false</DllExportOurILAsm>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="DllExport, Version=1.5.2.30304, Culture=neutral, PublicKeyToken=8337224c9ad9e356, processorArchitecture=MSIL">
<HintPath>..\packages\DllExport.1.5.2\lib\net20\DllExport.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Exports.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<COMReference Include="VirtualBox">
<Guid>{D7569351-1750-46F0-936E-BD127D5BC264}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>3</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="../packages/DllExport.1.5.2/tools/net.r_eg.DllExport.targets" Condition="Exists('../packages/DllExport.1.5.2/tools/net.r_eg.DllExport.targets')" />
</Project>

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DllExport" version="1.5.2" targetFramework="net462" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net462" />
</packages>