Fixed double start, and some older changes

Fiiinally got VBox working inside a VM spending a day on it. I was/am
tired. Now I have it set up and it's really easy to debug.

No errors, at first start anyways, but the machine only goes Starting
for a very short amount of time then it's off again.
This commit is contained in:
Norbi Peti 2017-10-15 03:55:16 +02:00
parent f031fc0b9a
commit dfc86e8371
14 changed files with 779 additions and 466 deletions

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"?>
<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>
<groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>.</directory>
<includes>
<include>*.dll</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.virtualbox:VirtualBox</include>
</includes>
</artifactSet>
<pluginExecution>
<action>
<execute />
</action>
</pluginExecution>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>repo</id>
<url>file://${basedir}/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>json-simple</artifactId>
<groupId>com.googlecode.json-simple</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>.</directory>
<includes>
<include>*.dll</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.virtualbox:VirtualBox</include>
</includes>
</artifactSet>
<pluginExecution>
<action>
<execute />
</action>
</pluginExecution>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>repo</id>
<url>file://${basedir}/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>json-simple</artifactId>
<groupId>com.googlecode.json-simple</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.4.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
</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"
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>
<groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>.</directory>
<includes>
<include>*.dll</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.virtualbox:VirtualBox</include>
</includes>
</artifactSet>
<pluginExecution>
<action>
<execute />
</action>
</pluginExecution>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>repo</id>
<url>file://${basedir}/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.virtualbox</groupId>
<artifactId>VirtualBox</artifactId>
<version>5.1</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hynnet/jacob -->
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.NorbiPeti</groupId>
<artifactId>VirtualComputer</artifactId>
<version>2.0-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>.</directory>
<includes>
<include>*.dll</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.virtualbox:VirtualBox</include>
</includes>
</artifactSet>
<pluginExecution>
<action>
<execute />
</action>
</pluginExecution>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>repo</id>
<url>file://${basedir}/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.virtualbox</groupId>
<artifactId>VirtualBox</artifactId>
<version>5.1</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.4.0</version>
</dependency>
</dependencies>
</project>

View file

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

View file

@ -2,6 +2,7 @@ package sznp.virtualcomputer;
import java.awt.Color;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Map;
import org.bukkit.World;
@ -50,11 +51,12 @@ public class DirectRenderer implements IRenderer {
private Exception ex;
@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 {
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++)
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");
field.setAccessible(true);
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) {
Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.Instance, () -> {
display.querySourceBitmap(0L, holder); // TODO: Test if it crashes here
holder.value.getTypedWrapped().queryBitmapInfo(PluginMain.allpixels, new long[] { width },
new long[] { height }, new long[] { getBitsPerPixel() }, new long[] { getBytesPerLine() },
byte[] arr = new byte[10];
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
for (IRenderer r : PluginMain.renderers)
if (r instanceof BukkitRenderer)

View file

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