Compare commits

..
72 changed files with 1145 additions and 2548 deletions

No files matched your search

+1 -11
View File
@@ -849,7 +849,7 @@ jobs:
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- name: Install Python test dependencies
timeout-minutes: 7
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers spirv-tools
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
- name: Resolve the pinned Android NDK
run: bash tools/ci/resolve-ndk.sh
@@ -879,16 +879,6 @@ jobs:
-ldl -o /tmp/test-presenter-shutdown
timeout 10 /tmp/test-presenter-shutdown
- name: Fetch the Mali compatibility layer's headers
run: |
set -euo pipefail
sdk=$(sed -n 's/^SDK=//p' tools/venus/ci-build.sh)
bcdec=$(grep -o 'https://raw.githubusercontent.com/iOrange/bcdec/[^ ]*' tools/venus/ci-build.sh)
mkdir -p build/layer-deps/bcdec
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/Vulkan-Headers.git build/layer-deps/vulkan
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/SPIRV-Headers.git build/layer-deps/spirv
curl -sSfL -o build/layer-deps/bcdec/bcdec.h "$bcdec"
- name: Steam import and game environment tests
run: bash tools/ci/run-python-tests.sh
-106
View File
@@ -1,106 +0,0 @@
#pragma once
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>
struct VkTable {
PFN_vkCreateInstance CreateInstance;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
PFN_vkCreateDevice CreateDevice;
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
PFN_vkDestroyDevice DestroyDevice;
PFN_vkGetDeviceQueue GetDeviceQueue;
PFN_vkDeviceWaitIdle DeviceWaitIdle;
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
PFN_vkQueuePresentKHR QueuePresentKHR;
PFN_vkQueueSubmit QueueSubmit;
PFN_vkCreateQueryPool CreateQueryPool;
PFN_vkDestroyQueryPool DestroyQueryPool;
PFN_vkCmdResetQueryPool CmdResetQueryPool;
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
PFN_vkGetQueryPoolResults GetQueryPoolResults;
PFN_vkCreateRenderPass CreateRenderPass;
PFN_vkDestroyRenderPass DestroyRenderPass;
PFN_vkCreateFramebuffer CreateFramebuffer;
PFN_vkDestroyFramebuffer DestroyFramebuffer;
PFN_vkCreateImageView CreateImageView;
PFN_vkDestroyImageView DestroyImageView;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkFreeMemory FreeMemory;
PFN_vkMapMemory MapMemory;
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkBindImageMemory BindImageMemory;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
PFN_vkCreateDescriptorPool CreateDescriptorPool;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
PFN_vkFreeDescriptorSets FreeDescriptorSets;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
PFN_vkCreatePipelineLayout CreatePipelineLayout;
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
PFN_vkCreateShaderModule CreateShaderModule;
PFN_vkDestroyShaderModule DestroyShaderModule;
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
PFN_vkDestroyPipeline DestroyPipeline;
PFN_vkCreateCommandPool CreateCommandPool;
PFN_vkDestroyCommandPool DestroyCommandPool;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
PFN_vkFreeCommandBuffers FreeCommandBuffers;
PFN_vkBeginCommandBuffer BeginCommandBuffer;
PFN_vkEndCommandBuffer EndCommandBuffer;
PFN_vkResetCommandBuffer ResetCommandBuffer;
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
PFN_vkCmdEndRenderPass CmdEndRenderPass;
PFN_vkCmdBindPipeline CmdBindPipeline;
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
PFN_vkCmdDraw CmdDraw;
PFN_vkCmdPushConstants CmdPushConstants;
PFN_vkCmdSetViewport CmdSetViewport;
PFN_vkCmdSetScissor CmdSetScissor;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
PFN_vkCmdCopyImage CmdCopyImage;
PFN_vkCmdBlitImage CmdBlitImage;
PFN_vkCmdDispatch CmdDispatch;
PFN_vkCreateComputePipelines CreateComputePipelines;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkResetDescriptorPool ResetDescriptorPool;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCreateSampler CreateSampler;
PFN_vkDestroySampler DestroySampler;
PFN_vkCreateSemaphore CreateSemaphore;
PFN_vkDestroySemaphore DestroySemaphore;
PFN_vkCreateFence CreateFence;
PFN_vkDestroyFence DestroyFence;
PFN_vkWaitForFences WaitForFences;
PFN_vkResetFences ResetFences;
PFN_vkGetFenceStatus GetFenceStatus;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
};
@@ -0,0 +1,680 @@
#pragma once
#include <vulkan/vulkan.h>
#include <list>
#include <vulkan/vulkan_android.h>
struct VkTable {
PFN_vkCreateInstance CreateInstance;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
PFN_vkCreateDevice CreateDevice;
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
PFN_vkDestroyDevice DestroyDevice;
PFN_vkGetDeviceQueue GetDeviceQueue;
PFN_vkDeviceWaitIdle DeviceWaitIdle;
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
PFN_vkQueuePresentKHR QueuePresentKHR;
PFN_vkQueueSubmit QueueSubmit;
PFN_vkCreateQueryPool CreateQueryPool;
PFN_vkDestroyQueryPool DestroyQueryPool;
PFN_vkCmdResetQueryPool CmdResetQueryPool;
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
PFN_vkGetQueryPoolResults GetQueryPoolResults;
PFN_vkCreateRenderPass CreateRenderPass;
PFN_vkDestroyRenderPass DestroyRenderPass;
PFN_vkCreateFramebuffer CreateFramebuffer;
PFN_vkDestroyFramebuffer DestroyFramebuffer;
PFN_vkCreateImageView CreateImageView;
PFN_vkDestroyImageView DestroyImageView;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkFreeMemory FreeMemory;
PFN_vkMapMemory MapMemory;
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkBindImageMemory BindImageMemory;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
PFN_vkCreateDescriptorPool CreateDescriptorPool;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
PFN_vkFreeDescriptorSets FreeDescriptorSets;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
PFN_vkCreatePipelineLayout CreatePipelineLayout;
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
PFN_vkCreateShaderModule CreateShaderModule;
PFN_vkDestroyShaderModule DestroyShaderModule;
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
PFN_vkDestroyPipeline DestroyPipeline;
PFN_vkCreateCommandPool CreateCommandPool;
PFN_vkDestroyCommandPool DestroyCommandPool;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
PFN_vkFreeCommandBuffers FreeCommandBuffers;
PFN_vkBeginCommandBuffer BeginCommandBuffer;
PFN_vkEndCommandBuffer EndCommandBuffer;
PFN_vkResetCommandBuffer ResetCommandBuffer;
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
PFN_vkCmdEndRenderPass CmdEndRenderPass;
PFN_vkCmdBindPipeline CmdBindPipeline;
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
PFN_vkCmdDraw CmdDraw;
PFN_vkCmdPushConstants CmdPushConstants;
PFN_vkCmdSetViewport CmdSetViewport;
PFN_vkCmdSetScissor CmdSetScissor;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
PFN_vkCmdCopyImage CmdCopyImage;
PFN_vkCmdBlitImage CmdBlitImage;
PFN_vkCmdDispatch CmdDispatch;
PFN_vkCreateComputePipelines CreateComputePipelines;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkResetDescriptorPool ResetDescriptorPool;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCreateSampler CreateSampler;
PFN_vkDestroySampler DestroySampler;
PFN_vkCreateSemaphore CreateSemaphore;
PFN_vkDestroySemaphore DestroySemaphore;
PFN_vkCreateFence CreateFence;
PFN_vkDestroyFence DestroyFence;
PFN_vkWaitForFences WaitForFences;
PFN_vkResetFences ResetFences;
PFN_vkGetFenceStatus GetFenceStatus;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
};
#include <android/log.h>
#include <string>
#define WLOG_TAG "DroidDeck_Renderer"
#define RLOG(...) if(verboseLog) __android_log_print(ANDROID_LOG_DEBUG,WLOG_TAG,__VA_ARGS__)
#define RLOG_E(...) __android_log_print(ANDROID_LOG_ERROR,WLOG_TAG,__VA_ARGS__)
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
#include <vulkan/vulkan_android.h>
#include <android/hardware_buffer.h>
#include <android/native_window.h>
#include <vector>
#include <unordered_map>
#include <thread>
#include <atomic>
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
#include <chrono>
#include "../scanout/ScanoutContext.h"
#include "lsfg/lsfg_probe.h"
#include <memory>
#include <string>
namespace lsfg { class Engine; }
namespace ddfg { class Engine; }
static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
struct SgsrPushConstants {
float ndc[4];
float viewportInfo[4];
float edgeSharpness;
};
struct NisPushConstants {
float ndc[4];
float viewportInfo[4];
float sharpness;
};
struct EasuPushConstants {
float ndc[4];
uint32_t con0[4], con1[4], con2[4], con3[4];
float outW, outH;
};
struct RcasPushConstants {
float ndc[4];
uint32_t con[4];
float outW, outH;
};
struct CasPushConstants {
float ndc[4];
float resolution[2];
float sharpness;
float _pad;
};
struct HdrPushConstants {
float ndc[4];
float resolution[2];
};
struct FxaaPushConstants {
float ndc[4];
float resolution[2];
};
struct ToonPushConstants {
float ndc[4];
float resolution[2];
};
struct ColorPushConstants {
float ndc[4];
float brightness;
float contrast;
float gamma;
float saturation;
};
struct NtscPushConstants {
float ndc[4];
float resolution[2];
float frameCount;
};
struct CrtPushConstants {
float ndc[4];
float resolution[2];
};
struct DebandPushConstants {
float ndc[4];
float resolution[2];
float strength;
};
class VulkanRendererContext {
public:
VulkanRendererContext(ANativeWindow* window, int cWidth, int cHeight, void* adrenotoolsHandle = nullptr,
bool lsfgVk11Compat = false);
~VulkanRendererContext();
void onSurfaceResized(int width, int height);
void setTransform(float ox, float oy, float sx, float sy);
void setClipRegion(int x, int y, int w, int h);
void updatePointerPosition(short x, short y);
void updateWindowContent(int64_t id, void* pixels, short w, short h, short stride, int x, int y);
void updateWindowContentAHB(int64_t id, AHardwareBuffer* ahb, short w, short h, int x, int y);
void updateCursorImage(void* pixels, short w, short h, short hotX, short hotY);
void setCursorVisible(bool visible);
void setRenderList(const int64_t* ids, const int* xs, const int* ys, int count);
void removeWindow(int64_t id);
void clearBackbuffer() {}
void beginBatch() {}
void endBatch() {}
void initScanout();
void destroyScanout();
void applyScanoutBuffer();
void initScanoutFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
void scanoutSetDst(int x, int y, int w, int h);
void scanoutSetBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
void scanoutSetCursorImage(void* pixels, short w, short h, short stride);
void scanoutSetCursorPos(short x, short y, short hotX, short hotY);
ScanoutContext scanout;
std::atomic<bool>& scanoutActive = scanout.scanoutActive;
std::atomic<bool>& gameFrameDelivered = scanout.gameFrameDelivered;
std::atomic<bool> surfaceDetached{false};
void detachSurface();
bool reattachSurface(ANativeWindow* newWindow);
bool verboseLog = true;
void setVerboseLog(bool v) { verboseLog = v; scanout.setVerboseLog(v); }
void dumpRendererInfo();
std::string adrenoDriverPath;
std::string adrenoDriverName;
std::string adrenoNativeLibDir;
void* vulkanHandle = nullptr;
std::atomic<bool> scanoutBlackFrameDone{false};
PFN_vkGetInstanceProcAddr gipa = nullptr;
VkTable vk_ = {};
void loadCustomDriver();
void loadInstanceDispatch();
void loadDeviceDispatch();
void setFilterMode(int mode);
void setUpscaler(int mode);
void setHqDownscale(bool enabled);
void setCas(bool enabled, int sharpness);
void setHdr(bool enabled);
void setDeband(bool enabled, int strength);
void setUpscaleSharpness(int sharpness);
void setFxaa(bool enabled);
void setToon(bool enabled);
void setCrt(bool enabled);
void setNtsc(bool enabled);
void setColorGrade(float brightness, float contrast, float gamma, float saturation);
void setSwapRB(bool enabled);
void setPresentMode(VkPresentModeKHR mode);
std::vector<int> getSupportedPresentModes() const;
const lsfg::Caps& lsfgCaps() const { return lsfgCaps_; }
void setFrameGenArmed(bool armed, int multiplier);
bool frameGenArmed() const { return fgArmed_.load(std::memory_order_relaxed); }
void frameGenStats(float out[6]) const;
int frameGenProblem() const;
void setLsfgCachePath(const char* path);
static constexpr int32_t kFgCaptureGame = -1;
void setFrameGenTuning(float flowScale, float refreshHz, int32_t captureHeight = 0);
void setFrameGenEngine(int kind);
void setDdFgTuning(int model, int perfPreset);
private:
struct WinTex {
VkImage img = VK_NULL_HANDLE;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
VkBuffer stg = VK_NULL_HANDLE;
VkDeviceMemory stgMem = VK_NULL_HANDLE;
void* mapped = nullptr;
VkDeviceSize cap = 0;
int w = 0;
int h = 0;
bool dirty = false;
bool isAHB = false;
bool needsTransition = false;
AHardwareBuffer* ahb = nullptr;
};
struct RenderEntry { int64_t id; int x, y; };
struct DrawEntry {
VkImage img = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
VkBuffer upload = VK_NULL_HANDLE;
int x=0, y=0, w=0, h=0;
bool needsTransition = false;
bool isAHB = false;
};
ANativeWindow* window;
int surfaceWidth, surfaceHeight, containerWidth, containerHeight;
std::atomic<int> clipRegionX{0}, clipRegionY{0}, clipRegionW{0}, clipRegionH{0};
void* adrenotoolsHandle = nullptr;
bool lsfgVk11Compat_ = false;
int filterMode = 0;
bool swapRB = false;
float maxAnisotropy = 1.0f;
bool cubicSupported = false;
VkPhysicalDeviceMemoryProperties memProperties{};
VkPresentModeKHR requestedPresentMode = VK_PRESENT_MODE_FIFO_KHR;
uint32_t graphicsQueueFamilyIndex = 0;
std::vector<VkPresentModeKHR> availablePresentModes;
std::unordered_map<int64_t, WinTex> texMap;
std::unordered_map<AHardwareBuffer*, WinTex> ahbImportCache;
std::unordered_map<int64_t, std::vector<AHardwareBuffer*>> windowAhbs;
std::vector<WinTex> deleteQueue;
std::vector<RenderEntry> renderList;
std::vector<DrawEntry> frameDraws;
std::vector<VkImageMemoryBarrier> frameAhbTransitions;
std::vector<VkImageMemoryBarrier> framePreUpload;
std::vector<VkImageMemoryBarrier> framePostUpload;
std::atomic<int> pointerX{0}, pointerY{0};
float sceneOffsetX=0.f, sceneOffsetY=0.f, sceneScaleX=1.f, sceneScaleY=1.f;
std::atomic<bool> cursorVisible{false};
short cursorHotX=0, cursorHotY=0, cursorTexW=0, cursorTexH=0;
std::vector<uint32_t> cursorPixels;
std::atomic<bool> isCursorImageDirty{false};
std::atomic<bool> cursorMoved{false};
VkImage cursorImg = VK_NULL_HANDLE;
VkDeviceMemory cursorMem = VK_NULL_HANDLE;
VkImageView cursorView = VK_NULL_HANDLE;
VkDescriptorSet cursorDS = VK_NULL_HANDLE;
VkBuffer cursorStg = VK_NULL_HANDLE;
VkDeviceMemory cursorStgM = VK_NULL_HANDLE;
void* cursorStgP = nullptr;
VkDeviceSize cursorStgC = 0;
VkDeviceSize cursorUploadSize = 0;
VkInstance instance;
VkSurfaceKHR surface;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkQueue graphicsQueue;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
VkFormat swapchainFmt;
VkExtent2D swapchainExt;
std::vector<VkImage> swapchainImages;
std::vector<VkImageView> swapchainViews;
std::vector<VkFramebuffer> swapchainFBs;
VkRenderPass renderPass = VK_NULL_HANDLE;
VkDescriptorSetLayout dsLayout = VK_NULL_HANDLE;
VkPipelineLayout pipeLayout = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
int upscalerMode = 0;
bool hqDownscale = false;
bool casEnabled = false;
int casSharpness = 60;
bool hdrEnabled = false;
float upscaleSharpness01 = 0.75f;
bool debandEnabled = false;
int debandStrength = 100;
bool fxaaEnabled = false;
bool toonEnabled = false;
bool crtEnabled = false;
bool ntscEnabled = false;
bool colorEnabled = false;
float colorBrightness = 0.0f;
float colorContrast = 0.0f;
float colorGamma = 1.0f;
float colorSaturation = 1.0f;
uint32_t ntscFrameCounter = 0;
VkSampler upscaleSampler = VK_NULL_HANDLE;
struct CompositeTarget {
VkImage img = VK_NULL_HANDLE;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkImageView storageView = VK_NULL_HANDLE;
VkFramebuffer fb = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
};
static constexpr uint32_t kMaxCompositeTargets = 7;
std::vector<CompositeTarget> compositeTargets;
VkRenderPass compositeRenderPass = VK_NULL_HANDLE;
uint32_t compositeW = 0, compositeH = 0;
uint32_t compositeIndex = 0;
bool compositeArmed = false;
bool swapchainTransferDst = false;
std::atomic<bool> fgArmed_{false};
std::atomic<int> fgMultiplier_{0};
std::atomic<float> fgFlowScale_{1.0f};
std::atomic<float> fgRefreshHz_{0.0f};
std::atomic<bool> fgConfigDirty_{true};
std::atomic<int32_t> fgCaptureHeight_{0};
void compositeExtentFor(uint32_t& w, uint32_t& h) const;
VkExtent2D renderExtent() const {
if (compositeActive() && (compositeW != swapchainExt.width || compositeH != swapchainExt.height))
return VkExtent2D{compositeW, compositeH};
return swapchainExt;
}
void recordCompositeToSwapchainTransfer(VkCommandBuffer cb, VkImage src, uint32_t imgIdx);
bool createCompositeRenderPass();
bool ensureCompositeTargets(uint32_t w, uint32_t h, uint32_t count);
void destroyCompositeTargets();
bool compositeActive() const;
VkRenderPass targetRenderPass() const;
VkFramebuffer targetFramebuffer(uint32_t imgIdx) const;
void copyCompositeToSwapchain(VkCommandBuffer cb, uint32_t imgIdx);
VkRenderPass cursorOverlayRenderPass = VK_NULL_HANDLE;
struct CursorOverlay {
bool draw = false;
float ox = 0, oy = 0, sx = 0, sy = 0, cw = 0, ch = 0;
short ptrX = 0, ptrY = 0, hotX = 0, hotY = 0, w = 0, h = 0;
};
CursorOverlay cursorOverlay_{};
bool createCursorOverlayRenderPass();
void recordCursorOverlay(VkCommandBuffer cb, uint32_t imgIdx);
bool cursorDrawnPerPresent() const;
static constexpr uint32_t kMaxPresentsPerFrame = 4;
struct FrameGenPlan {
uint32_t generations = 0;
uint32_t presents = 1;
uint32_t imgIdx[kMaxPresentsPerFrame] = {};
};
FrameGenPlan fgPlan_{};
std::unique_ptr<lsfg::Engine> lsfgEngine_;
uint64_t fgSourceFrames_ = 0;
std::string lsfgCachePath_;
bool lsfgEngineTried_ = false;
std::unique_ptr<ddfg::Engine> ddfgEngine_;
bool ddfgEngineTried_ = false;
std::atomic<int> fgEngineKind_{0};
std::atomic<int> fgModel_{4};
std::atomic<int> fgPerfPreset_{1};
bool ensureDdFgEngine();
bool fgCapsOk() const;
uint32_t syncSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
void recreateSyncObjects();
uint32_t fgAcquireFailLog_ = 0;
float fgPresentedRate_ = 0.0f;
float fgSourceRate_ = 0.0f;
uint32_t fgSourceAccum_ = 0;
uint32_t fgPresentAccum_ = 0;
std::chrono::steady_clock::time_point fgRateWindowStart_{};
bool fgRateWindowOpen_ = false;
void trackPresentedRate(uint32_t presents);
bool ensureLsfgEngine();
uint32_t cmdSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
void recordFrameGenProcess(VkCommandBuffer cb);
void recordFrameGenGeneration(VkCommandBuffer cb, uint32_t g);
VkQueryPool fgQueryPool_ = VK_NULL_HANDLE;
bool fgTimestampsOk_ = false;
float fgTimestampPeriodNs_ = 0.0f;
bool fgQueryPending_[MAX_FRAMES_IN_FLIGHT] = {};
uint32_t fgQueryGens_[MAX_FRAMES_IN_FLIGHT] = {};
float fgChainMsPerGen_ = -1.0f;
uint32_t fgChainLogCount_ = 0;
void ensureFgQueryPool();
void destroyFgQueryPool();
void readFgQueryResult();
VkFormat offscreenFmt = VK_FORMAT_R8G8B8A8_UNORM;
VkRenderPass offscreenRenderPass = VK_NULL_HANDLE;
VkPipelineLayout postPipeLayout = VK_NULL_HANDLE;
VkPipeline sgsrPipeline = VK_NULL_HANDLE;
VkPipeline nisPipeline = VK_NULL_HANDLE;
VkPipeline sgsrQualityPipeline = VK_NULL_HANDLE;
VkPipeline easuPipeline = VK_NULL_HANDLE;
VkPipeline rcasPipeline = VK_NULL_HANDLE;
VkPipeline downscalePipeline = VK_NULL_HANDLE;
VkPipeline casPipelineOff = VK_NULL_HANDLE;
VkPipeline casPipelineSwap = VK_NULL_HANDLE;
VkPipeline hdrPipelineOff = VK_NULL_HANDLE;
VkPipeline hdrPipelineSwap = VK_NULL_HANDLE;
VkPipeline fxaaPipelineOff = VK_NULL_HANDLE;
VkPipeline fxaaPipelineSwap = VK_NULL_HANDLE;
VkPipeline toonPipelineOff = VK_NULL_HANDLE;
VkPipeline toonPipelineSwap = VK_NULL_HANDLE;
VkPipeline colorPipelineOff = VK_NULL_HANDLE;
VkPipeline colorPipelineSwap = VK_NULL_HANDLE;
VkPipeline ntscPipelineOff = VK_NULL_HANDLE;
VkPipeline ntscPipelineSwap = VK_NULL_HANDLE;
VkPipeline crtPipelineOff = VK_NULL_HANDLE;
VkPipeline crtPipelineSwap = VK_NULL_HANDLE;
VkPipeline debandPipelineSwap = VK_NULL_HANDLE;
VkImage offscreenImg = VK_NULL_HANDLE;
VkDeviceMemory offscreenMem = VK_NULL_HANDLE;
VkImageView offscreenView = VK_NULL_HANDLE;
VkFramebuffer offscreenFB = VK_NULL_HANDLE;
VkDescriptorSet offscreenDS = VK_NULL_HANDLE;
int offscreenW = 0, offscreenH = 0;
VkImage midImg = VK_NULL_HANDLE;
VkDeviceMemory midMem = VK_NULL_HANDLE;
VkImageView midView = VK_NULL_HANDLE;
VkFramebuffer midFB = VK_NULL_HANDLE;
VkDescriptorSet midDS = VK_NULL_HANDLE;
int midW = 0, midH = 0;
VkImage fx1Img = VK_NULL_HANDLE;
VkDeviceMemory fx1Mem = VK_NULL_HANDLE;
VkImageView fx1View = VK_NULL_HANDLE;
VkFramebuffer fx1FB = VK_NULL_HANDLE;
VkDescriptorSet fx1DS = VK_NULL_HANDLE;
int fx1W = 0, fx1H = 0;
VkImage fx2Img = VK_NULL_HANDLE;
VkDeviceMemory fx2Mem = VK_NULL_HANDLE;
VkImageView fx2View = VK_NULL_HANDLE;
VkFramebuffer fx2FB = VK_NULL_HANDLE;
VkDescriptorSet fx2DS = VK_NULL_HANDLE;
int fx2W = 0, fx2H = 0;
struct UpscaleFrame {
bool active = false;
int mode = 0;
int outX = 0, outY = 0, outW = 0, outH = 0;
bool cas = false;
bool hdr = false;
bool fxaa = false;
bool toon = false;
bool color = false;
bool ntsc = false;
bool crt = false;
bool deband = false;
SgsrPushConstants sgsrPC{};
NisPushConstants nisPC{};
EasuPushConstants easuPC{};
RcasPushConstants rcasPC{};
CasPushConstants casPC{};
HdrPushConstants hdrPC{};
FxaaPushConstants fxaaPC{};
ToonPushConstants toonPC{};
ColorPushConstants colorPC{};
NtscPushConstants ntscPC{};
CrtPushConstants crtPC{};
DebandPushConstants debandPC{};
} upFrame;
VkCommandPool cmdPool = VK_NULL_HANDLE;
std::vector<VkCommandBuffer> cmdBufs;
std::vector<VkSemaphore> imgAvailSems;
std::vector<VkSemaphore> renderDoneSems;
std::vector<VkFence> inFlightFences;
std::vector<VkFence> imgInFlight;
uint32_t currentFrame = 0;
VkSampler sampler = VK_NULL_HANDLE;
VkDescriptorPool winTexPool = VK_NULL_HANDLE;
std::atomic<bool> needsRender{false};
std::thread renderThread;
std::atomic<bool> isRunning{false};
std::atomic<bool> fbResized{false};
std::mutex renderMutex;
std::mutex dirtyMutex;
std::condition_variable dirtyCV;
std::shared_mutex frameMutex;
void createInstance();
void createSurface();
void pickPhysicalDevice();
lsfg::Caps lsfgCaps_{};
void createLogicalDevice();
void createSwapchain();
void createRenderPass();
void createDSLayout();
void createPipeline(bool blend, VkPipeline& out);
void createFramebuffers();
void createCmdPool();
void createSampler();
void createUpscaleSampler();
void createOffscreenRenderPass();
void createPostPipelines();
VkPipeline createPostPipeline(const uint32_t* fragCode, size_t fragSz, VkRenderPass rp);
bool createColorTarget(int w, int h, VkImage& img, VkDeviceMemory& mem,
VkImageView& view, VkFramebuffer& fb, VkDescriptorSet& ds);
void destroyColorTarget(VkImage& img, VkDeviceMemory& mem, VkImageView& view,
VkFramebuffer& fb, VkDescriptorSet& ds);
bool ensureOffscreen(int w, int h);
bool ensureMid(int w, int h);
bool ensureFx1(int w, int h);
bool ensureFx2(int w, int h);
void recordUpscalePasses(VkCommandBuffer cb, uint32_t imgIdx,
const std::vector<DrawEntry>& draws, bool cursorDrawn,
short ptrX, short ptrY, short curHotX, short curHotY,
short curW, short curH,
float ox, float oy, float sx, float sy,
float cw, float ch);
void planUpscaleFrame();
void createWinTexPool();
void createCursorPipeline();
void createCursorDS();
void createCmdBufs();
void createSyncObjects();
void cleanupSwapchain();
bool createWinTexResources(WinTex& wt, int w, int h);
bool importAHBToWinTex(WinTex& wt, AHardwareBuffer* ahb);
void cleanupAllAHBCache();
void flushDeleteQueue();
void destroyWinTex(WinTex& wt);
void ensureCursorTex(short w, short h);
void cleanupCursorTex();
void ensureCursorStaging(VkDeviceSize sz);
void recordCmdBuf(VkCommandBuffer cb, uint32_t imgIdx,
const std::vector<DrawEntry>& draws,
std::vector<VkImageMemoryBarrier>& ahbTransitions,
std::vector<VkImageMemoryBarrier>& preUpload,
std::vector<VkImageMemoryBarrier>& postUpload,
VkBuffer cursorUpload, bool hasCursorUpload,
float ox, float oy, float sx, float sy, float cw, float ch,
short ptrX, short ptrY, short curHotX, short curHotY,
short curW, short curH, bool curVis);
void renderLoop();
void renderFrame();
uint32_t findMemType(uint32_t filter, VkMemoryPropertyFlags props);
void createBuffer(VkDeviceSize sz, VkBufferUsageFlags usage,
VkMemoryPropertyFlags props, VkBuffer& buf, VkDeviceMemory& mem);
VkCommandBuffer beginOneTime();
void endOneTime(VkCommandBuffer cmd);
void transition(VkCommandBuffer cmd, VkImage img,
VkImageLayout oldL, VkImageLayout newL,
VkAccessFlags srcA, VkAccessFlags dstA,
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS);
VkShaderModule makeShader(const uint32_t* code, size_t sz);
};
+1 -1
View File
@@ -1,5 +1,5 @@
#include "ddfg_vkd.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <android/log.h>
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id) {
@@ -1,6 +1,6 @@
#include "lsfg_probe.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <cstdio>
#include <cstring>
+1 -1
View File
@@ -1,6 +1,6 @@
#include "lsfg_vkd.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <android/log.h>
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <android/hardware_buffer.h>
#include <android/native_window.h>
#include <android/rect.h>
#include <android/log.h>
#include <atomic>
#include <mutex>
#include <cstdint>
#ifndef SCANOUT_LOG
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
#endif
class ScanoutContext {
public:
bool loadApi();
void initFromWindow(ANativeWindow* win = nullptr);
void initFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
void destroy();
void setBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
bool setCursorImage(void* pixels, short w, short h, short stride);
bool setCursorPos(short x, short y, short hotX, short hotY);
void applyPendingCursor();
void setDst(int x, int y, int w, int h);
void setContainerSize(int w, int h) { containerWidth = w; containerHeight = h; }
void setSurfaceSize(int w, int h) { surfaceWidth = w; surfaceHeight = h; }
void setFallbackWindow(ANativeWindow* win) { window = win; }
void setVerboseLog(bool v) { verboseLog = v; }
bool isActive() const { return scanoutActive.load(); }
bool isGameFrameDelivered() const {
return gameFrameDelivered.load(std::memory_order_acquire);
}
void* debugGameSC() const { return scanoutGameSC; }
std::atomic<bool> scanoutActive{false};
std::atomic<bool> gameFrameDelivered{false};
private:
ANativeWindow* window = nullptr;
bool verboseLog = true;
int surfaceWidth = 0, surfaceHeight = 0, containerWidth = 0, containerHeight = 0;
void* scanoutGameSC = nullptr;
void* scanoutCursorSC = nullptr;
void* scanoutCursorBuf = nullptr;
int32_t scanoutCursorBufW = 0;
int32_t scanoutCursorBufH = 0;
void* scanoutTx = nullptr;
void* scanoutGameTx = nullptr;
ARect scanoutLastSrc{}, scanoutLastDst{};
bool scanoutGeoDirty = true;
bool scanoutVisShown = false;
bool scanoutApiLoaded = false;
void* fnSCCreateFromWin = nullptr;
void* fnSCRelease = nullptr;
void* fnSTCreate = nullptr;
void* fnSTDelete = nullptr;
void* fnSTApply = nullptr;
void* fnSTSetBuffer = nullptr;
void* fnSTSetZOrder = nullptr;
void* fnSTSetVisibility = nullptr;
void* fnSTSetGeometry = nullptr;
int32_t scanoutDstX = 0, scanoutDstY = 0, scanoutDstW = 0, scanoutDstH = 0;
bool gameScVisible = false;
std::mutex scanoutMutex;
short pendingCursorX = 0, pendingCursorY = 0, pendingCursorHotX = 0, pendingCursorHotY = 0;
bool cursorPosDirty = false;
bool cursorImageDirty = false;
};
@@ -8,7 +8,7 @@
#include <android/log.h>
#include "VkDispatchTable.h"
#include "VulkanRendererContext.h"
#include "lsfg/lsfg_engine.h"
#include "lsfg/lsfg_probe.h"
#include "lsfg/lsfg_vkd.h"
@@ -694,7 +694,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AgentGuest.readyListener = agentReadyListener
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
runtimeRemovalBlocked = true
@@ -3765,46 +3764,37 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
runningGame = { gestureGame },
))
private fun captureScreenshot(onDone: (Boolean) -> Unit) = copyGameFrame { bitmap ->
if (bitmap == null) {
onDone(false)
return@copyGameFrame
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
}
private val gameFrame: ((android.graphics.Bitmap?) -> Unit) -> Unit = { copyGameFrame(it) }
/** The game's own surface, without anything DroidDeck draws over it; the caller recycles the bitmap. */
private fun copyGameFrame(onFrame: (android.graphics.Bitmap?) -> Unit) {
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
else if (::surfaceView.isInitialized) surfaceView else null
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
onFrame(null)
onDone(false)
return
}
val bitmap = try {
android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
} catch (_: OutOfMemoryError) {
onFrame(null)
onDone(false)
return
}
try {
android.view.PixelCopy.request(source, bitmap, { result ->
if (result != android.view.PixelCopy.SUCCESS) {
bitmap.recycle()
onFrame(null)
} else onFrame(bitmap)
onDone(false)
return@request
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
}, uiHandler)
} catch (_: IllegalArgumentException) {
bitmap.recycle()
onFrame(null)
onDone(false)
}
}
@@ -5680,7 +5670,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
frameGenRequests.incrementAndGet()
}
if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null
if (com.droiddeck.launcher.agent.AgentAttachments.gameFrame === gameFrame) com.droiddeck.launcher.agent.AgentAttachments.gameFrame = null
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
relativeMouseRequests.shutdownNow()
backQamInput.cancel()
@@ -1,13 +1,9 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
@@ -54,22 +50,6 @@ object AgentAttachments {
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
}
/** Copies the running game's frame; set while a session is open. */
var gameFrame by mutableStateOf<(((Bitmap?) -> Unit) -> Unit)?>(null)
/** Saves [frame] for [chat] (or a new conversation) on the calling thread; returns its guest path. */
fun saveFrame(context: Context, chat: String?, frame: Bitmap): String? = runCatching {
val folder = chat ?: NEW
val dir = File(hostDir(context), folder).apply { mkdirs() }
val target = File(dir, "game-${System.currentTimeMillis()}.jpg")
val written = target.outputStream().use { frame.compress(Bitmap.CompressFormat.JPEG, 88, it) }
if (!written) {
target.delete()
return@runCatching null
}
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
/** Deletes copies that will not be sent. */
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
@@ -37,21 +37,6 @@ object AgentChats {
}
.sortedByDescending { it.updated }
/** The chats among [chats] where the user or the agent wrote [query], ignoring case. */
fun search(context: Context, chats: List<Chat>, query: String): List<Chat> {
val q = query.trim()
if (q.isEmpty()) return chats
return chats.filter { chat ->
chat.title.contains(q, ignoreCase = true) || read(file(context, chat.id)).entries.any { matches(it, q) }
}
}
internal fun matches(entry: Entry, query: String) = when (entry) {
is Entry.Asked -> entry.text.contains(query, ignoreCase = true)
is Entry.Said -> entry.text.contains(query, ignoreCase = true)
else -> false
}
fun delete(context: Context, id: String) {
file(context, id).delete()
File(AgentAttachments.hostDir(context), id).deleteRecursively()
@@ -87,7 +72,6 @@ object AgentChats {
is Entry.Thought -> JSONObject().put("thought", entry.text)
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
.apply { if (entry.parent.isNotEmpty()) put("parent", entry.parent) }
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
if (entry.planned) put("planned", true)
@@ -121,7 +105,7 @@ object AgentChats {
o.has("said") -> Entry.Said(o.getString("said"))
o.has("thought") -> Entry.Thought(o.getString("thought"))
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"), o.optString("parent"))
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
o.has("finished") -> Entry.Finished(
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
@@ -108,11 +108,8 @@ object ClaudeCode : AgentHarness {
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
val parent = o.optString("parent_tool_use_id").takeIf { it.isNotEmpty() && it != "null" }
return when (o.optString("type")) {
"stream_event" -> {
if (parent != null) return null
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
when (delta.optString("type")) {
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
@@ -126,18 +123,18 @@ object ClaudeCode : AgentHarness {
val entries = (0 until content.length()).mapNotNull { i ->
val block = content.optJSONObject(i) ?: return@mapNotNull null
when (block.optString("type")) {
"text" -> if (parent != null) null else block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> if (parent != null) null else block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"tool_use" -> {
val input = block.optJSONObject("input")
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input), parent = parent.orEmpty())
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
}
else -> null
}
}
val usage = message?.optJSONObject("usage")
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 && parent == null })
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
}
"user" -> {
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
@@ -29,11 +29,8 @@ object AgentHost {
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
data class Said(val text: String) : Entry
data class Thought(val text: String) : Entry
/** A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any. */
data class Used(
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
val parent: String = "",
) : Entry
/** A tool call; [output] stays null until its result arrives. */
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
@@ -74,9 +71,7 @@ object AgentHost {
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
"The restart ends this process, and this conversation continues on the new build. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -147,7 +142,6 @@ object AgentHost {
fun seen() {
unseen = false
appContext?.let { AgentNotice.clear(it) }
}
fun refresh(context: Context) {
@@ -468,19 +462,7 @@ object AgentHost {
if (!stopped && queue.isNotEmpty()) {
val next = queue.removeAt(0)
send(app, next.text, next.files)
} else if (!stopped) notifyEnded(app, error)
}
private fun notifyEnded(app: Context, error: String?) {
val start = entries.indexOfLast { it is Entry.Asked }
val said = entries.subList(start + 1, entries.size).lastOrNull { it is Entry.Said } as? Entry.Said
val reply = said?.let { choices(it.text) }
val kind = when {
error != null -> AgentNotice.Kind.FAILED
!reply?.options.isNullOrEmpty() -> AgentNotice.Kind.QUESTION
else -> AgentNotice.Kind.DONE
}
AgentNotice.post(app, kind, error ?: reply?.text?.takeIf { it.isNotBlank() }?.let { firstLine(it) } ?: "")
}
/** A message typed or retried by the user replaces the automatic resend. */
@@ -519,7 +501,7 @@ object AgentHost {
}
/** The latest todo list the agent wrote in this conversation. */
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" && it.parent.isEmpty() }?.let { (it as Entry.Used).input }
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
private fun tick() {
now = SystemClock.elapsedRealtime()
@@ -663,34 +645,3 @@ object AgentHost {
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
}
/** A reply split into its text and the options of a trailing choices block. */
internal data class Choices(val text: String, val options: List<String>)
private val FENCE = Regex("""[ \t]{0,3}(`{3,}|~{3,})(.*)""")
/** Walks Markdown fences so a choices block counts only at the top level and only as the last thing in the reply. */
internal fun choices(reply: String): Choices {
val lines = reply.split('\n')
var open = ""
var opener = -1
var openChoices = false
var block: IntRange? = null
lines.forEachIndexed { i, line ->
val fence = FENCE.matchEntire(line)
if (open.isEmpty()) {
if (fence != null) {
open = fence.groupValues[1]
opener = i
openChoices = fence.groupValues[2].trim() == "choices"
block = null
} else if (line.isNotBlank()) block = null
} else if (fence != null && fence.groupValues[1][0] == open[0] && fence.groupValues[1].length >= open.length && fence.groupValues[2].isBlank()) {
block = if (openChoices) opener..i else null
open = ""
}
}
val found = block?.takeIf { open.isEmpty() } ?: return Choices(reply, emptyList())
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
}
@@ -1,58 +0,0 @@
package com.droiddeck.launcher.agent
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.AgentPet
/** Tells the user a turn has ended when nothing on screen already does. */
internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2,
Intent(context, FrontEndActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val title = context.getString(when (kind) {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(open)
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_STATUS)
.build())
}
}
fun clear(context: Context) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
}
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context): Boolean {
if (AgentPet.floating) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
}
@@ -1,143 +0,0 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.TimeUnit
/** Claude Code's MCP servers and skills in the userland, through its own CLI and skills folder. */
internal object AgentTools {
data class Server(val name: String, val target: String, val status: String) {
/** Connectors come from the claude.ai account and are managed there, not by the CLI. */
val account get() = name.startsWith("claude.ai ")
}
data class Skill(val name: String, val description: String)
class Result(val ok: Boolean, val output: String)
private const val SKILLS = "root/.claude/skills"
private val SERVER = Regex("""^(.+?): (.+) - (.+)$""")
fun servers(context: Context): List<Server>? {
val result = run(context, listOf(ClaudeCode.binary, "mcp", "list"))
if (!result.ok) return null
return parseServers(result.output)
}
internal fun parseServers(output: String): List<Server> = output.lines().mapNotNull { line ->
SERVER.find(line.trim())?.destructured?.let { (name, target, status) -> Server(name, target, status) }
}
/** A URL is added as an HTTP server; anything else is the command that starts a stdio server. */
internal fun addCommand(name: String, target: String): List<String> {
val t = target.trim()
val base = listOf(ClaudeCode.binary, "mcp", "add", "--scope", "user")
return if (t.startsWith("http://") || t.startsWith("https://")) base + listOf("--transport", "http", name.trim(), t)
else base + listOf(name.trim(), "--") + words(t)
}
/** Splits a command line the way a shell would for quotes and backslashes, without expanding anything. */
internal fun words(line: String): List<String> {
val words = mutableListOf<String>()
val word = StringBuilder()
var inWord = false
var quote: Char? = null
var i = 0
while (i < line.length) {
val c = line[i]
when {
quote == '\'' -> if (c == '\'') quote = null else word.append(c)
c == '\\' && i + 1 < line.length && (quote == null || line[i + 1] == '"' || line[i + 1] == '\\') -> {
word.append(line[++i])
inWord = true
}
quote == '"' -> if (c == '"') quote = null else word.append(c)
c == '\'' || c == '"' -> {
quote = c
inWord = true
}
c.isWhitespace() -> if (inWord) {
words += word.toString()
word.clear()
inWord = false
}
else -> {
word.append(c)
inWord = true
}
}
i++
}
if (inWord) words += word.toString()
return words
}
fun add(context: Context, name: String, target: String) = run(context, addCommand(name, target))
fun remove(context: Context, name: String) = run(context, listOf(ClaudeCode.binary, "mcp", "remove", name))
fun skills(context: Context): List<Skill> =
File(LinuxRuntime.rootDir(context), SKILLS).listFiles { f -> f.isDirectory }.orEmpty().sortedBy { it.name.lowercase() }.map { dir ->
Skill(dir.name, description(File(dir, "SKILL.md")))
}
internal fun description(file: File): String = runCatching {
val lines = file.readLines()
if (lines.firstOrNull()?.trim() != "---") return@runCatching ""
lines.drop(1).takeWhile { it.trim() != "---" }.firstOrNull { it.startsWith("description:") }
?.removePrefix("description:")?.trim()?.trim('"', '\'').orEmpty()
}.getOrDefault("")
fun deleteSkill(context: Context, name: String): Boolean {
if (name.isEmpty() || name.contains('/') || name.startsWith(".")) return false
val root = File(LinuxRuntime.rootDir(context), SKILLS)
val dir = File(root, name)
if (dir.parentFile?.path != root.path) return false
return deleteTree(dir.toPath())
}
/** Deletes [path] and what is under it; a symbolic link is removed itself, never what it points to. */
internal fun deleteTree(path: Path): Boolean = runCatching {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return@runCatching true
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: java.io.IOException?): FileVisitResult {
if (exc != null) throw exc
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
true
}.getOrDefault(false)
private fun run(context: Context, command: List<String>): Result {
val child = runCatching { AgentHost.guest(context.applicationContext, command, connectAdb = false).start() }
.getOrElse { return Result(false, it.message.orEmpty()) }
val output = StringBuffer()
// The CLI can hold its output open past the deadline, so it is read beside the wait rather than before it.
val reader = Thread({ runCatching { child.inputStream.bufferedReader().forEachLine { output.append(it).append('\n') } } }, "agent-tools").apply { start() }
return try {
val ended = child.waitFor(90, TimeUnit.SECONDS)
if (!ended) child.destroyForcibly()
reader.join(2_000)
Result(ended && child.exitValue() == 0, output.toString().trim())
} catch (e: InterruptedException) {
child.destroyForcibly()
Thread.currentThread().interrupt()
Result(false, output.toString().trim())
} finally {
runCatching { child.inputStream.close() }
}
}
}
@@ -6,8 +6,6 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
@@ -21,7 +19,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.ErrorOutline
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
@@ -42,8 +39,6 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
@@ -58,13 +53,9 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.choices
@Composable
internal fun AgentEntry(
entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, answerable: Boolean = false,
children: List<Entry.Used> = emptyList(), turn: List<Entry> = emptyList(), onRevise: () -> Unit = {}, onSent: () -> Unit = {},
) {
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
@@ -75,43 +66,24 @@ internal fun AgentEntry(
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
}
}
is Entry.Said -> {
val reply = remember(entry.text) { choices(entry.text) }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
is Entry.Said -> SelectionContainer { AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running, children)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Result -> Unit
is Entry.Finished -> when {
last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply()
last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AgentTurnEnd(entry, changes, turn)
AgentPlanActions(onRevise, onSent)
AgentTurnEnd(entry, changes)
AgentPlanActions(onRevise)
}
else -> AgentTurnEnd(entry, changes, turn)
}
}
}
/** The options a reply ends with; picking one sends it, while the reply is still the latest. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun AgentChoices(options: List<String>, answerable: Boolean, onSent: () -> Unit) {
val context = LocalContext.current
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
for (option in options) SecondaryButton(option, enabled = answerable, compact = true, modifier = Modifier.testTag("agent-choice")) {
AgentHost.send(context, option)
onSent()
else -> AgentTurnEnd(entry, changes)
}
}
}
/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */
@Composable
private fun AgentPlanActions(onRevise: () -> Unit, onSent: () -> Unit) {
private fun AgentPlanActions(onRevise: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val go = stringResource(R.string.agent_plan_go_message)
@@ -119,7 +91,6 @@ private fun AgentPlanActions(onRevise: () -> Unit, onSent: () -> Unit) {
PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) {
AgentHost.choosePlan(context, false)
AgentHost.send(context, go)
onSent()
}
SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) {
AgentHost.choosePlan(context, true)
@@ -135,18 +106,13 @@ internal data class Changes(val files: Int, val added: Int, val removed: Int)
/** The edits of the turn that ends at [end], or null when it changed no file. */
internal fun turnChanges(entries: List<Entry>, end: Int): Changes? {
val start = entries.subList(0, end).indexOfLast { it is Entry.Asked }
val edits = turnEdits(entries.subList(start + 1, end))
// Plan mode saves its plan as a file of its own, which is not a change to anything.
val edits = entries.subList(start + 1, end).filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }
.filter { !it.path.contains("/.claude/plans/") }
if (edits.isEmpty()) return null
return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed })
}
/** The edits in [turn] that took, in order. Plan mode saves its plan as a file of its own, which is not a change to anything. */
internal fun turnEdits(turn: List<Entry>): List<Diff> =
turn.filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }.filter { !it.path.contains("/.claude/plans/") }
/** What the agent said in [turn], to copy as one text. */
internal fun turnReply(turn: List<Entry>): String = turn.filterIsInstance<Entry.Said>().joinToString("\n\n") { it.text }
internal class Diff(val path: String, val lines: List<String>) {
val added = lines.count { it.startsWith("+") }
val removed = lines.count { it.startsWith("-") }
@@ -163,11 +129,9 @@ internal fun diffOf(entry: Entry.Used): Diff? {
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?, turn: List<Entry>) {
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable { mutableStateOf(false) }
val reply = turnReply(turn)
val text = when {
entry.stopped -> stringResource(R.string.agent_stopped)
entry.error != null -> stringResource(R.string.agent_failed, entry.error)
@@ -179,38 +143,18 @@ private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?, turn: List<En
}.joinToString(" · ")
}
}
if (text.isNullOrEmpty() && changes == null && reply.isEmpty()) return
if (text.isNullOrEmpty() && changes == null) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
if (changes != null) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.clip(Shape12).background(if (open) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant).clickable { open = !open }
.padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
) {
Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant)
Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good)
Text("−${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error)
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.weight(1f, fill = false))
if (reply.isNotEmpty()) CopyButton(reply, stringResource(R.string.agent_copy_reply))
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant)
}
if (open && changes != null) Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (diff in turnEdits(turn)) {
Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
}
}
}
@Composable
private fun CopyButton(text: String, label: String) {
val clipboard = LocalClipboardManager.current
val pal = LocalPalette.current
Icon(
Icons.Outlined.ContentCopy, label, tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(Shape12).clickable { clipboard.setText(AnnotatedString(text)) }.padding(6.dp).testTag("agent-copy"),
)
}
@Composable
@@ -272,7 +216,7 @@ private fun AgentTodos(list: String) {
/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean, children: List<Entry.Used> = emptyList()) {
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
@@ -301,17 +245,6 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean, children: List<En
}
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (children.isNotEmpty()) {
val latest = children.last()
Text(
pluralStringResource(R.plurals.agent_subagent_steps, children.size, children.size) + " · " + latest.tool + " " + latest.detail,
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 34.dp, end = 10.dp, bottom = 8.dp),
)
}
if (open && children.isNotEmpty()) Column(Modifier.padding(start = 10.dp, end = 4.dp, bottom = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (child in children) AgentToolCall(child, running && child.output == null)
}
if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
@@ -356,11 +289,7 @@ private fun DiffBox(diff: Diff) {
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant,
modifier = Modifier.weight(1f).padding(bottom = 3.dp))
CopyButton(text, stringResource(R.string.agent_copy))
}
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
SelectionContainer {
Text(
text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = color, lineHeight = 17.sp,
@@ -43,10 +43,6 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
@@ -70,12 +66,12 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
@@ -97,7 +93,6 @@ import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
@@ -121,54 +116,34 @@ import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS }
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
private const val COMPOSER_SLIDE_MS = 350L
/**
* The chat with the model, usage and menu on top and the editor at the bottom. Scrolling back
* through older messages hides the editor behind a small pill and stops following new output.
* [inputModifier] goes on the first control, where a controller lands without raising the keyboard.
* The chat with the composer at the bottom. The composer is the full editor only while it is
* being typed in; reading shrinks it to one line, and scrolling back through older messages
* hides it behind a small pill. [startTyping] opens an empty conversation ready to type.
*/
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPage(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
menuSlot: AgentMenuSlot? = null,
) = AgentPageContent(modifier, inputModifier, visible, hidesPet, menuSlot)
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet, showControlsWithoutKeyboard = false, menuSlot)
// Lab overlays run against the installed APK, so these entry points keep their JVM signatures.
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPageWithControls(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
showControlsWithoutKeyboard: Boolean,
) = AgentPageContent(modifier, inputModifier, visible, hidesPet = true, drawer = true)
/** Whether the session drawer's chat keeps the model, usage and menu in the editor's row, giving the conversation that row's height. */
internal object AgentDrawerLayout {
private const val KEY = "drawer_inline_controls"
var inline by mutableStateOf(true)
private set
private var loaded = false
fun load(context: android.content.Context) {
if (loaded) return
loaded = true
inline = AgentHost.prefs(context).getBoolean(KEY, true)
}
fun set(context: android.content.Context, on: Boolean) {
inline = on
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
}
}
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet = true, showControlsWithoutKeyboard = showControlsWithoutKeyboard)
@Composable
private fun AgentPageContent(
modifier: Modifier, inputModifier: Modifier, visible: Boolean, hidesPet: Boolean, menuSlot: AgentMenuSlot? = null, drawer: Boolean = false,
modifier: Modifier, inputModifier: Modifier, visible: Boolean, startTyping: Boolean, hidesPet: Boolean,
showControlsWithoutKeyboard: Boolean, menuSlot: AgentMenuSlot? = null,
) {
val context = LocalContext.current
val view = LocalView.current
@@ -183,19 +158,9 @@ private fun AgentPageContent(
}
}
remember { AgentHost.refresh(context) }
remember { AgentDrawerLayout.load(context) }
val inline = drawer && AgentDrawerLayout.inline
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
// A stopped activity keeps its composition; the page is only on screen while its host is started.
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
var started by remember(lifecycle) { mutableStateOf(lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) }
DisposableEffect(lifecycle) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, _ -> started = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED) }
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
DisposableEffect(visible, hidesPet, started) {
val counts = visible && hidesPet && started
DisposableEffect(visible, hidesPet) {
val counts = visible && hidesPet
if (counts) AgentPet.agentOnScreen++
onDispose { if (counts) AgentPet.agentOnScreen-- }
}
@@ -207,23 +172,17 @@ private fun AgentPageContent(
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
val composer = remember { ComposerState() }
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
val focusManager = LocalFocusManager.current
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
var menuOpen by rememberSaveable { mutableStateOf(false) }
val menu: @Composable () -> Unit = {
AgentMenu(menuOpen, { menuOpen = it }, onPanel = { panel = it }, onSetup = { setup = true })
}
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
menu()
}) else null
// A host with a title bar shows the top bar there.
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES && panel != AgentPanel.TOOLS
// A host with a title bar shows the menu there; otherwise it floats over the conversation's top corner.
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES
if (menuSlot != null) DisposableEffect(menuSlot, inSlot) {
menuSlot.content = if (inSlot) topBar else null
menuSlot.content = if (inSlot) menu else null
onDispose { menuSlot.content = null }
}
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
@@ -232,7 +191,7 @@ private fun AgentPageContent(
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
true
},
@@ -246,22 +205,11 @@ private fun AgentPageContent(
AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE }
AgentProcessList(Modifier.weight(1f))
}
AgentPanel.TOOLS -> {
AgentPanelBar(stringResource(R.string.agent_tools)) { panel = AgentPanel.NONE }
AgentToolsPanel(Modifier.weight(1f))
}
else -> {
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
else -> Unit
}
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
// Only dragging back through older messages stops following the latest; reaching the bottom again resumes it.
// Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more.
var readingBack by remember { mutableStateOf(false) }
LaunchedEffect(AgentHost.chat) { readingBack = false }
LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } }
val dragBack = remember {
object : NestedScrollConnection {
@@ -275,53 +223,57 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned {
// The editor sliding in or the keyboard rising shrinks the list from below; a list following the latest keeps it in view, even mid-drag.
// Scrolling remeasures the list, which Compose refuses during a measure pass, so this runs once positioning is done.
val height = it.size.height
val shrunk = listHeight - height
listHeight = height
if (shrunk > 0 && !readingBack) list.dispatchRawDelta(shrunk.toFloat())
},
) {
val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty()
var wasHidden by remember { mutableStateOf(false) }
LaunchedEffect(hidden) {
if (hidden) wasHidden = true
else if (wasHidden) {
wasHidden = false
// The composer takes its height back as it slides in; the latest message stays above it.
kotlinx.coroutines.delay(COMPOSER_SLIDE_MS)
list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2)
}
}
Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) {
AgentConversation(
Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.focused) focusManager.clearFocus()
if (composer.typing) focusManager.clearFocus()
}
},
list, following = !readingBack, onRevise = { composer.open() }, onSent = toLatest,
list, onRevise = { composer.open() },
)
androidx.compose.animation.AnimatedVisibility(
hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
) {
AgentJumpPill(toLatest)
}
if (menuSlot == null) Box(Modifier.align(Alignment.TopEnd).padding(top = 4.dp)) { menu() }
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, visible, inlineControls, onPanel = { panel = it }, onSent = toLatest)
AgentComposer(composer, draft, inputModifier, panel, togglePanel, showControlsWithoutKeyboard)
}
}
}
}
}
/** Whether the editor has the cursor; [open] puts it there. */
/** Whether the composer is the full editor; [open] also puts the cursor in it. */
@Stable
private class ComposerState {
var focused by mutableStateOf(false)
private class ComposerState(typing: Boolean) {
var typing by mutableStateOf(typing)
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
var opening = false
fun open() {
typing = true
opening = true
focusRequests++
if (focused) consumeFocusRequest()
}
fun hasUnconsumedFocusRequest() = focusRequests > consumedFocusRequests
@@ -337,37 +289,6 @@ internal class AgentMenuSlot {
var content by mutableStateOf<(@Composable () -> Unit)?>(null)
}
/** The model and how full the context is, then the [menu]. */
@Composable
private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, menu: @Composable () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
ModelChip(panel, onPanel, firstControl, Modifier.weight(1f, fill = false))
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
menu()
}
}
/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */
@Composable
private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) {
val context = LocalContext.current
val pal = LocalPalette.current
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl)
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = if (compact) listOf(model)
else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
/** History, processes, a new conversation, the pet and setup, folded behind one button. */
@Composable
private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
@@ -385,9 +306,6 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
Row(verticalAlignment = Alignment.CenterVertically) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 36.dp, tag = "agent-history") { onOpen(false); onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 36.dp, tag = "agent-processes") { onOpen(false); onPanel(AgentPanel.PROCESSES) }
if (AgentHost.harness == com.droiddeck.launcher.agent.ClaudeCode) HeaderAction(
Icons.Outlined.Extension, stringResource(R.string.agent_tools), size = 36.dp, tag = "agent-tools",
) { onOpen(false); onPanel(AgentPanel.TOOLS) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 36.dp, tag = "agent-new") {
onOpen(false)
AgentHost.forget(context)
@@ -434,20 +352,18 @@ internal fun HeaderAction(
}
@Composable
private fun AgentConversation(modifier: Modifier, list: LazyListState, following: Boolean, onRevise: () -> Unit, onSent: () -> Unit) {
private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) {
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
// A subagent's calls are shown inside the call that started it.
val shown = AgentHost.entries.indices.filter { (AgentHost.entries[it] as? Entry.Used)?.parent.isNullOrEmpty() }
val items = shown.size + (if (working) 1 else 0)
val follow by rememberUpdatedState(following)
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
LaunchedEffect(items) {
if (items == 0 || !follow) return@LaunchedEffect
if (items == 0) return@LaunchedEffect
list.animateScrollToItem(items - 1)
list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (follow && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
if (AgentHost.entries.isEmpty() && !working) {
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
@@ -459,15 +375,11 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, following
}
val start = AgentHost.entries.indexOfLast { it is Entry.Asked }
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(shown.size) { n ->
val i = shown[n]
items(AgentHost.entries.size) { i ->
val entry = AgentHost.entries[i]
AgentEntry(
entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex,
children = if (entry is Entry.Used) AgentHost.entries.filter { it is Entry.Used && it.parent == entry.id && entry.id.isNotEmpty() }.map { it as Entry.Used } else emptyList(),
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null,
turn = if (entry is Entry.Finished) AgentHost.entries.subList(AgentHost.entries.subList(0, i).indexOfLast { it is Entry.Asked } + 1, i) else emptyList(),
answerable = !working && i > start && AgentHost.queue.isEmpty(), onRevise = onRevise, onSent = onSent,
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise,
)
}
if (working) item { AgentLive() }
@@ -653,13 +565,14 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
showControlsWithoutKeyboard: Boolean,
) {
val context = LocalContext.current
var draft by draftState
var labOpen by rememberSaveable { mutableStateOf(false) }
if (AgentHost.lab == null) labOpen = false
var hadFocus by remember { mutableStateOf(false) }
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
@@ -673,33 +586,90 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
onSent()
}
}
draft = ""
}
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) {
// Leaving the composer for the conversation, by touch or D-pad, is reading.
Column(
Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged {
if (it.hasFocus) hadFocus = true
else if (hadFocus) {
hadFocus = false
if (composer.typing && !composer.opening) composer.typing = false
}
},
) {
if (labOpen) AgentLabCard()
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, visible, controls, send)
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() }
else -> Unit
}
if (composer.typing) {
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, inputModifier, panel, onPanel, highlightControls = showControlsWithoutKeyboard, send = send)
} else AgentReadingBar(
composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }, onUsage = { onPanel(AgentPanel.USAGE) },
) {
// The session drawer is driven by a controller, so its editor opens without raising the keyboard.
if (showControlsWithoutKeyboard) {
composer.typing = true
composer.opening = true
} else composer.open()
}
}
}
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
@Composable
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
private fun AgentReadingBar(
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit, onOpen: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable(onClick = onOpen).testTag("agent-composer-bar")
.padding(start = 14.dp, end = 4.dp),
) {
Text(
draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp,
color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp),
)
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen, onLab) }
ContextRing("agent-usage-bar", onUsage)
if (working) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f))
.clickable { AgentHost.stop(context) }.testTag("agent-stop"),
) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) }
}
}
/** The full editor: model and usage on top, the text with attach, stop and send under them. */
@Composable
private fun AgentEditor(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
highlightControls: Boolean = false, send: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val voice = remember { AgentVoice(context.applicationContext, { draftState.value }) { draftState.value = it } }
val voiceAvailable = remember { AgentVoice.available(context) }
DisposableEffect(voice) { onDispose { voice.stop() } }
LaunchedEffect(visible) { if (!visible) voice.stop() }
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
@@ -724,11 +694,26 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
.border(if (focused || highlightControls) 2.dp else 1.dp, if (focused || highlightControls) pal.primary else pal.line, Shape16).padding(6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }
.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
}
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
@@ -738,82 +723,27 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
draft, { draft = it },
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
if (it.isFocused) {
composer.consumeFocusRequest()
composer.opening = false
}
}.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = {
voice.stop()
send()
}),
keyboardActions = KeyboardActions(onSend = { send() }),
minLines = 1,
maxLines = 8,
)
}
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
// An empty message has nothing to send, so the button there dictates one instead.
if ((!canSend || voice.listening) && voiceAvailable) VoiceButton(voice) { voice.start(draft) }
else RoundButton(
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) {
voice.stop()
send()
}
}
}
}
@Composable
private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) onStart() else android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
} else null
RoundButton(
if (voice.listening) Icons.Outlined.MicOff else Icons.Outlined.Mic, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice),
if (voice.listening) pal.primary else pal.surfaceVariant, if (voice.listening) pal.onPrimary else pal.onBackground, "agent-voice",
) {
when {
voice.listening -> voice.finish()
context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED -> onStart()
ask != null -> ask.launch(android.Manifest.permission.RECORD_AUDIO)
else -> android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
}
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
@Composable
private fun GameFrameButton() {
val context = LocalContext.current
val pal = LocalPalette.current
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
val grab = AgentAttachments.gameFrame ?: return@RoundButton
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
) { send() }
}
}
}
@@ -41,18 +41,6 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import com.droiddeck.launcher.agent.AgentTools
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentChats
import com.droiddeck.launcher.agent.AgentHarness
@@ -112,85 +100,44 @@ internal fun AgentHistory(modifier: Modifier, onOpened: () -> Unit) {
}
return
}
var query by rememberSaveable { mutableStateOf("") }
val found by produceState<List<AgentChats.Chat>?>(null, chats, query) {
if (query.isNotBlank()) delay(250)
value = withContext(Dispatchers.IO) { AgentChats.search(context, chats, query) }
}
val working = AgentHost.state == AgentHost.State.WORKING
Column(modifier.fillMaxWidth()) {
AgentHistorySearch(query) { query = it }
val shown = found ?: chats
if (shown.isEmpty()) Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.agent_history_no_match), fontSize = 15.sp, color = pal.onSurfaceVariant)
} else LazyColumn(Modifier.weight(1f).fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(shown, key = { it.id }) { chat -> AgentHistoryRow(chat, working, onOpened) { version++ } }
}
}
}
@Composable
private fun AgentHistorySearch(query: String, onQuery: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp).height(44.dp).clip(Shape14).background(colors.surface)
.border(1.dp, pal.line, Shape14).padding(horizontal = 12.dp),
) {
Icon(Icons.Outlined.Search, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
Box(Modifier.weight(1f).padding(start = 8.dp)) {
if (query.isEmpty()) Text(stringResource(R.string.agent_history_search), fontSize = 15.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
query, onQuery, singleLine = true, textStyle = TextStyle(fontSize = 15.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag("agent-history-search"),
)
}
if (query.isNotEmpty()) Icon(Icons.Outlined.Close, stringResource(R.string.agent_close), tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(CircleShape).clickable { onQuery("") }.padding(5.dp))
}
}
@Composable
private fun AgentHistoryRow(chat: AgentChats.Chat, working: Boolean, onOpened: () -> Unit, onDeleted: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column {
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(chats, key = { it.id }) { chat ->
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
if (armed) {
AgentHost.delete(context, chat.id)
onDeleted()
} else armed = true
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
) {
if (armed) {
AgentHost.delete(context, chat.id)
version++
} else armed = true
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
@@ -313,117 +260,3 @@ private fun resetTime(context: android.content.Context, epochSeconds: Long): Str
else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME
return DateUtils.formatDateTime(context, ms, flags)
}
/** Claude Code's MCP servers, with a way to add and remove them, and the skills in its skills folder. */
@Composable
internal fun AgentToolsPanel(modifier: Modifier) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
var version by remember { mutableIntStateOf(0) }
var loading by remember { mutableStateOf(true) }
val servers by produceState<List<AgentTools.Server>?>(null, version) {
loading = true
value = withContext(Dispatchers.IO) { AgentTools.servers(context) }
loading = false
}
val skills by produceState(emptyList<AgentTools.Skill>(), version) { value = withContext(Dispatchers.IO) { AgentTools.skills(context) } }
var name by rememberSaveable { mutableStateOf("") }
var target by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
fun act(added: Boolean = false, action: suspend () -> AgentTools.Result) {
busy = true
message = null
scope.launch {
val result = withContext(Dispatchers.IO) { action() }
busy = false
if (!result.ok) message = result.output.ifBlank { context.getString(R.string.agent_tools_failed) }
else if (added) {
name = ""
target = ""
}
version++
}
}
LazyColumn(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
item { ToolsHeading(stringResource(R.string.agent_tools_servers)) }
val list = servers
when {
loading && list == null -> item { Text(stringResource(R.string.agent_tools_loading), fontSize = 13.sp, color = pal.onSurfaceVariant) }
list == null -> item { Text(stringResource(R.string.agent_tools_failed), fontSize = 13.sp, color = AttentionAmber) }
list.isEmpty() -> item { Text(stringResource(R.string.agent_tools_no_servers), fontSize = 13.sp, color = pal.onSurfaceVariant) }
else -> items(list, key = { "mcp:" + it.name }) { server ->
var armed by remember(server.name) { mutableStateOf(false) }
ToolsRow(server.name, server.target + " · " + server.status) {
if (!server.account) SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_tools_remove), compact = true, enabled = !busy,
) { if (armed) act { AgentTools.remove(context, server.name) } else armed = true }
}
}
}
item {
Column(
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ToolsField(name, { name = it }, stringResource(R.string.agent_tools_name), "agent-tools-name")
ToolsField(target, { target = it }, stringResource(R.string.agent_tools_target), "agent-tools-target")
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.agent_tools_add_hint), fontSize = 12.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f))
PrimaryButton(stringResource(R.string.agent_tools_add), enabled = !busy && name.isNotBlank() && target.isNotBlank(), compact = true) {
act(added = true) { AgentTools.add(context, name, target) }
}
}
message?.let { Text(it, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = AttentionAmber) }
}
}
item { ToolsHeading(stringResource(R.string.agent_tools_skills)) }
if (skills.isEmpty()) item { Text(stringResource(R.string.agent_tools_no_skills), fontSize = 13.sp, color = pal.onSurfaceVariant) }
items(skills, key = { "skill:" + it.name }) { skill ->
var armed by remember(skill.name) { mutableStateOf(false) }
ToolsRow(skill.name, skill.description) {
SecondaryButton(stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true, enabled = !busy) {
if (armed) act {
AgentTools.Result(AgentTools.deleteSkill(context, skill.name), "")
} else armed = true
}
}
}
}
}
@Composable
private fun ToolsHeading(text: String) {
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = LocalPalette.current.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp))
}
@Composable
private fun ToolsRow(title: String, detail: String, action: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail.isNotBlank()) Text(detail, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
action()
}
}
@Composable
private fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag),
)
}
}
@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -33,6 +34,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
@@ -60,7 +62,9 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
@@ -553,7 +557,10 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Box(Modifier.weight(1f)) { menuSlot.content?.invoke() }
Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.padding(start = 4.dp))
Spacer(Modifier.weight(1f))
menuSlot.content?.invoke()
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
@@ -40,7 +40,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.agent.AgentSetup.Status
import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
@@ -119,15 +118,6 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_drawer_inline), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.agent_drawer_inline_hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
ToggleSwitch(AgentDrawerLayout.inline, label = stringResource(R.string.agent_drawer_inline), modifier = Modifier.testTag("setting-agent-drawer-inline")) {
AgentDrawerLayout.set(context, it)
}
}
if (AgentSetup.ready || AgentSetup.completed(context)) PrimaryButton(stringResource(R.string.agent_setup_done), main = true, onClick = onDone)
StorageCard()
}
@@ -1,74 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft. */
internal class AgentVoice(private val context: Context, private val draft: () -> String, private val onText: (String) -> Unit) {
var listening by mutableStateOf(false)
private set
private var recognizer: SpeechRecognizer? = null
private var base = ""
private var written = ""
fun start(typed: String) {
stop()
val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() ?: return
recognizer = speech
base = typed.trimEnd().let { if (it.isEmpty()) it else "$it " }
written = typed
speech.setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) { listening = true }
override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {}
override fun onError(error: Int) { if (recognizer === speech) stop() }
override fun onResults(results: Bundle?) {
if (recognizer !== speech) return
heard(results)
stop()
}
override fun onPartialResults(partialResults: Bundle?) { if (recognizer === speech) heard(partialResults) }
override fun onEvent(eventType: Int, params: Bundle?) {}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
runCatching { speech.startListening(intent) }.onFailure { stop() }
}
private fun heard(results: Bundle?) {
val spoken = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.takeIf { it.isNotBlank() } ?: return
if (draft() != written) return stop()
written = base + spoken
onText(written)
}
/** Ends listening but keeps the recognizer until its final result arrives. */
fun finish() {
val speech = recognizer ?: return
listening = false
runCatching { speech.stopListening() }.onFailure { stop() }
}
fun stop() {
listening = false
val speech = recognizer ?: return
recognizer = null
runCatching { speech.cancel() }
runCatching { speech.destroy() }
}
companion object {
fun available(context: Context) = SpeechRecognizer.isRecognitionAvailable(context)
}
}
+2
View File
@@ -1179,6 +1179,7 @@
<string name="agent_plan_untouched">لم يتغير شيء بعد</string>
<string name="agent_plan_go_message">المضي قدماً في الخطة.</string>
<string name="agent_send_now">إرسال الآن</string>
<string name="agent_message">رسالة</string>
<string name="agent_more">المزيد</string>
<string name="agent_close">إغلاق</string>
<string name="agent_latest">الأحدث</string>
@@ -2682,6 +2683,7 @@
<string name="setup_agent_pet_float">فوق التطبيقات الأخرى</string>
<string name="setup_agent_pet_float_hint">اسمح لـ DeeDee بالظهور فوق كل التطبيقات وفتح المحادثة هناك</string>
<string name="setup_agent_pet_allow">السماح</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">الدردشة مع DeeDee</string>
<string name="library_display">العرض</string>
<string name="library_display_larger">بطاقات أكبر</string>
@@ -1197,6 +1197,7 @@
<string name="agent_plan_untouched">Aún no hay cambios</string>
<string name="agent_plan_go_message">Adelante con el plan.</string>
<string name="agent_send_now">Enviar ahora</string>
<string name="agent_message">Mensaje</string>
<string name="agent_more">Más</string>
<string name="agent_close">Cerrar</string>
<string name="agent_latest">Más reciente</string>
@@ -2614,6 +2615,7 @@
<string name="setup_agent_pet_float">Sobre otras aplicaciones</string>
<string name="setup_agent_pet_float_hint">Permite que DeeDee flote sobre todas las aplicaciones y abra su chat allí</string>
<string name="setup_agent_pet_allow">Permitir</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chatear con DeeDee</string>
<string name="library_display">Vista</string>
<string name="library_display_larger">Tarjetas más grandes</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Още нищо не е променено</string>
<string name="agent_plan_go_message">Изпълни плана.</string>
<string name="agent_send_now">Изпрати сега</string>
<string name="agent_message">Съобщение</string>
<string name="agent_more">Още</string>
<string name="agent_close">Затвори</string>
<string name="agent_latest">Най-новото</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Над други приложения</string>
<string name="setup_agent_pet_float_hint">Позволи на DeeDee да се показва над всяко приложение и да отваря чата си там</string>
<string name="setup_agent_pet_allow">Разреши</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Чат с DeeDee</string>
<string name="library_display">Изглед</string>
<string name="library_display_larger">По-големи карти</string>
+2
View File
@@ -1173,6 +1173,7 @@
<string name="agent_plan_untouched">Zatím se nic nezměnilo</string>
<string name="agent_plan_go_message">Proveď plán.</string>
<string name="agent_send_now">Odeslat nyní</string>
<string name="agent_message">Zpráva</string>
<string name="agent_more">Více</string>
<string name="agent_close">Zavřít</string>
<string name="agent_latest">Nejnovější</string>
@@ -2630,6 +2631,7 @@
<string name="setup_agent_pet_float">Nad ostatními aplikacemi</string>
<string name="setup_agent_pet_float_hint">Umožněte DeeDee zobrazovat se nad všemi aplikacemi a otevírat v nich chat.</string>
<string name="setup_agent_pet_allow">Povolit</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat s DeeDee</string>
<string name="library_display">Zobrazení</string>
<string name="library_display_larger">Větší karty</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Intet ændret endnu</string>
<string name="agent_plan_go_message">Gå i gang med planen.</string>
<string name="agent_send_now">Send nu</string>
<string name="agent_message">Besked</string>
<string name="agent_more">Mere</string>
<string name="agent_close">Luk</string>
<string name="agent_latest">Seneste</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Over andre apps</string>
<string name="setup_agent_pet_float_hint">Lad DeeDee svæve over alle apps og åbne chatten der</string>
<string name="setup_agent_pet_allow">Tillad</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat med DeeDee</string>
<string name="library_display">Visning</string>
<string name="library_display_larger">Større kort</string>
+2
View File
@@ -1159,6 +1159,7 @@
<string name="agent_plan_untouched">Noch nichts geändert</string>
<string name="agent_plan_go_message">Führe den Plan aus.</string>
<string name="agent_send_now">Jetzt senden</string>
<string name="agent_message">Nachricht</string>
<string name="agent_more">Mehr</string>
<string name="agent_close">Schließen</string>
<string name="agent_latest">Neueste</string>
@@ -2570,6 +2571,7 @@
<string name="setup_agent_pet_float">Über anderen Apps</string>
<string name="setup_agent_pet_float_hint">DeeDee über allen Apps schweben lassen und den Chat dort öffnen</string>
<string name="setup_agent_pet_allow">Erlauben</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Mit DeeDee chatten</string>
<string name="library_display">Anzeige</string>
<string name="library_display_larger">Größere Karten</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Δεν έχει αλλάξει τίποτα ακόμη</string>
<string name="agent_plan_go_message">Προχώρησε με το σχέδιο.</string>
<string name="agent_send_now">Αποστολή τώρα</string>
<string name="agent_message">Μήνυμα</string>
<string name="agent_more">Περισσότερα</string>
<string name="agent_close">Κλείσιμο</string>
<string name="agent_latest">Πιο πρόσφατο</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Πάνω από άλλες εφαρμογές</string>
<string name="setup_agent_pet_float_hint">Αφήστε το DeeDee να εμφανίζεται πάνω από κάθε εφαρμογή και να ανοίγει εκεί τη συνομιλία</string>
<string name="setup_agent_pet_allow">Να επιτρέπεται</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Συνομιλία με DeeDee</string>
<string name="library_display">Προβολή</string>
<string name="library_display_larger">Μεγαλύτερες κάρτες</string>
+2
View File
@@ -1170,6 +1170,7 @@
<string name="agent_plan_untouched">Aún no hay cambios</string>
<string name="agent_plan_go_message">Adelante con el plan.</string>
<string name="agent_send_now">Enviar ahora</string>
<string name="agent_message">Mensaje</string>
<string name="agent_more">Más</string>
<string name="agent_close">Cerrar</string>
<string name="agent_latest">Más reciente</string>
@@ -2604,6 +2605,7 @@
<string name="setup_agent_pet_float">Sobre otras aplicaciones</string>
<string name="setup_agent_pet_float_hint">Permite que DeeDee flote sobre todas las aplicaciones y abra su chat allí</string>
<string name="setup_agent_pet_allow">Permitir</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat con DeeDee</string>
<string name="library_display">Vista</string>
<string name="library_display_larger">Tarjetas más grandes</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Ei muutoksia vielä</string>
<string name="agent_plan_go_message">Aloita suunnitelman toteutus.</string>
<string name="agent_send_now">Lähetä nyt</string>
<string name="agent_message">Viesti</string>
<string name="agent_more">Lisää</string>
<string name="agent_close">Sulje</string>
<string name="agent_latest">Uusin</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Muiden sovellusten päällä</string>
<string name="setup_agent_pet_float_hint">Anna DeeDee:n leijua kaikkien sovellusten päällä ja avata keskustelunsa siellä</string>
<string name="setup_agent_pet_allow">Salli</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Keskustele DeeDee:n kanssa</string>
<string name="library_display">Näkymä</string>
<string name="library_display_larger">Suuremmat kortit</string>
+2
View File
@@ -1170,6 +1170,7 @@
<string name="agent_plan_untouched">Rien n’a encore changé</string>
<string name="agent_plan_go_message">Exécute le plan.</string>
<string name="agent_send_now">Envoyer maintenant</string>
<string name="agent_message">Message</string>
<string name="agent_more">Plus</string>
<string name="agent_close">Fermer</string>
<string name="agent_latest">Dernier</string>
@@ -2603,6 +2604,7 @@
<string name="setup_agent_pet_float">Au-dessus des autres applications</string>
<string name="setup_agent_pet_float_hint">Autorise DeeDee à flotter au-dessus de toutes les applications et à y ouvrir sa discussion</string>
<string name="setup_agent_pet_allow">Autoriser</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Discuter avec DeeDee</string>
<string name="library_display">Affichage</string>
<string name="library_display_larger">Cartes plus grandes</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">अभी तक कुछ नहीं बदला</string>
<string name="agent_plan_go_message">योजना के साथ आगे बढ़ें।</string>
<string name="agent_send_now">अभी भेजें</string>
<string name="agent_message">संदेश</string>
<string name="agent_more">अधिक</string>
<string name="agent_close">बंद करें</string>
<string name="agent_latest">नवीनतम</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">अन्य ऐप्स के ऊपर दिखाएँ</string>
<string name="setup_agent_pet_float_hint">DeeDee को हर ऐप के ऊपर दिखने दें और वहीं इसकी चैट खोलें</string>
<string name="setup_agent_pet_allow">अनुमति दें</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">DeeDee के साथ चैट करें</string>
<string name="library_display">डिस्प्ले</string>
<string name="library_display_larger">बड़े कार्ड</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Még semmi sem változott</string>
<string name="agent_plan_go_message">Hajtsd végre a tervet.</string>
<string name="agent_send_now">Küldés most</string>
<string name="agent_message">Üzenet</string>
<string name="agent_more">Továbbiak</string>
<string name="agent_close">Bezárás</string>
<string name="agent_latest">Legújabb</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Más alkalmazások felett</string>
<string name="setup_agent_pet_float_hint">Engedd, hogy DeeDee minden alkalmazás felett lebegjen és ott nyissa meg a csevegést</string>
<string name="setup_agent_pet_allow">Engedélyezés</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Csevegés DeeDee-vel</string>
<string name="library_display">Megjelenítés</string>
<string name="library_display_larger">Nagyobb kártyák</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">Belum ada perubahan</string>
<string name="agent_plan_go_message">Jalankan rencana ini.</string>
<string name="agent_send_now">Kirim sekarang</string>
<string name="agent_message">Pesan</string>
<string name="agent_more">Lainnya</string>
<string name="agent_close">Tutup</string>
<string name="agent_latest">Terbaru</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">Di atas aplikasi lain</string>
<string name="setup_agent_pet_float_hint">Izinkan DeeDee melayang di atas semua aplikasi dan membuka obrolannya di sana</string>
<string name="setup_agent_pet_allow">Izinkan</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat dengan DeeDee</string>
<string name="library_display">Tampilan</string>
<string name="library_display_larger">Kartu lebih besar</string>
+2
View File
@@ -1162,6 +1162,7 @@
<string name="agent_plan_untouched">Ancora nessuna modifica</string>
<string name="agent_plan_go_message">Procedi con il piano.</string>
<string name="agent_send_now">Invia ora</string>
<string name="agent_message">Messaggio</string>
<string name="agent_more">Altro</string>
<string name="agent_close">Chiudi</string>
<string name="agent_latest">Più recente</string>
@@ -2595,6 +2596,7 @@
<string name="setup_agent_pet_float">Sopra altre app</string>
<string name="setup_agent_pet_float_hint">Consenti a DeeDee di apparire sopra tutte le app e di aprire lì la sua chat</string>
<string name="setup_agent_pet_allow">Consenti</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Apri la chat con DeeDee</string>
<string name="library_display">Visualizzazione</string>
<string name="library_display_larger">Schede più grandi</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">まだ変更はありません</string>
<string name="agent_plan_go_message">計画を進めてください。</string>
<string name="agent_send_now">今すぐ送信</string>
<string name="agent_message">メッセージ</string>
<string name="agent_more">その他</string>
<string name="agent_close">閉じる</string>
<string name="agent_latest">最新</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">他のアプリの上に表示</string>
<string name="setup_agent_pet_float_hint">DeeDee をすべてのアプリの上に表示し、そこでチャットを開けるようにします</string>
<string name="setup_agent_pet_allow">許可</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">DeeDee とチャット</string>
<string name="library_display">表示</string>
<string name="library_display_larger">大きいカード</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">아직 변경된 내용 없음</string>
<string name="agent_plan_go_message">계획대로 진행해 주세요.</string>
<string name="agent_send_now">지금 보내기</string>
<string name="agent_message">메시지</string>
<string name="agent_more">더보기</string>
<string name="agent_close">닫기</string>
<string name="agent_latest">최신</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">다른 앱 위에 표시</string>
<string name="setup_agent_pet_float_hint">DeeDee가 모든 앱 위에 표시되도록 허용하고 해당 앱에서 채팅을 열 수 있게 합니다.</string>
<string name="setup_agent_pet_allow">허용</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">DeeDee와 채팅하기</string>
<string name="library_display">표시</string>
<string name="library_display_larger">카드 크게</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">Belum ada perubahan</string>
<string name="agent_plan_go_message">Teruskan dengan pelan ini.</string>
<string name="agent_send_now">Hantar sekarang</string>
<string name="agent_message">Mesej</string>
<string name="agent_more">Lagi</string>
<string name="agent_close">Tutup</string>
<string name="agent_latest">Terkini</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">Di atas apl lain</string>
<string name="setup_agent_pet_float_hint">Benarkan DeeDee terapung di atas setiap apl dan buka sembangnya di situ</string>
<string name="setup_agent_pet_allow">Benarkan</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Sembang dengan DeeDee</string>
<string name="library_display">Paparan</string>
<string name="library_display_larger">Kad lebih besar</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Ingen endringer ennå</string>
<string name="agent_plan_go_message">Gå videre med planen.</string>
<string name="agent_send_now">Send nå</string>
<string name="agent_message">Melding</string>
<string name="agent_more">Mer</string>
<string name="agent_close">Lukk</string>
<string name="agent_latest">Nyeste</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Over andre apper</string>
<string name="setup_agent_pet_float_hint">La DeeDee flyte over alle apper og åpne chatten sin der</string>
<string name="setup_agent_pet_allow">Tillat</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat med DeeDee</string>
<string name="library_display">Visning</string>
<string name="library_display_larger">Større kort</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Nog niets gewijzigd</string>
<string name="agent_plan_go_message">Ga door met het plan.</string>
<string name="agent_send_now">Nu verzenden</string>
<string name="agent_message">Bericht</string>
<string name="agent_more">Meer</string>
<string name="agent_close">Sluiten</string>
<string name="agent_latest">Nieuwste</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Boven andere apps</string>
<string name="setup_agent_pet_float_hint">Laat DeeDee boven elke app zweven en open daar de chat</string>
<string name="setup_agent_pet_allow">Toestaan</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chatten met DeeDee</string>
<string name="library_display">Weergave</string>
<string name="library_display_larger">Grotere kaarten</string>
+2
View File
@@ -1173,6 +1173,7 @@
<string name="agent_plan_untouched">Nic jeszcze nie zmieniono</string>
<string name="agent_plan_go_message">Wykonaj plan.</string>
<string name="agent_send_now">Wyślij teraz</string>
<string name="agent_message">Wiadomość</string>
<string name="agent_more">Więcej</string>
<string name="agent_close">Zamknij</string>
<string name="agent_latest">Najnowsze</string>
@@ -2630,6 +2631,7 @@
<string name="setup_agent_pet_float">Nad innymi aplikacjami</string>
<string name="setup_agent_pet_float_hint">Pozwól DeeDee wyświetlać się nad każdą aplikacją i otwierać tam jej czat</string>
<string name="setup_agent_pet_allow">Zezwól</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Czat z DeeDee</string>
<string name="library_display">Wyświetlanie</string>
<string name="library_display_larger">Większe karty</string>
@@ -1162,6 +1162,7 @@
<string name="agent_plan_untouched">Ainda nada mudou</string>
<string name="agent_plan_go_message">Avançar com o plano.</string>
<string name="agent_send_now">Enviar agora</string>
<string name="agent_message">Mensagem</string>
<string name="agent_more">Mais</string>
<string name="agent_close">Fechar</string>
<string name="agent_latest">Mais recente</string>
@@ -2595,6 +2596,7 @@
<string name="setup_agent_pet_float">Sobre outras aplicações</string>
<string name="setup_agent_pet_float_hint">Permitir que a DeeDee flutue sobre todas as aplicações e abra aí a conversa</string>
<string name="setup_agent_pet_allow">Permitir</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Conversar com a DeeDee</string>
<string name="library_display">Apresentação</string>
<string name="library_display_larger">Cartões maiores</string>
+2
View File
@@ -1162,6 +1162,7 @@
<string name="agent_plan_untouched">Nada mudou ainda</string>
<string name="agent_plan_go_message">Siga em frente com o plano.</string>
<string name="agent_send_now">Enviar agora</string>
<string name="agent_message">Mensagem</string>
<string name="agent_more">Mais</string>
<string name="agent_close">Fechar</string>
<string name="agent_latest">Mais recente</string>
@@ -2596,6 +2597,7 @@
<string name="setup_agent_pet_float">Sobre outros apps</string>
<string name="setup_agent_pet_float_hint">Permita que DeeDee flutue sobre todos os apps e abra o chat dela ali</string>
<string name="setup_agent_pet_allow">Permitir</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Conversar com DeeDee</string>
<string name="library_display">Exibição</string>
<string name="library_display_larger">Cards maiores</string>
+2
View File
@@ -1170,6 +1170,7 @@
<string name="agent_plan_untouched">Nimic nu s-a schimbat încă</string>
<string name="agent_plan_go_message">Continuă cu planul.</string>
<string name="agent_send_now">Trimite acum</string>
<string name="agent_message">Mesaj</string>
<string name="agent_more">Mai multe</string>
<string name="agent_close">Închide</string>
<string name="agent_latest">Cele mai recente</string>
@@ -2604,6 +2605,7 @@
<string name="setup_agent_pet_float">Peste alte aplicații</string>
<string name="setup_agent_pet_float_hint">Permite ca DeeDee să plutească peste orice aplicație și să deschidă chatul acolo</string>
<string name="setup_agent_pet_allow">Permite</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Discută cu DeeDee</string>
<string name="library_display">Afișare</string>
<string name="library_display_larger">Carduri mai mari</string>
+2
View File
@@ -1173,6 +1173,7 @@
<string name="agent_plan_untouched">Изменений пока нет</string>
<string name="agent_plan_go_message">Действуйте по плану.</string>
<string name="agent_send_now">Отправить сейчас</string>
<string name="agent_message">Сообщение</string>
<string name="agent_more">Ещё</string>
<string name="agent_close">Закрыть</string>
<string name="agent_latest">Последняя версия</string>
@@ -2630,6 +2631,7 @@
<string name="setup_agent_pet_float">Поверх других приложений</string>
<string name="setup_agent_pet_float_hint">Разрешить DeeDee отображаться поверх всех приложений и открывать там чат с DeeDee</string>
<string name="setup_agent_pet_allow">Разрешить</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Чат с DeeDee</string>
<string name="library_display">Вид</string>
<string name="library_display_larger">Крупные карточки</string>
+2
View File
@@ -1167,6 +1167,7 @@
<string name="agent_plan_untouched">Inget har ändrats ännu</string>
<string name="agent_plan_go_message">Kör planen.</string>
<string name="agent_send_now">Skicka nu</string>
<string name="agent_message">Meddelande</string>
<string name="agent_more">Mer</string>
<string name="agent_close">Stäng</string>
<string name="agent_latest">Senaste</string>
@@ -2578,6 +2579,7 @@
<string name="setup_agent_pet_float">Över andra appar</string>
<string name="setup_agent_pet_float_hint">Låt DeeDee sväva över alla appar och öppna chatten där</string>
<string name="setup_agent_pet_allow">Tillåt</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chatta med DeeDee</string>
<string name="library_display">Visning</string>
<string name="library_display_larger">Större kort</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">ยังไม่มีการเปลี่ยนแปลง</string>
<string name="agent_plan_go_message">ดำเนินการตามแผนได้เลย</string>
<string name="agent_send_now">ส่งตอนนี้</string>
<string name="agent_message">ข้อความ</string>
<string name="agent_more">เพิ่มเติม</string>
<string name="agent_close">ปิด</string>
<string name="agent_latest">ล่าสุด</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">เหนือแอปอื่น</string>
<string name="setup_agent_pet_float_hint">ให้ DeeDee ลอยเหนือทุกแอปและเปิดแชทได้จากตรงนั้น</string>
<string name="setup_agent_pet_allow">อนุญาต</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">แชทกับ DeeDee</string>
<string name="library_display">การแสดงผล</string>
<string name="library_display_larger">การ์ดใหญ่ขึ้น</string>
+2
View File
@@ -1159,6 +1159,7 @@
<string name="agent_plan_untouched">Henüz bir şey değişmedi</string>
<string name="agent_plan_go_message">Planla devam et.</string>
<string name="agent_send_now">Şimdi gönder</string>
<string name="agent_message">Mesaj</string>
<string name="agent_more">Diğer</string>
<string name="agent_close">Kapat</string>
<string name="agent_latest">En son</string>
@@ -2570,6 +2571,7 @@
<string name="setup_agent_pet_float">Diğer uygulamaların üzerinde</string>
<string name="setup_agent_pet_float_hint">DeeDee\'nin her uygulamanın üzerinde görünmesine ve sohbetini orada açmasına izin ver</string>
<string name="setup_agent_pet_allow">İzin ver</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">DeeDee ile sohbet et</string>
<string name="library_display">Görünüm</string>
<string name="library_display_larger">Daha büyük kartlar</string>
+2
View File
@@ -1173,6 +1173,7 @@
<string name="agent_plan_untouched">Поки нічого не змінено</string>
<string name="agent_plan_go_message">Виконайте план.</string>
<string name="agent_send_now">Надіслати зараз</string>
<string name="agent_message">Повідомлення</string>
<string name="agent_more">Ще</string>
<string name="agent_close">Закрити</string>
<string name="agent_latest">Найновіше</string>
@@ -2630,6 +2631,7 @@
<string name="setup_agent_pet_float">Поверх інших застосунків</string>
<string name="setup_agent_pet_float_hint">Дозволити DeeDee відображатися поверх усіх застосунків і відкривати там чат</string>
<string name="setup_agent_pet_allow">Дозволити</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Чат з DeeDee</string>
<string name="library_display">Вигляд</string>
<string name="library_display_larger">Великі картки</string>
+2
View File
@@ -1164,6 +1164,7 @@
<string name="agent_plan_untouched">Chưa có thay đổi nào</string>
<string name="agent_plan_go_message">Hãy tiến hành kế hoạch.</string>
<string name="agent_send_now">Gửi ngay</string>
<string name="agent_message">Tin nhắn</string>
<string name="agent_more">Khác</string>
<string name="agent_close">Đóng</string>
<string name="agent_latest">Mới nhất</string>
@@ -2553,6 +2554,7 @@
<string name="setup_agent_pet_float">Trên các ứng dụng khác</string>
<string name="setup_agent_pet_float_hint">Cho DeeDee nổi trên mọi ứng dụng và mở khung trò chuyện của DeeDee ngay tại đó</string>
<string name="setup_agent_pet_allow">Cho phép</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Trò chuyện với DeeDee</string>
<string name="library_display">Hiển thị</string>
<string name="library_display_larger">Thẻ lớn hơn</string>
@@ -1247,6 +1247,7 @@
<string name="agent_plan_untouched">尚未更改</string>
<string name="agent_plan_go_message">按计划执行。</string>
<string name="agent_send_now">立即发送</string>
<string name="agent_message">消息</string>
<string name="agent_more">更多</string>
<string name="agent_close">关闭</string>
<string name="agent_latest">最新</string>
@@ -2630,6 +2631,7 @@
<string name="setup_agent_pet_float">显示在其他应用上层</string>
<string name="setup_agent_pet_float_hint">让 DeeDee 悬浮在所有应用上层,并在那里打开聊天</string>
<string name="setup_agent_pet_allow">允许</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">与 DeeDee 聊天</string>
<string name="library_display">显示</string>
<string name="library_display_larger">较大卡片</string>
@@ -1163,6 +1163,7 @@
<string name="agent_plan_untouched">尚未有任何更改</string>
<string name="agent_plan_go_message">按計劃執行。</string>
<string name="agent_send_now">立即傳送</string>
<string name="agent_message">訊息</string>
<string name="agent_more">更多</string>
<string name="agent_close">關閉</string>
<string name="agent_latest">最新</string>
@@ -2550,6 +2551,7 @@
<string name="setup_agent_pet_float">浮動於其他應用程式之上</string>
<string name="setup_agent_pet_float_hint">讓 DeeDee 浮動於所有應用程式之上,並可在該處開啟對話</string>
<string name="setup_agent_pet_allow">允許</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">與 DeeDee 對話</string>
<string name="library_display">顯示</string>
<string name="library_display_larger">較大卡片</string>
@@ -1163,6 +1163,7 @@
<string name="agent_plan_untouched">尚未變更</string>
<string name="agent_plan_go_message">按計畫執行。</string>
<string name="agent_send_now">立即傳送</string>
<string name="agent_message">訊息</string>
<string name="agent_more">更多</string>
<string name="agent_close">關閉</string>
<string name="agent_latest">最新</string>
@@ -2550,6 +2551,7 @@
<string name="setup_agent_pet_float">顯示在其他應用程式上層</string>
<string name="setup_agent_pet_float_hint">讓 DeeDee 浮動顯示在所有應用程式上方,並在該處開啟與 DeeDee 的聊天視窗</string>
<string name="setup_agent_pet_allow">允許</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">與 DeeDee 聊天</string>
<string name="library_display">顯示</string>
<string name="library_display_larger">較大的卡片</string>
+2 -31
View File
@@ -1182,37 +1182,6 @@
<string name="rail_agent">Agent</string>
<string name="agent_channel_name">Agent</string>
<string name="agent_working">Agent is working</string>
<string name="agent_drawer_inline">Compact chat in the session drawer</string>
<string name="agent_drawer_inline_hint">The model, usage and menu share the message row, leaving more room for the conversation</string>
<string name="agent_tools">MCP servers and skills</string>
<string name="agent_tools_servers">MCP servers</string>
<string name="agent_tools_skills">Skills in ~/.claude/skills</string>
<string name="agent_tools_loading">Asking Claude Code…</string>
<string name="agent_tools_failed">Claude Code could not do that</string>
<string name="agent_tools_no_servers">No MCP servers yet</string>
<string name="agent_tools_no_skills">No skills yet</string>
<string name="agent_tools_remove">Remove</string>
<string name="agent_tools_name">Name</string>
<string name="agent_tools_target">URL, or the command that starts it</string>
<string name="agent_tools_add_hint">Added for every project</string>
<string name="agent_tools_add">Add</string>
<string name="agent_voice">Dictate</string>
<string name="agent_voice_stop">Stop dictating</string>
<string name="agent_voice_denied">DroidDeck needs the microphone to dictate</string>
<string name="agent_attach_game">Attach what the game shows</string>
<string name="agent_attach_game_failed">Could not capture the game</string>
<string name="agent_done_channel">Agent replies</string>
<string name="agent_done">Agent finished</string>
<string name="agent_done_failed">Agent stopped with an error</string>
<string name="agent_done_question">Agent has a question</string>
<plurals name="agent_subagent_steps">
<item quantity="one">%d step</item>
<item quantity="other">%d steps</item>
</plurals>
<string name="agent_copy">Copy</string>
<string name="agent_copy_reply">Copy the reply</string>
<string name="agent_history_search">Search conversations</string>
<string name="agent_history_no_match">No conversation mentions that</string>
<string name="agent_missing">Install Claude Code in the Linux userland to use the agent.</string>
<string name="agent_hint">Ask about a game, a crash, or a change to DroidDeck</string>
<string name="agent_send">Send</string>
@@ -1260,6 +1229,7 @@
<string name="agent_plan_untouched">Nothing changed yet</string>
<string name="agent_plan_go_message">Go ahead with the plan.</string>
<string name="agent_send_now">Send now</string>
<string name="agent_message">Message</string>
<string name="agent_more">More</string>
<string name="agent_close">Close</string>
<string name="agent_latest">Latest</string>
@@ -2755,6 +2725,7 @@
<string name="setup_agent_pet_float">Over other apps</string>
<string name="setup_agent_pet_float_hint">Let DeeDee float over every app and open its chat there</string>
<string name="setup_agent_pet_allow">Allow</string>
<string name="agent_pet_name">DeeDee</string>
<string name="agent_pet_open">Chat with DeeDee</string>
<string name="library_display">Display</string>
<string name="library_display_larger">Larger cards</string>
@@ -1,68 +0,0 @@
package com.droiddeck.launcher.agent
import org.junit.Assert.assertEquals
import org.junit.Test
class AgentChoicesTest {
@Test fun aTrailingChoicesBlockBecomesOptions() {
val reply = choices("Which build?\n\n```choices\n- Debug\n- Release\n```\n")
assertEquals("Which build?", reply.text)
assertEquals(listOf("Debug", "Release"), reply.options)
}
@Test fun plainLinesAreOptionsToo() {
assertEquals(listOf("Yes", "No"), choices("Go on?\n```choices\nYes\nNo\n```").options)
}
@Test fun aReplyWithoutTheBlockStaysWhole() {
val text = "Done.\n```kotlin\nval a = 1\n```"
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun aChoicesBlockFollowedByAnotherFenceIsNotAQuestion() {
val text = "```choices\nA\nB\n```\nExplanation.\n```kotlin\nval x = 1\n```"
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun aChoicesBlockFollowedByTextIsNotAQuestion() {
val text = "```choices\nA\nB\n```\nMore after it."
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun backticksInsideAChoiceAreKept() {
val reply = choices("How?\n```choices\nUse ``` for code\nUse indentation\n```")
assertEquals("How?", reply.text)
assertEquals(listOf("Use ``` for code", "Use indentation"), reply.options)
}
@Test fun aLongerOpenerNeedsAClosingFenceAsLong() {
val reply = choices("````choices\nA\n```\nB\n````")
assertEquals(listOf("A", "```", "B"), reply.options)
}
@Test fun aChoicesExampleInsideACodeBlockStaysLiteral() {
val text = "Example:\n````markdown\n```choices\nA\nB\n````"
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun anUnclosedChoicesBlockIsNotAQuestion() {
val text = "Pick:\n```choices\nA\nB"
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun aChoicesExampleInsideAnUnclosedTildeFenceStaysLiteral() {
val text = "Example:\n~~~markdown\n```choices\nA\nB\n```"
assertEquals(Choices(text, emptyList()), choices(text))
}
@Test fun aChoicesBlockAfterAClosedTildeFenceCounts() {
val reply = choices("~~~\ncode\n~~~\nPick:\n```choices\nA\nB\n```")
assertEquals(listOf("A", "B"), reply.options)
}
@Test fun aTildeChoicesBlockBecomesOptions() {
val reply = choices("Pick:\n~~~choices\nYes\nNo\n~~~")
assertEquals("Pick:", reply.text)
assertEquals(listOf("Yes", "No"), reply.options)
}
}
@@ -32,22 +32,6 @@ class AgentHostTest {
assertEquals(105L, event.context)
}
@Test fun aSubagentShowsOnlyItsToolCallsUnderItsParent() {
val event = ClaudeCode.parse(
"""{"type":"assistant","session_id":"abc","parent_tool_use_id":"task1","message":{"content":[
{"type":"text","text":"I will look."},
{"type":"tool_use","id":"t2","name":"Grep","input":{"pattern":"crash"}}],"usage":{"input_tokens":10,"output_tokens":5}}}""",
)!!
assertEquals(listOf(Entry.Used("t2", "Grep", "crash", "{\n \"pattern\": \"crash\"\n}", parent = "task1")), event.entries)
assertNull(event.context)
assertNull(ClaudeCode.parse("""{"type":"stream_event","parent_tool_use_id":"task1","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"x"}}}"""))
}
@Test fun aParentlessMessageReadsTheNullAsNoParent() {
val event = ClaudeCode.parse("""{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"text","text":"hi"}]}}""")!!
assertEquals(listOf(Entry.Said("hi")), event.entries)
}
@Test fun claudeStreamsTextAsItIsWritten() {
val event = ClaudeCode.parse("""{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}}""")!!
assertEquals("Hel", event.text)
@@ -1,53 +0,0 @@
package com.droiddeck.launcher.agent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.nio.file.Files
class AgentToolsTest {
@Test fun serversAreReadFromTheListOutput() {
val output = "Checking MCP server health…\n\nclaude.ai Claude Docs: https://api.anthropic.com/v1/pages/mcp - ✔ Connected\n" +
"files: npx -y @modelcontextprotocol/server-filesystem /root - ✗ Failed to connect\n"
val servers = AgentTools.parseServers(output)
assertEquals(listOf("claude.ai Claude Docs", "files"), servers.map { it.name })
assertEquals("npx -y @modelcontextprotocol/server-filesystem /root", servers[1].target)
assertTrue(servers[0].account)
}
@Test fun aUrlIsAddedOverHttpAndACommandOverStdio() {
assertEquals(listOf("mcp", "add", "--scope", "user", "--transport", "http", "sentry", "https://mcp.sentry.dev/mcp"),
AgentTools.addCommand("sentry", " https://mcp.sentry.dev/mcp ").drop(1))
assertEquals(listOf("mcp", "add", "--scope", "user", "files", "--", "npx", "-y", "server", "/root"),
AgentTools.addCommand("files", "npx -y server /root").drop(1))
}
@Test fun aCommandKeepsItsQuotedArguments() {
assertEquals(listOf("python", "/root/My Tools/server.py", "--name", "it's", "a b"),
AgentTools.words("""python "/root/My Tools/server.py" --name "it's" a\ b"""))
assertEquals(listOf("sh", "-c", "echo \"hi\""), AgentTools.words("""sh -c 'echo "hi"'"""))
}
@Test fun deletingASkillLeavesWhatItsLinksPointTo() {
val outside = Files.createTempDirectory("outside").toFile()
File(outside, "keep.txt").writeText("keep")
val skill = Files.createTempDirectory("skill").toFile()
File(skill, "SKILL.md").writeText("x")
Files.createSymbolicLink(File(skill, "resources").toPath(), outside.toPath())
assertTrue(AgentTools.deleteTree(skill.toPath()))
assertTrue(!skill.exists())
assertTrue(File(outside, "keep.txt").isFile)
outside.deleteRecursively()
}
@Test fun aSkillsDescriptionComesFromItsFrontMatter() {
val file = Files.createTempFile("skill", ".md").toFile()
file.writeText("---\nname: deploy\ndescription: \"Ship the build\"\n---\nBody\n")
assertEquals("Ship the build", AgentTools.description(file))
file.writeText("No front matter\ndescription: nope\n")
assertEquals("", AgentTools.description(file))
file.delete()
assertEquals("", AgentTools.description(File(file.path)))
}
}
@@ -38,9 +38,4 @@ class AgentChangesTest {
assertEquals("1.5M", tokens(1_500_000))
assertEquals("23k", tokens(23_400))
}
@Test fun aTurnsReplyIsEverythingItSaid() {
val turn = listOf(Entry.Said("One."), Entry.Used("e1", "Bash", "ls"), Entry.Said("Two."))
assertEquals("One.\n\nTwo.", turnReply(turn))
}
}
+2 -8
View File
@@ -122,16 +122,11 @@ What it does, per feature:
- The source must be memory the application has mapped; DXVK's staging memory is.
- Decoded texels go through the layer's own staging buffers, recycled when the command buffer is reset.
- Copies from a BC image into a buffer, and between BC and uncompressed images, are skipped with a warning.
- `dualSrcBlend`: reports maxFragmentDualSrcAttachments 1. DXVK 2.x and 3.x require it for D3D11.
- Fragment outputs with `Index 1` become Private, in shader modules and in inline stage code.
- SRC1 blend factors become source alpha: `SRC1_COLOR` and `SRC1_ALPHA` → `SRC_ALPHA`, their `ONE_MINUS_` forms → `ONE_MINUS_SRC_ALPHA`.
- Pipelines and `vkCmdSetColorBlendEquationEXT` both.
- Why alpha: output 0's color is the paint, its alpha is the usual coverage. Per-channel coverage collapses to one value; blending stays plain alpha blending, not tinted by the paint.
Files:
- `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table.
- `pipeline.c`: pipelines, shader modules, viewports.
- `spirv.c`: the SPIR-V rewriter for clip and cull distances and the second blend source.
- `spirv.c`: the SPIR-V rewriter for clip and cull distances.
- `bc.c`: BC formats, images and uploads.
- `VkLayer_droiddeck_mali_compat.json`: implicit layer manifest.
@@ -147,8 +142,7 @@ How it ships:
- Guest paths: `usr/local/lib/droiddeck-mali/` and `usr/local/share/vulkan/implicit_layer.d/`.
Not done yet:
- Unit tests for the clip and cull distance rewriter. It is untested beyond DXVK's shaders, and unknown whether Silksong's shaders used clip distances at all.
- The dual-source rewrite has them: `tools/tests/test_mali_compat_layer.py`.
- Unit tests for the SPIR-V rewriter. It is untested beyond DXVK's shaders, and unknown whether Silksong's shaders used clip distances at all.
- Performance: BC decoding on the CPU makes loads slow. A compute-shader decoder would be the next step.
## Changes on the branch
+48
View File
@@ -0,0 +1,48 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DroidDeck stars milestone</title>
<style>
*{box-sizing:border-box}
html,body{width:100%;height:100%;margin:0;background:#000;color:#fff;font-family:Arial,Helvetica,sans-serif}
body{display:grid;place-items:center;overflow:hidden}
.stage{--unit:min(1vw,1.7777778vh);position:relative;width:calc(100 * var(--unit));aspect-ratio:16/9;overflow:hidden;background:#000;isolation:isolate}
.mark{position:absolute;left:50%;top:31%;width:16%;aspect-ratio:1;transform:translate(-50%,-50%)}
.arc{position:absolute;left:13%;width:74%;height:37%;border:min(calc(1.5 * var(--unit)),22px) solid #fff}
.arc.top{top:0;border-top:0;border-radius:0 0 100px 100px;animation:top 9s cubic-bezier(.2,.7,.2,1) infinite}
.arc.bottom{bottom:0;border-bottom:0;border-radius:100px 100px 0 0;animation:bottom 9s cubic-bezier(.2,.7,.2,1) infinite}
.dot{position:absolute;left:37%;top:37%;width:26%;aspect-ratio:1;border-radius:50%;background:#29a1e9;animation:dot 9s cubic-bezier(.2,.7,.2,1) infinite}
.copy{position:absolute;inset:48% 5% auto;text-align:center;animation:copy 9s ease both infinite}
.name{font-size:min(calc(5.3 * var(--unit)),100px);font-weight:800;letter-spacing:-.055em;line-height:1}
.rule{width:7%;height:3px;margin:2.2% auto;background:#29a1e9;animation:rule 9s ease infinite}
.message{font-size:min(calc(2.15 * var(--unit)),40px);font-weight:700;letter-spacing:.045em;line-height:1.25;text-transform:uppercase}
.message span{color:#29a1e9}
.thanks{margin-top:2%;font-size:min(calc(1.35 * var(--unit)),25px);font-weight:400;letter-spacing:.04em;color:#bfc8d0}
@keyframes top{0%,7%{opacity:0;transform:translateY(-100%) rotate(-90deg)}20%,76%{opacity:1;transform:none}90%,100%{opacity:0;transform:translateY(-70%) rotate(45deg)}}
@keyframes bottom{0%,7%{opacity:0;transform:translateY(100%) rotate(90deg)}20%,76%{opacity:1;transform:none}90%,100%{opacity:0;transform:translateY(70%) rotate(-45deg)}}
@keyframes dot{0%,10%{opacity:0;transform:scale(0)}24%,76%{opacity:1;transform:scale(1)}90%,100%{opacity:0;transform:scale(0)}}
@keyframes copy{0%,22%{opacity:0;transform:translateY(12%)}32%,76%{opacity:1;transform:none}88%,100%{opacity:0;transform:translateY(-5%)}}
@keyframes rule{0%,25%{transform:scaleX(0)}36%,76%{transform:scaleX(1)}88%,100%{transform:scaleX(0)}}
@media (max-width:600px) and (orientation:portrait){
body{display:block;overflow:auto}
.stage{width:100%;min-height:100vh;aspect-ratio:auto;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:32px;padding:32px 20px;overflow:visible}
.mark{position:relative;left:auto;top:auto;width:min(32vw,120px);flex:none;transform:none}
.arc{border-width:clamp(4px,3vw,12px)}
.copy{position:relative;inset:auto;width:100%}
.name{font-size:clamp(32px,10vw,52px)}
.rule{width:40px;margin:18px auto}
.message{font-size:clamp(16px,4.5vw,22px)}
.thanks{margin-top:18px;font-size:16px;line-height:1.4}
}
@media (prefers-reduced-motion:reduce){.arc.top,.arc.bottom,.dot,.copy,.rule{animation:none}}
</style>
</head>
<body>
<main class="stage" aria-label="DroidDeck is the most starred PC gaming app on Android. Thank you to our community.">
<div class="mark" aria-hidden="true"><div class="arc top"></div><div class="dot"></div><div class="arc bottom"></div></div>
<div class="copy"><div class="name">DroidDeck</div><div class="rule"></div><div class="message">The <span>most starred</span> PC gaming<br>app on Android</div><div class="thanks">Thank you to our community.</div></div>
</main>
</body>
</html>
@@ -361,36 +361,6 @@ def engine_fixes(exe, args):
return env, extra, notes
DS_APP_IDS = {"1190460", "1850570"}
DS_SIZE = 86479872
DS_WINDOW_OFFSET = 0x38FE190
DS_WINDOW = bytes.fromhex("48895c240848896c2410488974241848897c242041564883ec70458bf1498bf0488bfa488be94885c9")
DS_ORIGINAL = bytes.fromhex("0f85a5000000")
DS_FIXED = bytes.fromhex("e9a600000090")
def death_stranding_allocator(app_id, exe):
# The game's bundled mimalloc tries one random address between 4 and 8 TiB and never falls back,
# but a 39-bit kernel cannot map anything above 512 GiB. Jumping straight to its aligned path avoids it.
if app_id not in DS_APP_IDS or os.path.basename(exe).lower() != "ds.exe":
return False
try:
with open(exe, "r+b") as game:
if os.fstat(game.fileno()).st_size != DS_SIZE:
return False
game.seek(DS_WINDOW_OFFSET)
seen = game.read(len(DS_WINDOW) + len(DS_ORIGINAL))
if seen[:len(DS_WINDOW)] != DS_WINDOW or seen[len(DS_WINDOW):] != DS_ORIGINAL:
return False
game.seek(DS_WINDOW_OFFSET + len(DS_WINDOW))
game.write(DS_FIXED)
except OSError as error:
print("droiddeck-game-env: Death Stranding allocator fix not applied (%s)" % error, file=sys.stderr)
return False
print("droiddeck-game-env: Death Stranding: memory allocator no longer needs a high address (39-bit kernels)", file=sys.stderr)
return True
def win_components(compat, app_id, proton=None, env=None):
if not compat:
return ""
@@ -927,55 +897,6 @@ PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
pe_machine = PE["pe_machine"]
def newest_foreign_backup(path):
newest = None
backup = path.with_name(path.name + FOREIGN_SUFFIX)
serial = 1
while os.path.lexists(backup):
newest = backup
backup = path.with_name(path.name + FOREIGN_SUFFIX + ".%d" % serial)
serial += 1
return newest
def restore_x64_guest_dlls(prefix, proton, env=None):
machines_by_folder = PE["proton_pe_machines"](proton, env or {})
if machines_by_folder is None or 0xA641 not in machines_by_folder["system32"][1]:
return []
builtins = Path(proton).parent / "files/lib/wine" / machines_by_folder["system32"][0]
system32 = Path(prefix) / "pfx/drive_c/windows/system32"
try:
names = sorted(name for name in os.listdir(system32) if name.lower().endswith(".dll"))
except OSError:
return []
present, restorable = [], {}
for name in names:
path = system32 / name
if not path.is_symlink():
if pe_machine(path) == 0x8664 and not PE["pe_has_arm64ec_metadata"](path):
present.append(name)
continue
if not os.path.realpath(path).startswith(os.path.realpath(builtins) + os.sep):
continue
backup = newest_foreign_backup(path)
if backup and backup.is_file() and not backup.is_symlink() and pe_machine(backup) == 0x8664 \
and not PE["pe_has_arm64ec_metadata"](backup):
restorable[name] = backup
if not restorable:
return []
guests = PE["x64_guests"](builtins, present + list(restorable))
restored = []
for name, backup in sorted(restorable.items()):
if name.lower() not in guests:
continue
try:
os.replace(backup, system32 / name)
except OSError:
continue
restored.append("system32/" + name)
return restored
def repair_foreign_system_dlls(prefix, proton, env=None):
dist = Path(proton).parent / "files/lib/wine"
windows = Path(prefix) / "pfx/drive_c/windows"
@@ -993,10 +914,6 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
names = sorted(os.listdir(windows / folder))
except OSError:
continue
candidates = [name for name in names if name.lower().endswith(".dll") and not (windows / folder / name).is_symlink()
and pe_machine(windows / folder / name) == 0x8664
and not PE["pe_has_arm64ec_metadata"](windows / folder / name)]
guests = PE["x64_guests"](builtins, candidates) if candidates and 0xA641 in machines else frozenset()
for name in names:
path = windows / folder / name
builtin_name = builtin_names.get(name.lower())
@@ -1004,7 +921,7 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
if path.is_symlink() or not name.lower().endswith(".dll") or not source.is_file() or not path.is_file():
continue
machine = pe_machine(path)
if machine is None or PE["machine_compatible"](path, machines, machine, guests):
if machine is None or PE["machine_compatible"](path, machines, machine):
continue
link = windows / folder / (name + ".bl-new")
backup = windows / folder / (name + FOREIGN_SUFFIX)
@@ -1354,14 +1271,6 @@ def main():
if waiting:
components = win_components(prefix_path, app_id, command[0], effective_env)
if prefix_path and command:
try:
restored = restore_x64_guest_dlls(prefix_path, command[0], effective_env)
except OSError as error:
restored = []
print("droiddeck-game-env: prefix x64 DLL restore skipped (%s)" % error, file=sys.stderr)
if restored:
print("droiddeck-game-env: restored x64 system DLLs that only x64 code imports: %s" % ", ".join(restored),
file=sys.stderr)
try:
fixed = repair_foreign_system_dlls(prefix_path, command[0], effective_env)
except OSError as error:
@@ -1391,8 +1300,6 @@ def main():
fixes = {}
if waiting:
command = skip_red_launcher(command)
if len(command) > 2:
death_stranding_allocator(app_id, command[2])
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
@@ -479,49 +479,13 @@ def save_state(compat, state):
os.replace(temp, compat / STATE)
def system_folder(rel):
def foreign_component(rel, path, machines):
parts = Path(rel).parts
return parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None
def foreign_component(rel, path, machines, guests=frozenset()):
folder = system_folder(rel)
folder = parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None
if not machines or folder not in PE_MACHINES or not rel.lower().endswith(".dll"):
return False
machine = pe_machine(path)
return machine is not None and not machine_compatible(path, machines[folder][1], machine, guests, Path(rel).name)
def plain_x64(path):
return pe_machine(path) == 0x8664 and not PE["pe_has_arm64ec_metadata"](path)
def component_guests(compat, proton, machines, planned, owned):
if not machines or 0xA641 not in machines["system32"][1]:
return frozenset()
system32 = compat / "pfx/drive_c/windows/system32"
def top_dll(rel):
return len(Path(rel).parts) == 4 and system_folder(rel) == "system32" and rel.lower().endswith(".dll")
final = {}
for rel, src in planned:
if top_dll(rel) and (plain_x64(src) or machine_compatible(src, machines["system32"][1])):
final[rel.lower()] = (rel, src)
removed = {rel.lower(): rel for rel in owned if rel.lower() not in final and top_dll(rel)}
names = {Path(rel).name for rel, src in final.values() if plain_x64(src)}
replaced = {key for key, (rel, src) in final.items() if not plain_x64(src)}
try:
present = list(os.scandir(system32))
except OSError:
present = []
names.update(entry.name for entry in present if entry.name.lower().endswith(".dll") and not entry.is_symlink()
and ("drive_c/windows/system32/" + entry.name).lower() not in removed
and ("drive_c/windows/system32/" + entry.name).lower() not in replaced and plain_x64(entry.path))
names.update(Path(rel).name for rel in removed.values()
if rel.lower().endswith(".dll") and (compat / BACKUP / rel).is_file() and plain_x64(compat / BACKUP / rel))
if not names:
return frozenset()
return PE["x64_guests"](Path(proton).parent / "files/lib/wine" / machines["system32"][0], names)
return machine is not None and not machine_compatible(path, machines[folder][1], machine)
def pending_for(app_id, pending=PENDING):
@@ -595,13 +559,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
saved_requires = dict(saved_requires, **{cid: loose})
inferred.add(cid)
kept_overrides, kept_requires = {}, {}
expanded = expand(store, ids, saved_requires)
planned = [entry for cid in expanded for entry in (component(store, cid) or ([], [], [], []))[1]]
retained = {cid for cid in expanded if component(store, cid) is None
and (cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners)}
guests = component_guests(compat, proton, machines, planned,
{rel: cid for rel, cid in state["files"].items() if cid not in retained})
for cid in expanded:
for cid in expand(store, ids, saved_requires):
found = component(store, cid)
if found is None:
if cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners:
@@ -627,7 +585,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
foreign = foreign_component(rel, src, machines, guests)
foreign = foreign_component(rel, src, machines)
if foreign:
skipped.add(Path(rel).stem.lower())
changed = False
@@ -648,7 +606,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
if foreign_component(rel, saved, machines, guests):
if foreign_component(rel, saved, machines):
if path is not None and not path.is_symlink():
path.unlink()
continue
@@ -1,5 +1,4 @@
#!/usr/bin/python3
import os
import re
from pathlib import Path
@@ -83,119 +82,9 @@ VC_RUNTIME = re.compile(r"(msvc[pr]\d.*|vcruntime\d.*|vcomp\d*|vcamp\d.*|vccorli
re.IGNORECASE)
def pe_imports(path):
try:
with open(path, "rb") as image:
head = image.read(64)
if head[:2] != b"MZ" or len(head) < 64:
return []
pe_offset = int.from_bytes(head[60:64], "little")
image.seek(pe_offset)
if image.read(4) != b"PE\0\0":
return []
coff = image.read(20)
if len(coff) != 20:
return []
section_count = int.from_bytes(coff[2:4], "little")
optional_size = int.from_bytes(coff[16:18], "little")
if section_count > 96:
return []
optional = image.read(optional_size)
if len(optional) != optional_size or len(optional) < 2:
return []
magic = int.from_bytes(optional[:2], "little")
directories = {0x20B: 112, 0x10B: 96}.get(magic)
if directories is None:
return []
sections = []
for _ in range(section_count):
section = image.read(40)
if len(section) != 40:
return []
sections.append((int.from_bytes(section[12:16], "little"),
max(int.from_bytes(section[8:12], "little"), int.from_bytes(section[16:20], "little")),
int.from_bytes(section[20:24], "little")))
def offset(rva):
for start, size, raw in sections:
if start <= rva < start + size:
return raw + rva - start
return None
def directory(index):
at = directories + index * 8
if len(optional) < at + 8:
return 0
return int.from_bytes(optional[at:at + 4], "little")
def name_at(rva):
at = offset(rva)
if at is None:
return None
image.seek(at)
raw = image.read(256).split(b"\0", 1)[0]
return raw.decode("ascii", "replace").lower() or None
names = []
for index, size, field in ((1, 20, 12), (13, 32, 4)):
at = offset(directory(index)) if directory(index) else None
while at is not None and len(names) < 512:
image.seek(at)
entry = image.read(size)
if len(entry) != size or not any(entry):
break
name = name_at(int.from_bytes(entry[field:field + 4], "little"))
if name:
names.append(name)
at += size
return names
except (OSError, OverflowError, ValueError):
return []
IMPORTERS = {}
def builtin_importers(builtins):
try:
stamp = os.stat(builtins).st_mtime_ns
except OSError:
return {}
cached = IMPORTERS.get(str(builtins))
if cached and cached[0] == stamp:
return cached[1]
importers = {}
try:
entries = list(os.scandir(builtins))
except OSError:
return {}
for entry in entries:
if entry.name.lower().endswith(".dll"):
for name in pe_imports(entry.path):
importers.setdefault(name, set()).add(entry.name.lower())
IMPORTERS[str(builtins)] = (stamp, importers)
return importers
def x64_guests(builtins, names):
importers = builtin_importers(builtins)
guests = {name.lower() for name in names}
changed = True
while changed:
changed = False
for name in sorted(guests):
if not importers.get(name, set()) <= guests:
guests.discard(name)
changed = True
return guests
def machine_compatible(path, machines, machine=None, guests=frozenset(), name=None):
def machine_compatible(path, machines, machine=None):
machine = pe_machine(path) if machine is None else machine
name = name or Path(path).name
if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(name):
return True
if machine == 0x8664 and 0xA641 in machines and name.lower() in guests and not pe_has_arm64ec_metadata(path):
if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(Path(path).name):
return True
if machine == 0x8664 and pe_has_arm64ec_metadata(path):
return 0xA641 in machines
-490
View File
@@ -1,490 +0,0 @@
#include "mali_compat.h"
#include <assert.h>
#include <spirv/unified1/spirv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *interface);
struct object { void *dispatch; };
static int instance_table, device_table;
static struct object mock_instance = {&instance_table};
static struct object mock_lacking = {&instance_table}, mock_capable = {&instance_table};
static struct object mock_device = {&device_table}, mock_command_buffer = {&device_table};
static VkBool32 driver_saw_dual_source;
static uint32_t *driver_code;
static size_t driver_code_count;
static VkPipelineColorBlendAttachmentState driver_attachments[4];
static uint32_t driver_attachment_count;
static VkColorBlendEquationEXT driver_equations[4];
static uint32_t driver_equation_count;
#define MAIN 1
#define VOID 2
#define FUNCTION 3
#define FLOAT 4
#define VEC4 5
#define OUTPUT_VEC4 6
#define COLOR 7
#define SECOND 8
#define ONE 9
#define ONES 10
#define OUTPUT_FLOAT 11
#define UINT 12
#define ZERO 13
#define LABEL 14
#define CHANNEL 15
#define BOUND 16
struct spirv { uint32_t w[256]; size_t n; };
static void op(struct spirv *s, SpvOp code, uint32_t count, const uint32_t *operands)
{
s->w[s->n++] = (count + 1) << 16 | code;
for (uint32_t i = 0; i < count; i++)
s->w[s->n++] = operands[i];
}
#define OP(s, code, ...) \
do { \
const uint32_t operands_[] = {__VA_ARGS__}; \
op(s, code, sizeof(operands_) / sizeof(operands_[0]), operands_); \
} while (0)
static void fragment_shader(struct spirv *s, uint32_t version, bool dual_source)
{
s->n = 0;
const uint32_t header[5] = {SpvMagicNumber, version, 0, BOUND, 0};
memcpy(s->w, header, sizeof(header));
s->n = 5;
OP(s, SpvOpCapability, SpvCapabilityShader);
OP(s, SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450);
OP(s, SpvOpEntryPoint, SpvExecutionModelFragment, MAIN, 0x6e69616d, 0, COLOR, SECOND);
OP(s, SpvOpExecutionMode, MAIN, SpvExecutionModeOriginUpperLeft);
OP(s, SpvOpDecorate, COLOR, SpvDecorationLocation, 0);
if (dual_source) {
OP(s, SpvOpDecorate, COLOR, SpvDecorationIndex, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationIndex, 1);
} else {
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 1);
}
OP(s, SpvOpTypeVoid, VOID);
OP(s, SpvOpTypeFunction, FUNCTION, VOID);
OP(s, SpvOpTypeFloat, FLOAT, 32);
OP(s, SpvOpTypeVector, VEC4, FLOAT, 4);
OP(s, SpvOpTypePointer, OUTPUT_VEC4, SpvStorageClassOutput, VEC4);
OP(s, SpvOpTypePointer, OUTPUT_FLOAT, SpvStorageClassOutput, FLOAT);
OP(s, SpvOpTypeInt, UINT, 32, 0);
OP(s, SpvOpConstant, FLOAT, ONE, 0x3f800000);
OP(s, SpvOpConstantComposite, VEC4, ONES, ONE, ONE, ONE, ONE);
OP(s, SpvOpConstant, UINT, ZERO, 0);
OP(s, SpvOpVariable, OUTPUT_VEC4, COLOR, SpvStorageClassOutput);
OP(s, SpvOpVariable, OUTPUT_VEC4, SECOND, SpvStorageClassOutput);
OP(s, SpvOpFunction, VOID, MAIN, SpvFunctionControlMaskNone, FUNCTION);
OP(s, SpvOpLabel, LABEL);
OP(s, SpvOpStore, COLOR, ONES);
OP(s, SpvOpStore, SECOND, ONES);
OP(s, SpvOpAccessChain, OUTPUT_FLOAT, CHANNEL, SECOND, ZERO);
OP(s, SpvOpStore, CHANNEL, ONE);
s->w[s->n++] = 1u << 16 | SpvOpReturn;
s->w[s->n++] = 1u << 16 | SpvOpFunctionEnd;
}
static const uint32_t *find(const uint32_t *w, size_t count, SpvOp code, uint32_t position, uint32_t value)
{
for (size_t i = 5; i < count; i += w[i] >> 16) {
if ((w[i] & 0xffff) == code && (w[i] >> 16) > position && w[i + position] == value)
return &w[i];
}
return NULL;
}
static uint32_t storage_of(const uint32_t *w, size_t count, uint32_t pointer_type)
{
const uint32_t *type = find(w, count, SpvOpTypePointer, 1, pointer_type);
assert(type);
return type[2];
}
static bool in_interface(const uint32_t *w, size_t count, uint32_t id)
{
const uint32_t *entry = find(w, count, SpvOpEntryPoint, 2, MAIN);
assert(entry);
for (uint32_t i = 5; i < entry[0] >> 16; i++) {
if (entry[i] == id)
return true;
}
return false;
}
static void save(const char *directory, const char *name, const uint32_t *words, size_t count)
{
if (!directory)
return;
char path[512];
snprintf(path, sizeof(path), "%s/%s", directory, name);
FILE *file = fopen(path, "wb");
assert(file);
assert(fwrite(words, sizeof(uint32_t), count, file) == count);
fclose(file);
}
static void check_stripped(const uint32_t *w, size_t count, bool second_listed)
{
assert(!spirv_uses_dual_source(w, count));
const uint32_t *second = find(w, count, SpvOpVariable, 2, SECOND);
const uint32_t *color = find(w, count, SpvOpVariable, 2, COLOR);
assert(second && second[3] == SpvStorageClassPrivate);
assert(storage_of(w, count, second[1]) == SpvStorageClassPrivate);
assert(color && color[3] == SpvStorageClassOutput && color[1] == OUTPUT_VEC4);
assert(!find(w, count, SpvOpDecorate, 1, SECOND));
const uint32_t *location = find(w, count, SpvOpDecorate, 1, COLOR);
assert(location && location[2] == SpvDecorationLocation && location[3] == 0);
const uint32_t *channel = find(w, count, SpvOpAccessChain, 2, CHANNEL);
assert(channel && storage_of(w, count, channel[1]) == SpvStorageClassPrivate);
assert(storage_of(w, count, OUTPUT_FLOAT) == SpvStorageClassOutput);
assert(in_interface(w, count, COLOR));
assert(in_interface(w, count, SECOND) == second_listed);
}
static void test_spirv(const char *directory)
{
struct spirv dual, plain;
struct spirv_code out;
fragment_shader(&dual, 0x00010000, true);
save(directory, "dual-1.0.spv", dual.w, dual.n);
assert(spirv_uses_dual_source(dual.w, dual.n));
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, false);
save(directory, "stripped-1.0.spv", out.words, out.count);
free(out.words);
fragment_shader(&dual, 0x00010400, true);
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, true);
save(directory, "stripped-1.4.spv", out.words, out.count);
free(out.words);
fragment_shader(&plain, 0x00010000, false);
save(directory, "plain-1.0.spv", plain.w, plain.n);
assert(!spirv_uses_dual_source(plain.w, plain.n));
assert(spirv_strip_dual_source(plain.w, plain.n, &out));
assert(out.count == plain.n && !memcmp(out.words, plain.w, plain.n * sizeof(uint32_t)));
free(out.words);
uint32_t truncated[5] = {SpvMagicNumber, 0x00010000, 0, BOUND, 0};
assert(!spirv_uses_dual_source(truncated, 5));
assert(!spirv_strip_dual_source(truncated, 5, &out));
}
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
*instance = (VkInstance)&mock_instance;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_extensions(VkPhysicalDevice physical, const char *layer, uint32_t *count,
VkExtensionProperties *properties)
{
*count = 0;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features)
{
memset(features, 0, sizeof(*features));
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
{
mock_features(physical, &features->features);
}
static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *properties)
{
memset(properties, 0, sizeof(*properties));
strcpy(properties->deviceName, "mock");
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *properties)
{
mock_properties(physical, &properties->properties);
}
static void VKAPI_CALL mock_memory_properties(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties *properties)
{
memset(properties, 0, sizeof(*properties));
}
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out)
{
memset(&out->formatProperties, 0, sizeof(out->formatProperties));
}
static VkResult VKAPI_CALL mock_image_format_properties2(VkPhysicalDevice physical,
const VkPhysicalDeviceImageFormatInfo2 *info,
VkImageFormatProperties2 *properties)
{
return VK_ERROR_FORMAT_NOT_SUPPORTED;
}
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDevice *device)
{
driver_saw_dual_source = info->pEnabledFeatures && info->pEnabledFeatures->dualSrcBlend;
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext) {
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
((const VkPhysicalDeviceFeatures2 *)p)->features.dualSrcBlend)
driver_saw_dual_source = VK_TRUE;
}
VkPhysicalDeviceFeatures supported;
mock_features(physical, &supported);
if (driver_saw_dual_source && !supported.dualSrcBlend)
return VK_ERROR_FEATURE_NOT_PRESENT;
*device = (VkDevice)&mock_device;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
static void capture_code(const uint32_t *words, size_t size)
{
free(driver_code);
driver_code_count = size / sizeof(uint32_t);
driver_code = malloc(size);
memcpy(driver_code, words, size);
}
static VkResult VKAPI_CALL mock_create_shader_module(VkDevice device, const VkShaderModuleCreateInfo *info,
const VkAllocationCallbacks *allocator, VkShaderModule *module)
{
capture_code(info->pCode, info->codeSize);
*module = (VkShaderModule)0x1000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_shader_module(VkDevice device, VkShaderModule module,
const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkGraphicsPipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
const VkPipelineColorBlendStateCreateInfo *blend = infos[0].pColorBlendState;
driver_attachment_count = blend->attachmentCount;
memcpy(driver_attachments, blend->pAttachments, blend->attachmentCount * sizeof(*driver_attachments));
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
capture_code(module->pCode, module->codeSize);
pipelines[0] = (VkPipeline)0x2000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations)
{
for (uint32_t i = 0; i < count; i++)
driver_equations[first + i] = equations[i];
if (first + count > driver_equation_count)
driver_equation_count = first + count;
}
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested)
{
MOCK("vkCreateInstance", mock_create_instance);
MOCK("vkDestroyInstance", mock_destroy_instance);
MOCK("vkCreateDevice", mock_create_device);
MOCK("vkEnumerateDeviceExtensionProperties", mock_extensions);
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
MOCK("vkGetPhysicalDeviceProperties", mock_properties);
MOCK("vkGetPhysicalDeviceProperties2", mock_properties2);
MOCK("vkGetPhysicalDeviceMemoryProperties", mock_memory_properties);
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
MOCK("vkGetPhysicalDeviceImageFormatProperties2", mock_image_format_properties2);
return NULL;
}
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested)
{
MOCK("vkDestroyDevice", mock_destroy_device);
MOCK("vkCreateShaderModule", mock_create_shader_module);
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
return NULL;
}
static PFN_vkGetInstanceProcAddr layer_gipa;
static PFN_vkGetDeviceProcAddr layer_gdpa;
static VkResult create_device(VkPhysicalDevice physical, const void *chain, const VkPhysicalDeviceFeatures *enabled,
VkDevice *device)
{
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
PFN_vkCreateDevice create = (PFN_vkCreateDevice)layer_gipa((VkInstance)&mock_instance, "vkCreateDevice");
return create(physical, &info, NULL, device);
}
static void destroy_device(VkDevice device)
{
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
}
static const VkPipelineColorBlendAttachmentState dual_attachment = {
VK_TRUE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static const VkPipelineColorBlendAttachmentState plain_attachment = {
VK_TRUE, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static void create_pipeline(VkDevice device, VkPipelineColorBlendAttachmentState *attachments,
VkShaderModuleCreateInfo *module)
{
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, module, 0,
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_LOGIC_OP_COPY, 2, attachments, {0}};
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
.pStages = &stage, .pColorBlendState = &blend};
VkPipeline pipeline;
PFN_vkCreateGraphicsPipelines create =
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
assert(stage.pNext == module && blend.pAttachments == attachments);
}
static bool same_attachment(const VkPipelineColorBlendAttachmentState *a, const VkPipelineColorBlendAttachmentState *b)
{
return !memcmp(a, b, sizeof(*a));
}
static void test_lacking_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_lacking;
VkPhysicalDeviceFeatures features;
((PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures"))(physical,
&features);
assert(features.dualSrcBlend);
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
((PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2"))(physical,
&queried);
assert(queried.features.dualSrcBlend);
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && enabled.dualSrcBlend);
destroy_device(device);
VkPhysicalDeviceFeatures2 chained = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, NULL, {.dualSrcBlend = VK_TRUE}};
assert(create_device(physical, &chained, NULL, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && chained.features.dualSrcBlend);
struct spirv dual;
fragment_shader(&dual, 0x00010300, true);
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dual.n * sizeof(uint32_t),
dual.w};
VkShaderModule handle;
assert(((PFN_vkCreateShaderModule)layer_gdpa(device, "vkCreateShaderModule"))(device, &module, NULL, &handle) ==
VK_SUCCESS);
check_stripped(driver_code, driver_code_count, false);
((PFN_vkDestroyShaderModule)layer_gdpa(device, "vkDestroyShaderModule"))(device, handle, NULL);
VkPipelineColorBlendAttachmentState attachments[2] = {dual_attachment, plain_attachment};
create_pipeline(device, attachments, &module);
check_stripped(driver_code, driver_code_count, false);
assert(module.pCode == dual.w && spirv_uses_dual_source(module.pCode, module.codeSize / sizeof(uint32_t)));
assert(driver_attachment_count == 2);
assert(driver_attachments[0].srcColorBlendFactor == VK_BLEND_FACTOR_ONE);
assert(driver_attachments[0].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_attachments[0].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].colorWriteMask == 0xf && driver_attachments[0].blendEnable);
assert(same_attachment(&driver_attachments[1], &plain_attachment));
assert(same_attachment(&attachments[0], &dual_attachment));
VkColorBlendEquationEXT equations[2] = {
{VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD},
{VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_OP_ADD},
};
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
PFN_vkCmdSetColorBlendEquationEXT set_equation =
(PFN_vkCmdSetColorBlendEquationEXT)layer_gdpa(device, "vkCmdSetColorBlendEquationEXT");
assert(set_equation != (PFN_vkCmdSetColorBlendEquationEXT)mock_set_blend_equation);
set_equation(cmd, 1, 2, equations);
assert(driver_equation_count == 3);
assert(driver_equations[1].srcColorBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_equations[1].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_equations[1].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE);
assert(!memcmp(&driver_equations[2], &equations[1], sizeof(equations[1])));
assert(equations[0].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR);
destroy_device(device);
}
static void test_capable_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_capable;
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS && driver_saw_dual_source);
assert(layer_gdpa(device, "vkCreateGraphicsPipelines") == (PFN_vkVoidFunction)mock_create_graphics_pipelines);
assert(layer_gdpa(device, "vkCreateShaderModule") == (PFN_vkVoidFunction)mock_create_shader_module);
assert(layer_gdpa(device, "vkCmdSetColorBlendEquationEXT") == (PFN_vkVoidFunction)mock_set_blend_equation);
destroy_device(device);
}
int main(int argc, char **argv)
{
test_spirv(argc > 1 ? argv[1] : NULL);
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
layer_gipa = negotiate.pfnGetInstanceProcAddr;
layer_gdpa = negotiate.pfnGetDeviceProcAddr;
VkLayerInstanceLink link = {NULL, mock_gipa, NULL};
VkLayerInstanceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO, {&link}};
VkInstanceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &loader};
VkInstance instance;
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
test_lacking_device();
test_capable_device();
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
free(driver_code);
printf("mali compat layer ok\n");
return 0;
}
-214
View File
@@ -33,94 +33,6 @@ class SupergiantDotnetReporterTest(unittest.TestCase):
self.assertIsNone(MODULE["supergiant_dotnet_reporter"](game))
class DeathStrandingAllocatorTest(unittest.TestCase):
def make_exe(self, name="ds.exe", size=None, window=None, tail=None):
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder, True)
path = os.path.join(folder, name)
with open(path, "wb") as game:
game.truncate(MODULE["DS_SIZE"] if size is None else size)
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
game.write(b"<" + (MODULE["DS_WINDOW"] if window is None else window) + (MODULE["DS_ORIGINAL"] if tail is None else tail) + b">")
return path
def read_tail(self, path):
with open(path, "rb") as game:
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
return game.read(len(MODULE["DS_WINDOW"]) + len(MODULE["DS_ORIGINAL"]) + 2)
def run_fix(self, path, app_id="1850570"):
errors = io.StringIO()
with mock.patch("sys.stderr", errors):
return MODULE["death_stranding_allocator"](app_id, path), errors.getvalue()
def test_window_and_patch_have_the_measured_shape(self):
self.assertEqual(41, len(MODULE["DS_WINDOW"]))
self.assertEqual(6, len(MODULE["DS_ORIGINAL"]))
self.assertEqual(6, len(MODULE["DS_FIXED"]))
self.assertEqual(0x38FE1B9, MODULE["DS_WINDOW_OFFSET"] + len(MODULE["DS_WINDOW"]))
def test_replaces_only_the_jump_in_the_original_build(self):
path = self.make_exe()
patched, message = self.run_fix(path)
self.assertTrue(patched)
self.assertIn("Death Stranding", message)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
self.assertEqual(MODULE["DS_SIZE"], os.path.getsize(path))
def test_an_already_patched_game_is_left_alone(self):
path = self.make_exe(tail=MODULE["DS_FIXED"])
before = os.stat(path).st_mtime_ns
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, os.stat(path).st_mtime_ns)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
def test_a_second_run_changes_nothing(self):
path = self.make_exe()
self.assertTrue(self.run_fix(path)[0])
after_first = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(after_first, self.read_tail(path))
def test_other_builds_of_the_game_are_not_touched(self):
for size, window in ((MODULE["DS_SIZE"] + 1, None), (None, bytes(len(MODULE["DS_WINDOW"])))):
path = self.make_exe(size=size, window=window)
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_an_unknown_instruction_at_the_patch_site_is_not_touched(self):
path = self.make_exe(tail=bytes.fromhex("0f85a6000000"))
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_executables_are_ignored(self):
path = self.make_exe(name="game.exe")
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_games_are_not_touched_even_with_a_matching_file(self):
for app_id in ("440", "", None):
path = self.make_exe()
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path, app_id))
self.assertEqual(before, self.read_tail(path))
def test_both_death_stranding_app_ids_are_patched(self):
for app_id in ("1850570", "1190460"):
self.assertTrue(self.run_fix(self.make_exe(), app_id)[0])
def test_the_file_name_check_ignores_case(self):
self.assertTrue(self.run_fix(self.make_exe(name="DS.EXE"))[0])
def test_a_missing_game_file_is_reported_without_raising(self):
patched, message = self.run_fix(os.path.join(tempfile.gettempdir(), "droiddeck-no-such-folder", "ds.exe"))
self.assertFalse(patched)
self.assertIn("not applied", message)
def mapping_of(text):
tokens = COMPAT["tokenize"](text)
return COMPAT["read_mapping"](tokens, COMPAT["mapping_block"](tokens))
@@ -2806,38 +2718,6 @@ def arm64ec_pe_image():
return bytes(image)
def pe_image_importing(machine, imports=(), delayed=()):
image = bytearray(0x600)
image[:2] = b"MZ"
image[60:64] = (64).to_bytes(4, "little")
image[64:68] = b"PE\0\0"
coff = 68
image[coff:coff + 2] = machine.to_bytes(2, "little")
image[coff + 2:coff + 4] = (1).to_bytes(2, "little")
image[coff + 16:coff + 18] = (240).to_bytes(2, "little")
optional = coff + 20
image[optional:optional + 2] = (0x20B).to_bytes(2, "little")
image[optional + 108:optional + 112] = (16).to_bytes(4, "little")
section = optional + 240
image[section + 8:section + 12] = (0x400).to_bytes(4, "little")
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
image[section + 16:section + 20] = (0x400).to_bytes(4, "little")
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
names = 0x1200
for index, size, field, entries in ((1, 20, 12, imports), (13, 32, 4, delayed)):
if not entries:
continue
table = 0x1000 if index == 1 else 0x1100
image[optional + 112 + index * 8:optional + 116 + index * 8] = table.to_bytes(4, "little")
for number, name in enumerate(entries):
entry = 0x200 + table - 0x1000 + number * size
image[entry + field:entry + field + 4] = names.to_bytes(4, "little")
raw = name.encode() + b"\0"
image[0x200 + names - 0x1000:0x200 + names - 0x1000 + len(raw)] = raw
names += len(raw)
return bytes(image)
class ForeignSystemDllTest(unittest.TestCase):
def prefix(self, tmp, arm=True):
proton = Path(tmp) / "Proton"
@@ -2850,8 +2730,6 @@ class ForeignSystemDllTest(unittest.TestCase):
(dist / libdir).mkdir(parents=True)
for name in ("ucrtbase.dll", "rpcrt4.dll"):
(dist / libdir / name).write_bytes(pe_image(machine))
(dist / libdir / "kernel32.dll").write_bytes(
pe_image_importing(machine, ("ucrtbase.dll", "rpcrt4.dll"), ("msvcp_win.dll",)))
windows = Path(tmp) / "compat/pfx/drive_c/windows"
for folder in ("system32", "syswow64"):
(windows / folder).mkdir(parents=True)
@@ -2902,98 +2780,6 @@ class ForeignSystemDllTest(unittest.TestCase):
self.assertFalse((windows / "system32/msvcp140.dll").is_symlink())
self.assertFalse((windows / "system32/VCRUNTIME140.dll").is_symlink())
def test_x64_dlls_only_imported_by_each_other_stay_in_arm64_system32(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64))
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",)))
for name in ("d3dcompiler_43.dll", "D3DX9_43.dll", "ucrtbase.dll"):
(windows / "system32" / name).write_bytes(pe_image(0x8664))
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertEqual([], self.run_repair(compat, proton))
for name in ("d3dcompiler_43.dll", "D3DX9_43.dll"):
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
def test_x64_dlls_replaced_by_an_earlier_build_are_restored_and_core_dlls_are_not(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64))
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",)))
for name in ("d3dcompiler_43.dll", "d3dx9_43.dll", "ucrtbase.dll"):
(windows / "system32" / name).write_bytes(pe_image(0x8664))
for name in ("d3dcompiler_43.dll", "d3dx9_43.dll", "ucrtbase.dll"):
path = windows / "system32" / name
os.replace(path, path.with_name(name + ".foreign-arch"))
os.symlink(os.path.relpath(builtins / name, path.parent), path)
restored = MODULE["restore_x64_guest_dlls"](str(compat), str(proton))
self.assertEqual(["system32/d3dcompiler_43.dll", "system32/d3dx9_43.dll"], restored)
for name in ("d3dcompiler_43.dll", "d3dx9_43.dll"):
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
self.assertTrue((windows / "system32/ucrtbase.dll").is_symlink())
self.assertEqual([], self.run_repair(compat, proton))
self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton)))
def test_restore_leaves_x64_proton_prefixes_and_user_files_alone(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp, arm=False)
(windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0x8664))
(windows / "system32/d3dx9_43.dll.foreign-arch").write_bytes(pe_image(0xAA64))
self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton)))
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32/d3dx9_43.dll"))
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
mine = Path(tmp) / "mine.dll"
mine.write_bytes(pe_image(0xAA64))
os.symlink(mine, windows / "system32/userlib.dll")
(windows / "system32/userlib.dll.foreign-arch").write_bytes(pe_image(0x8664))
self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton)))
self.assertEqual(mine, Path(os.readlink(windows / "system32/userlib.dll")))
def test_x64_dll_imported_by_a_builtin_that_stays_is_replaced(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64))
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",)))
(windows / "system32/d3dcompiler_43.dll").write_bytes(pe_image(0x8664))
(windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0xAA64))
self.assertEqual(["system32/d3dcompiler_43.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertEqual(0xAA64, MODULE["pe_machine"](windows / "system32/d3dcompiler_43.dll"))
def test_arm64ec_importer_does_not_let_an_x64_dependency_stay(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64))
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",)))
(windows / "system32/d3dx9_43.dll").write_bytes(arm64ec_pe_image())
(windows / "system32/d3dcompiler_43.dll").write_bytes(pe_image(0x8664))
self.assertEqual(["system32/d3dcompiler_43.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertFalse((windows / "system32/d3dx9_43.dll").is_symlink())
def test_x64_proton_prefix_ignores_builtin_imports(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp, arm=False)
builtins = proton.parent / "files/lib/wine/x86_64-windows"
builtins.mkdir(parents=True)
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image(0x8664))
(windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0xAA64))
self.assertEqual(["system32/d3dx9_43.dll (machine 0xaa64)"], self.run_repair(compat, proton))
def test_import_tables_and_delay_imports_are_read(self):
with tempfile.TemporaryDirectory() as tmp:
dll = Path(tmp) / "a.dll"
dll.write_bytes(pe_image_importing(0xAA64, ("UCRTBASE.dll", "ntdll.dll"), ("msvcp_win.dll",)))
self.assertEqual(["ucrtbase.dll", "ntdll.dll", "msvcp_win.dll"], MODULE["PE"]["pe_imports"](dll))
dll.write_bytes(pe_image(0x8664))
self.assertEqual([], MODULE["PE"]["pe_imports"](dll))
dll.write_bytes(b"MZ")
self.assertEqual([], MODULE["PE"]["pe_imports"](dll))
def test_final_arm64ec_image_is_not_repaired_as_a_foreign_x64_dll(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
-56
View File
@@ -1,56 +0,0 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
LAYER = ROOT / "tools/venus/layer"
DEPS = ROOT / "build/layer-deps"
def include(variable, default):
return Path(os.environ.get(variable, str(default)))
class MaliCompatLayerTest(unittest.TestCase):
def test_dual_source_blending_against_a_mock_loader_and_driver(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the Mali compatibility layer test")
vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include")
spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include")
bcdec = include("MALI_COMPAT_BCDEC_INCLUDE", DEPS / "bcdec")
missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h",
bcdec / "bcdec.h") if not path.is_file()]
if missing:
message = "Vulkan 1.4, SPIR-V and bcdec headers are required: " + ", ".join(missing)
if os.environ.get("CI"):
self.fail(message)
self.skipTest(message)
with tempfile.TemporaryDirectory(prefix="droiddeck-mali-compat-") as tmp:
program = Path(tmp) / "mali-compat-layer"
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv),
"-I", str(bcdec), str(Path(__file__).with_name("mali_compat_layer_test.c")),
*sorted(str(source) for source in LAYER.glob("*.c")), "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program), tmp], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
self.assertIn("mali compat layer ok", ran.stdout)
self.assertIn("emulating dualSrcBlend for mock", ran.stderr)
validator = shutil.which("spirv-val")
if not validator:
return
for name, environment in (("dual-1.0.spv", "vulkan1.0"), ("plain-1.0.spv", "vulkan1.0"),
("stripped-1.0.spv", "vulkan1.0"), ("stripped-1.4.spv", "vulkan1.2")):
checked = subprocess.run([validator, "--target-env", environment, str(Path(tmp) / name)],
capture_output=True, text=True)
self.assertEqual(checked.returncode, 0, name + ": " + checked.stdout + checked.stderr)
if __name__ == "__main__":
unittest.main()
-129
View File
@@ -9,7 +9,6 @@ from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
MODULE = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
GAME_ENV = runpy.run_path(str(BIN / "droiddeck-game-env"))
pe_image_importing = runpy.run_path(str(Path(__file__).with_name("test_game_environment.py")))["pe_image_importing"]
class WinComponentsTest(unittest.TestCase):
@@ -42,10 +41,6 @@ class WinComponentsTest(unittest.TestCase):
def proton(self, arm=True):
root = Path(self.tmp.name) / ("arm-proton" if arm else "x64-proton")
(root / "files/lib/wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
builtins = root / "files/lib/wine" / ("aarch64-windows" if arm else "x86_64-windows")
builtins.mkdir(parents=True)
builtins.joinpath("kernel32.dll").write_bytes(pe_image_importing(0xAA64 if arm else 0x8664, ("ucrtbase.dll",)))
builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64 if arm else 0x8664, ("d3dcompiler_43.dll",)))
return root / "proton"
def pe_image(self, machine):
@@ -109,130 +104,6 @@ class WinComponentsTest(unittest.TestCase):
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/msvcp140.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140_1.dll"), 0x8664)
def test_x64_d3dx9_and_its_compiler_are_placed_in_arm64_system32(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {
"system32/d3dx9_43.dll": self.pe_image(0x8664),
"syswow64/d3dx9_43.dll": self.pe_image(0x14C),
})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
names, _ = self.apply(proton)
self.assertEqual(names, ["d3dx9_43", "d3dcompiler_43"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
names, _ = self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_deselected_x64_d3dx9_no_longer_keeps_its_compiler(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
self.pick("d3dcompiler")
self.apply(proton)
self.assertFalse((self.pfx / "system32/d3dx9_43.dll").exists())
self.assertNotEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_deselected_component_restores_the_saved_x64_dll(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/d3dx9_43.dll").write_bytes(self.pe_image(0x8664))
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": pe_image_importing(0xAA64)})
self.pick("d3dx9")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0xAA64)
self.pick()
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
def test_arm64_d3dx9_replacing_an_x64_copy_does_not_keep_an_x64_compiler(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/d3dx9_43.dll").write_bytes(self.pe_image(0x8664))
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": pe_image_importing(0xAA64)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0xAA64)
self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists())
def test_rejected_replacement_keeps_the_present_x64_importer(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/d3dx9_43.dll").write_bytes(self.pe_image(0x8664))
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": pe_image_importing(0x14C)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_overwritten_x64_entry_does_not_keep_an_x64_compiler(self):
proton = self.proton()
self.component("a-x64", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("b-arm", ["d3dx9_43"], {"system32/d3dx9_43.dll": pe_image_importing(0xAA64)})
self.component("c-compiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("a-x64", "b-arm", "c-compiler")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0xAA64)
self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists())
def test_rejected_later_entry_does_not_hide_an_accepted_x64_entry(self):
proton = self.proton()
self.component("a-x64", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("b-x86", ["d3dx9_43"], {"system32/d3dx9_43.dll": pe_image_importing(0x14C)})
self.component("c-compiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("a-x64", "b-x86", "c-compiler")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_nested_system32_file_does_not_count_as_an_importer(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {"system32/drivers/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists())
def test_owned_x64_importer_with_a_rejected_new_source_does_not_keep_its_dependency(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
(self.store / "d3dx9/system32/d3dx9_43.dll").write_bytes(pe_image_importing(0x14C))
self.apply(proton)
self.assertFalse((self.pfx / "system32/d3dx9_43.dll").exists())
self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists())
def test_held_component_files_still_count_as_x64_importers(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
self.apply(proton)
for path in sorted((self.store / "d3dx9").rglob("*"), reverse=True):
path.rmdir() if path.is_dir() else path.unlink()
(self.store / "d3dx9").rmdir()
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_x64_compiler_alone_is_skipped_while_the_builtin_d3dx9_imports_it(self):
proton = self.proton()
self.component("d3dcompiler", ["d3dcompiler_43"], {
"system32/d3dcompiler_43.dll": self.pe_image(0x8664),
"syswow64/d3dcompiler_43.dll": self.pe_image(0x14C),
})
self.pick("d3dcompiler")
names, _ = self.apply(proton)
self.assertEqual(names, ["d3dcompiler_43"])
self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists())
def test_compatible_copy_keeps_override_when_other_architecture_copy_is_skipped(self):
proton = self.proton()
self.component("vc", ["ucrtbase"], {
+4 -16
View File
@@ -212,8 +212,6 @@ uint32_t physical_device_gaps(struct instance *inst, VkPhysicalDevice physical_d
gaps |= GAP_ROBUSTNESS2;
if (!features.features.multiDrawIndirect)
gaps |= GAP_MULTI_DRAW;
if (!features.features.dualSrcBlend)
gaps |= GAP_DUAL_SRC_BLEND;
if (!has_extension(inst, physical_device, VK_EXT_DEPTH_CLIP_ENABLE_EXTENSION_NAME))
gaps |= GAP_DEPTH_CLIP;
/* No robustness2 at all: the extension is offered with robustBufferAccess2 (as robustBufferAccess)
@@ -286,8 +284,6 @@ static void report_features(VkPhysicalDeviceFeatures *features, uint32_t gaps)
features->textureCompressionBC = VK_TRUE;
if (gaps & GAP_MULTI_DRAW)
features->multiDrawIndirect = VK_TRUE;
if (gaps & GAP_DUAL_SRC_BLEND)
features->dualSrcBlend = VK_TRUE;
}
/* Which made-up features the application asked for, and off with them before the driver sees them. */
@@ -318,10 +314,6 @@ static uint32_t take_features(VkPhysicalDeviceFeatures *features, uint32_t gaps)
requested |= GAP_MULTI_DRAW;
features->multiDrawIndirect = VK_FALSE;
}
if ((gaps & GAP_DUAL_SRC_BLEND) && features->dualSrcBlend) {
requested |= GAP_DUAL_SRC_BLEND;
features->dualSrcBlend = VK_FALSE;
}
return requested;
}
@@ -331,8 +323,6 @@ static void report_limits(VkPhysicalDeviceLimits *limits, uint32_t gaps)
limits->maxViewports = 16;
if ((gaps & GAP_MULTI_DRAW) && limits->maxDrawIndirectCount < (1u << 30))
limits->maxDrawIndirectCount = 1u << 30;
if ((gaps & GAP_DUAL_SRC_BLEND) && !limits->maxFragmentDualSrcAttachments)
limits->maxFragmentDualSrcAttachments = 1;
if (gaps & GAPS_SHADER) {
limits->maxClipDistances = 8;
limits->maxCullDistances = 8;
@@ -626,7 +616,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
pthread_mutex_unlock(&global_lock);
if (requested) {
layer_log("emulating%s%s%s%s%s%s%s%s%s%s for %s", (requested & GAP_FILL_MODE) ? " fillModeNonSolid" : "",
layer_log("emulating%s%s%s%s%s%s%s%s%s for %s", (requested & GAP_FILL_MODE) ? " fillModeNonSolid" : "",
(requested & GAP_MULTI_VIEWPORT) ? " multiViewport" : "",
(requested & GAP_CLIP_DISTANCE) ? " shaderClipDistance" : "",
(requested & GAP_CULL_DISTANCE) ? " shaderCullDistance" : "",
@@ -634,8 +624,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
(requested & GAP_BC) ? " textureCompressionBC" : "",
(requested & GAP_MULTI_DRAW) ? " multiDrawIndirect" : "",
(requested & GAP_DEPTH_CLIP) ? " depthClipEnable" : "",
(requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "",
(requested & GAP_DUAL_SRC_BLEND) ? " dualSrcBlend" : "", properties.deviceName);
(requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "", properties.deviceName);
}
return VK_SUCCESS;
}
@@ -678,8 +667,8 @@ struct hook {
#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps}
static const struct hook device_hooks[] = {
HOOK(CreateShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND),
HOOK(DestroyShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND),
HOOK(CreateShaderModule, GAPS_SHADER),
HOOK(DestroyShaderModule, GAPS_SHADER),
HOOK(CreateGraphicsPipelines, GAPS_PIPELINE),
HOOK(CmdSetViewport, GAP_MULTI_VIEWPORT),
HOOK(CmdSetScissor, GAP_MULTI_VIEWPORT),
@@ -687,7 +676,6 @@ static const struct hook device_hooks[] = {
HOOK_ALIAS(CmdSetViewportWithCount, CmdSetViewportWithCountEXT, GAP_MULTI_VIEWPORT),
HOOK(CmdSetScissorWithCount, GAP_MULTI_VIEWPORT),
HOOK_ALIAS(CmdSetScissorWithCount, CmdSetScissorWithCountEXT, GAP_MULTI_VIEWPORT),
HOOK(CmdSetColorBlendEquationEXT, GAP_DUAL_SRC_BLEND),
HOOK(CreateImage, GAP_BC),
HOOK(DestroyImage, GAP_BC),
HOOK(CreateImageView, GAP_BC),
+2 -8
View File
@@ -29,11 +29,10 @@ enum gap {
GAP_MULTI_DRAW = 1u << 6, /* multiDrawIndirect: indirect draws looped one by one */
GAP_DEPTH_CLIP = 1u << 7, /* VK_EXT_depth_clip_enable: depthClipEnable off becomes depth clamp */
GAP_NULL_DESCRIPTOR = 1u << 8, /* VK_EXT_robustness2 missing entirely: nullDescriptor stand-ins */
GAP_DUAL_SRC_BLEND = 1u << 9,
};
#define GAPS_SHADER (GAP_CLIP_DISTANCE | GAP_CULL_DISTANCE)
#define GAPS_PIPELINE (GAP_FILL_MODE | GAP_MULTI_VIEWPORT | GAPS_SHADER | GAP_DEPTH_CLIP | GAP_DUAL_SRC_BLEND)
#define GAPS_PIPELINE (GAP_FILL_MODE | GAP_MULTI_VIEWPORT | GAPS_SHADER | GAP_DEPTH_CLIP)
void layer_log(const char *format, ...) __attribute__((format(printf, 1, 2)));
@@ -136,8 +135,7 @@ struct instance {
X(UpdateDescriptorSetWithTemplate) \
X(CmdPushDescriptorSetWithTemplate) \
X(CmdBindVertexBuffers) \
X(CmdBindVertexBuffers2) \
X(CmdSetColorBlendEquationEXT)
X(CmdBindVertexBuffers2)
struct staging_block;
@@ -185,8 +183,6 @@ struct spirv_code {
bool spirv_uses_distances(const uint32_t *words, size_t count);
/* The module with clip and cull distances taken out; false when it cannot be rewritten. */
bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_code *out);
bool spirv_uses_dual_source(const uint32_t *words, size_t count);
bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out);
enum clip_role { CLIP_STRIP, CLIP_PRODUCER, CLIP_CONSUMER };
@@ -220,8 +216,6 @@ VKAPI_ATTR void VKAPI_CALL CmdSetScissor(VkCommandBuffer cmd, uint32_t first, ui
VKAPI_ATTR void VKAPI_CALL CmdSetViewportWithCount(VkCommandBuffer cmd, uint32_t count,
const VkViewport *viewports);
VKAPI_ATTR void VKAPI_CALL CmdSetScissorWithCount(VkCommandBuffer cmd, uint32_t count, const VkRect2D *scissors);
VKAPI_ATTR void VKAPI_CALL CmdSetColorBlendEquationEXT(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations);
/* bc.c */
VkFormat bc_substitute(VkFormat format);
+13 -115
View File
@@ -12,46 +12,27 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateShaderModule(VkDevice device, const VkShade
const VkAllocationCallbacks *allocator, VkShaderModule *module)
{
struct device *dev = device_from_handle(device);
VkShaderModuleCreateInfo copy = *info;
size_t count = info->codeSize / sizeof(uint32_t);
struct spirv_code single = {0};
if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(info->pCode, count)) {
if (spirv_strip_dual_source(info->pCode, count, &single)) {
copy.pCode = single.words;
copy.codeSize = single.count * sizeof(uint32_t);
count = single.count;
} else {
layer_log("could not take the second blend source out of a shader module");
}
}
if (!(dev->emulated & GAPS_SHADER) || !spirv_uses_distances(copy.pCode, count)) {
VkResult result = dev->CreateShaderModule(device, &copy, allocator, module);
free(single.words);
return result;
}
if (!spirv_uses_distances(info->pCode, count))
return dev->CreateShaderModule(device, info, allocator, module);
struct spirv_code stripped;
if (!spirv_strip_distances(copy.pCode, count, &stripped)) {
if (!spirv_strip_distances(info->pCode, count, &stripped)) {
layer_log("could not take the clip and cull distances out of a shader module");
VkResult result = dev->CreateShaderModule(device, &copy, allocator, module);
free(single.words);
return result;
return dev->CreateShaderModule(device, info, allocator, module);
}
struct spirv_code *original = malloc(sizeof(*original));
original->count = count;
original->words = malloc(copy.codeSize);
memcpy(original->words, copy.pCode, copy.codeSize);
free(single.words);
VkShaderModuleCreateInfo copy = *info;
copy.pCode = stripped.words;
copy.codeSize = stripped.count * sizeof(uint32_t);
VkResult result = dev->CreateShaderModule(device, &copy, allocator, module);
free(stripped.words);
if (result != VK_SUCCESS) {
free(original->words);
free(original);
if (result != VK_SUCCESS)
return result;
}
struct spirv_code *original = malloc(sizeof(*original));
original->count = count;
original->words = malloc(info->codeSize);
memcpy(original->words, info->pCode, info->codeSize);
pthread_mutex_lock(&dev->lock);
map_put(&dev->shader_modules, HANDLE(*module), original);
pthread_mutex_unlock(&dev->lock);
@@ -106,15 +87,12 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat
struct pipeline_rewrite {
VkPipelineRasterizationStateCreateInfo rasterization;
VkPipelineColorBlendStateCreateInfo blend;
VkPipelineColorBlendAttachmentState *attachments;
/* VK_EXT_depth_clip_enable's state, taken out of the application's chain for the call. */
VkBaseOutStructure *clip_prev, *clip_node;
VkPipelineViewportStateCreateInfo viewport;
VkPipelineShaderStageCreateInfo stages[MAX_STAGES];
VkShaderModuleCreateInfo modules[MAX_STAGES];
struct spirv_code code[MAX_STAGES];
struct spirv_code single[MAX_STAGES];
VkShaderModule temporary[MAX_STAGES];
/* Rewritten where they are, when they are not first in their stage's chain. */
VkShaderModuleCreateInfo *in_place[MAX_STAGES];
@@ -176,17 +154,8 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in
bool any = false;
for (uint32_t i = 0; i < n; i++) {
find_stage_code(dev, &info->pStages[i], &code[i]);
if ((dev->emulated & GAP_DUAL_SRC_BLEND) && code[i].inline_info &&
spirv_uses_dual_source(code[i].words, code[i].count)) {
if (spirv_strip_dual_source(code[i].words, code[i].count, &rw->single[i])) {
code[i].words = rw->single[i].words;
code[i].count = rw->single[i].count;
} else {
layer_log("could not take the second blend source out of a pipeline's shader");
}
}
uses[i] = (dev->emulated & GAPS_SHADER) && code[i].words && spirv_uses_distances(code[i].words, code[i].count);
any |= uses[i] || rw->single[i].words;
uses[i] = code[i].words && spirv_uses_distances(code[i].words, code[i].count);
any |= uses[i];
}
if (!any)
return;
@@ -227,63 +196,11 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in
!spirv_strip_distances(code[i].words, code[i].count, &rw->code[i])) {
layer_log("could not take the clip and cull distances out of a pipeline's shader");
}
if (!rw->code[i].words && rw->single[i].words) {
rw->code[i] = rw->single[i];
rw->single[i] = (struct spirv_code){0};
}
if (rw->code[i].words)
use_code(dev, info, rw, &code[i], i);
}
}
static bool single_source(VkBlendFactor *factor)
{
switch (*factor) {
case VK_BLEND_FACTOR_SRC1_COLOR:
case VK_BLEND_FACTOR_SRC1_ALPHA:
*factor = VK_BLEND_FACTOR_SRC_ALPHA;
return true;
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR:
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA:
*factor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
return true;
default:
return false;
}
}
static bool single_source_equation(VkBlendFactor *src_color, VkBlendFactor *dst_color, VkBlendFactor *src_alpha,
VkBlendFactor *dst_alpha)
{
bool changed = single_source(src_color);
changed |= single_source(dst_color);
changed |= single_source(src_alpha);
changed |= single_source(dst_alpha);
return changed;
}
static void rewrite_blend(const VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw)
{
const VkPipelineColorBlendStateCreateInfo *blend = info->pColorBlendState;
if (!blend || !blend->pAttachments || !blend->attachmentCount)
return;
rw->attachments = malloc(blend->attachmentCount * sizeof(*rw->attachments));
memcpy(rw->attachments, blend->pAttachments, blend->attachmentCount * sizeof(*rw->attachments));
bool changed = false;
for (uint32_t i = 0; i < blend->attachmentCount; i++) {
VkPipelineColorBlendAttachmentState *a = &rw->attachments[i];
changed |= single_source_equation(&a->srcColorBlendFactor, &a->dstColorBlendFactor, &a->srcAlphaBlendFactor,
&a->dstAlphaBlendFactor);
}
if (!changed) {
free(rw->attachments);
rw->attachments = NULL;
return;
}
rw->blend = *blend;
rw->blend.pAttachments = rw->attachments;
}
static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw)
{
if ((dev->emulated & GAP_FILL_MODE) && info->pRasterizationState &&
@@ -324,12 +241,7 @@ static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *i
rw->viewport.scissorCount = 1;
info->pViewportState = &rw->viewport;
}
if (dev->emulated & GAP_DUAL_SRC_BLEND) {
rewrite_blend(info, rw);
if (rw->attachments)
info->pColorBlendState = &rw->blend;
}
if (dev->emulated & (GAPS_SHADER | GAP_DUAL_SRC_BLEND))
if (dev->emulated & GAPS_SHADER)
rewrite_shaders(dev, info, rw);
}
@@ -345,9 +257,7 @@ static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw)
if (rw->temporary[i] != VK_NULL_HANDLE)
dev->DestroyShaderModule(dev->handle, rw->temporary[i], NULL);
free(rw->code[i].words);
free(rw->single[i].words);
}
free(rw->attachments);
}
VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
@@ -396,15 +306,3 @@ VKAPI_ATTR void VKAPI_CALL CmdSetScissorWithCount(VkCommandBuffer cmd, uint32_t
struct device *dev = device_from_handle(cmd);
dev->CmdSetScissorWithCount(cmd, count > 1 ? 1 : count, scissors);
}
VKAPI_ATTR void VKAPI_CALL CmdSetColorBlendEquationEXT(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations)
{
struct device *dev = device_from_handle(cmd);
for (uint32_t i = 0; i < count; i++) {
VkColorBlendEquationEXT equation = equations[i];
single_source_equation(&equation.srcColorBlendFactor, &equation.dstColorBlendFactor,
&equation.srcAlphaBlendFactor, &equation.dstAlphaBlendFactor);
dev->CmdSetColorBlendEquationEXT(cmd, first + i, 1, &equation);
}
}
+6 -50
View File
@@ -416,19 +416,19 @@ static void add_to_interface(struct module *m, uint32_t id)
}
/* A standalone distance variable becomes Private, and its decorations go. */
static void privatize(struct module *m, uint32_t id)
static void privatize(struct module *m, const struct distance_var *var)
{
size_t d = definition(m, id);
size_t d = definition(m, var->id);
uint32_t storage, pointee;
pointer_parts(m, m->w[d + 1], &storage, &pointee);
m->w[d + 1] = pointer_type(m, SpvStorageClassPrivate, pointee);
m->w[d + 3] = SpvStorageClassPrivate;
mark_private(m, id);
mark_private(m, var->id);
/* Before SPIR-V 1.4 an entry point lists only its inputs and outputs. */
if (m->version < VERSION_1_4)
m->interface_remove[id] = 1;
m->interface_remove[var->id] = 1;
for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) {
if (OPCODE(m->w[i]) == SpvOpDecorate && m->w[i + 1] == id)
if (OPCODE(m->w[i]) == SpvOpDecorate && m->w[i + 1] == var->id)
edit(m, i, INSTEAD);
}
}
@@ -667,7 +667,7 @@ static void strip(struct module *m, const struct analysis *a, uint32_t keep)
{
for (uint32_t i = 0; i < a->var_count; i++) {
if (a->vars[i].id != keep)
privatize(m, a->vars[i].id);
privatize(m, &a->vars[i]);
}
struct stand_in stand_ins[16];
uint32_t count = make_stand_ins(m, a, stand_ins, 16);
@@ -688,50 +688,6 @@ bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_cod
return done;
}
static bool is_second_source(const uint32_t *w)
{
return OPCODE(w[0]) == SpvOpDecorate && LENGTH(w[0]) == 4 && w[2] == SpvDecorationIndex && w[3] == 1;
}
bool spirv_uses_dual_source(const uint32_t *words, size_t count)
{
if (count <= 5 || words[0] != SpvMagicNumber)
return false;
for (size_t i = 5; i < count && LENGTH(words[i]) && i + LENGTH(words[i]) <= count; i += LENGTH(words[i])) {
if (is_declaration(OPCODE(words[i])))
break;
if (is_second_source(&words[i]))
return true;
}
return false;
}
bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out)
{
struct module m;
if (!load(&m, words, count))
return false;
uint32_t outputs[8];
uint32_t output_count = 0;
for (size_t i = 5; i < m.first_declaration; i += LENGTH(m.w[i])) {
if (!is_second_source(&m.w[i]))
continue;
size_t d = definition(&m, m.w[i + 1]);
uint32_t storage, pointee;
if (output_count == 8 || !d || OPCODE(m.w[d]) != SpvOpVariable ||
!pointer_parts(&m, m.w[d + 1], &storage, &pointee) || storage != SpvStorageClassOutput)
m.failed = true;
else
outputs[output_count++] = m.w[i + 1];
}
for (uint32_t i = 0; i < output_count && !m.failed; i++)
privatize(&m, outputs[i]);
retarget_accesses(&m, NULL, 0);
bool done = finish(&m, out);
unload(&m);
return done;
}
static const struct distance_var *clip_output(const struct module *m, const struct analysis *a, uint32_t *length)
{
for (uint32_t i = 0; i < a->var_count; i++) {
+3 -3
View File
@@ -1,3 +1,3 @@
VENUS_REPO=Droid-Deck/DroidDeck-Components
VENUS_TAG=venus-dualsrc-463ba9ef
VENUS_SHA256=ace6f4c3e62db0c7487859d8cebdcdd83656272951f84c00471fafc364ae30af
VENUS_REPO=The412Banner/droiddeck-nonadreno-drivers
VENUS_TAG=venus-proto13-e24ed8ab
VENUS_SHA256=25f236bbc32c8490fc61c20a6016b0bea4a8c3267a69de6b91496da2afe6bc04