cmake_minimum_required(VERSION 3.22)
if(NOT SOL_LIVE_RELEASE_VERSION MATCHES "^[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?$"
   OR NOT EXISTS "${SOL_LIVE_SOURCE_DIR}/CMakeLists.txt")
    message(FATAL_ERROR "Run Build-Engine.ps1 to configure with the current SOL DAW Live release.")
endif()
set(live "${SOL_LIVE_SOURCE_DIR}")
file(STRINGS "${live}/CMakeLists.txt" version_line REGEX "^project\\(SOL_DAW VERSION [0-9.]+ ")
string(REGEX MATCH "VERSION ([0-9.]+) LANGUAGES" matched_version "${version_line}")
if(NOT matched_version OR NOT "${CMAKE_MATCH_1}" STREQUAL SOL_LIVE_RELEASE_VERSION)
    message(FATAL_ERROR "The selected SOL Daw Live source and panel build versions differ.")
endif()
project(SOL_DAW_Live_Control_Trial VERSION ${SOL_LIVE_RELEASE_VERSION} LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17)
set(licensing "${CMAKE_CURRENT_SOURCE_DIR}/../../release-20261101/licensing" CACHE PATH "SOL Studio licensing sources")
set(vendor "C:/Users/PC/Documents/Codex/SOLDEV/SOL-ALL-SOURCE-2026-10-28/Projects/SOL-DAW/vendor" CACHE PATH "SOL DAW vendor sources")
add_subdirectory("${vendor}/JUCE" juce-build)
juce_set_vst2_sdk_path("${vendor}/fst")
juce_set_ara_sdk_path("${vendor}/ARA_SDK")

# Keep the complete Windows Live application. Its factory dispatches the two
# panel command-line modes and delegates ordinary launches to the original app.
set(engine_source "${live}/Source/Main.cpp")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${engine_source}")
file(READ "${engine_source}" live_code)
string(FIND "${live_code}" "START_JUCE_APPLICATION(App)" editor_boundary)
if(editor_boundary LESS 1)
    message(FATAL_ERROR "Cannot locate SOL DAW Live's app entry point")
endif()
string(SUBSTRING "${live_code}" 0 ${editor_boundary} engine_code)
# Optional save hooks belong to the bundled panel edition. Normal SOL DAW
# launches leave them unset and continue using the shared project implementation.
function(replace_required variable old new)
    string(FIND "${${variable}}" "${old}" at)
    if(at LESS 0)
        message(FATAL_ERROR "Panel save integration no longer matches upstream: ${old}")
    endif()
    string(REPLACE "${old}" "${new}" updated "${${variable}}")
    set(${variable} "${updated}" PARENT_SCOPE)
endfunction()
foreach(header IN ITEMS ProjectSession LiveProjectSave SessionHistory)
    set(source "${live}/Source/${header}.h")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source}")
    file(READ "${source}" ${header})
endforeach()
replace_required(LiveProjectSave "var loadedWorkspace;" [=[var loadedWorkspace;
bool panelReplayMedia=false, panelOfflineEndpoints=false;
static bool panelEndpointName(const String& name) {
  return name.equalsIgnoreCase("SOL Receive") || name.equalsIgnoreCase("SOL Send") ||
         name.equalsIgnoreCase("TO SOL") || name.equalsIgnoreCase("FROM SOL");
}
bool skipPanelEndpoint(AudioPluginInstance* p) const { return panelOfflineEndpoints && panelEndpointName(p->getName()); }
int64 panelProbeRecordingLimit=0;
int64 captureLimit() const {return panelProbeRecordingLimit>0 ? panelProbeRecordingLimit : takeFrameLimit(rate);}
std::atomic<bool> panelTakeDeviceLost{false};
std::function<void(AudioBuffer<float>&)> panelProbeReceive;
std::function<void(float* const*,int,int,double)> panelMixLiveEffects;
std::function<void(const float*const*,int,int)> panelReadMic;
std::function<void(const String&)> panelTakeStopped;
std::function<String(const File&)> panelGuardSave;
std::function<void(AudioPluginInstance*)> panelPluginCreated;
std::function<String(var&)> panelFilterSnapshot;]=])
replace_required(LiveProjectSave "auto error=storePortable(target,portableSnapshot(target,workspace),media,withHistory,checkpoint);" [=[if(panelGuardSave) {
    if (auto reason=panelGuardSave(target); reason.isNotEmpty()) return reason;
  }
  auto snapshot=portableSnapshot(target,workspace);
  if(panelFilterSnapshot) {
    if(auto reason=panelFilterSnapshot(snapshot);reason.isNotEmpty())return reason;
  }
  auto error=storePortable(target,snapshot,media,withHistory,checkpoint);]=])
replace_required(ProjectSession "File protectedProjectSource;" [=[File protectedProjectSource;
std::function<void(const File&)> panelDidSave;]=])
replace_required(engine_code "const bool receiving=receiveTake&&isLiveReceive(track.descriptions[i]);" [=[const auto& desc=track.descriptions[i];
      if(panelOfflineEndpoints && (isLiveReceive(desc) || panelEndpointName(desc.name)))continue;
      if(panelReplayMedia && !recording && playing && track.audio.getNumSamples()>0 && isLiveReceive(desc))continue;
      const bool receiving=receiveTake&&isLiveReceive(desc);]=])
replace_required(engine_code "plugin->processBlock(receive,midi);" [=[if(panelProbeReceive)panelProbeReceive(receive);
        else plugin->processBlock(receive,midi);]=])
replace_required(engine_code "render(outputs,count,n,inputs,inputCount,sources);" "render(outputs,count,n,inputs,inputCount,sources,true);")
replace_required(engine_code "std::optional<InputTakeBuffers> raw;" [=[if(panelReadMic)panelReadMic(inputs,numInputs,n);
    std::optional<InputTakeBuffers> raw;]=])
replace_required(engine_code "render(deviceMix.getArrayOfWritePointers(),2,n,inputs,inputCount,sources);" "render(deviceMix.getArrayOfWritePointers(),2,n,inputs,inputCount,sources,true);")
replace_required(engine_code "bool playSources = true) {" "bool playSources = true,bool deviceOutput = false) {")
replace_required(engine_code "if(!legacySendActive)sendBuffer.clear();" [=[if(!legacySendActive)sendBuffer.clear();
    if(deviceOutput && panelMixLiveEffects)panelMixLiveEffects(out,jmin(channels,2),n,rate);]=])
replace_required(engine_code "takeFrameLimit(rate)-" "captureLimit()-")
replace_required(engine_code [=[if (auto x = engine.devices.createStateXml())
      atomicText(home().getChildFile("audio-device.xml"), x->toString());]=] [=[if (!engine.panelReplayMedia) if (auto x = engine.devices.createStateXml())
      atomicText(home().getChildFile("audio-device.xml"), x->toString());]=])
replace_required(engine_code "std::vector<std::unique_ptr<ExtraTake>> prepared;" [=[std::vector<File> newPanelTakeFiles;
    const ScopeGuard rollbackEmptyFiles{[&]{if(panelReplayMedia && !recording)for(const auto& f:newPanelTakeFiles)f.deleteFile();}};
    std::vector<std::unique_ptr<ExtraTake>> prepared;]=])
replace_required(engine_code [=[WavAudioFormat wav;auto*w=wav.createWriterFor(stream.release(),rate,take->channels]=] [=[if(panelReplayMedia)newPanelTakeFiles.push_back(take->file);
      WavAudioFormat wav;auto*w=wav.createWriterFor(stream.release(),rate,take->channels]=])
replace_required(engine_code "p->releaseResources();" "if(skipPanelEndpoint(p.get()))continue; p->releaseResources();")
foreach(realtime IN ITEMS true false)
    foreach(indent IN ITEMS "      " "        ")
        replace_required(engine_code "${indent}p->reset();\n${indent}p->setNonRealtime(${realtime});"
             "${indent}if(skipPanelEndpoint(p.get()))continue;\n${indent}p->reset();\n${indent}p->setNonRealtime(${realtime});")
    endforeach()
endforeach()
replace_required(engine_code "deviceFailed = true; // Finalize" [=[if(panelReplayMedia)panelTakeDeviceLost=true;
      deviceFailed = true; // Finalize]=])
replace_required(engine_code "void audioDeviceError(const String &) override { deviceFailed = true; }" [=[void audioDeviceError(const String &) override { if(panelReplayMedia)panelTakeDeviceLost=true;deviceFailed = true; }]=])
replace_required(engine_code [=[extraTakes.clear();if(errors.isEmpty())home().getChildFile("pending-recording.json").deleteFile();]=] [=[extraTakes.clear();if(errors.isEmpty())home().getChildFile("pending-recording.json").deleteFile();
      if(panelTakeStopped)panelTakeStopped(errors);]=])
replace_required(ProjectSession "if(Engine::writeProjectSnapshot(autosave,snapshot).isEmpty())" [=[if((!engine.panelFilterSnapshot || engine.panelFilterSnapshot(snapshot).isEmpty()) && Engine::writeProjectSnapshot(autosave,snapshot).isEmpty())]=])
replace_required(ProjectSession "projectLibrary.touch(file);syncProjectTitle();message" [=[projectLibrary.touch(file);if(panelDidSave)panelDidSave(file);syncProjectTitle();message]=])
replace_required(engine_code "historyPluginIds[p.get()]=Uuid().toString();" [=[historyPluginIds[p.get()]=Uuid().toString();if(panelPluginCreated)panelPluginCreated(p.get());]=])
replace_required(SessionHistory "void dirtyHistoryPlugin(AudioProcessor*p)" [=[decltype(historyWatched) panelParameterEdits{};
void dirtyHistoryPlugin(AudioProcessor*p,bool parameter=false)]=])
replace_required(SessionHistory "{historyDirty[i]=true;return;}" [=[{historyDirty[i]=true;if(parameter && engine.panelFilterSnapshot)panelParameterEdits[i]=p;return;}]=])
replace_required(SessionHistory "audioProcessorParameterChanged(AudioProcessor*p,int,float)override{dirtyHistoryPlugin(p);}" [=[audioProcessorParameterChanged(AudioProcessor*p,int,float)override{dirtyHistoryPlugin(p,true);}]=])
replace_required(SessionHistory "historyDirty[i]=true;historyWatched[i]=p;" [=[historyDirty[i]=true;panelParameterEdits[i]=nullptr;historyWatched[i]=p;]=])
replace_required(engine_code "if(!safe->projectFile.deleteFile())" [=[if((safe->engine.panelGuardSave && safe->engine.panelGuardSave(safe->projectFile).isNotEmpty()) || !safe->projectFile.deleteFile())]=])
replace_required(engine_code "safe->projectLibrary.touch(target);safe->syncProjectTitle();" [=[safe->projectLibrary.touch(target);if(safe->panelDidSave)safe->panelDidSave(target);safe->syncProjectTitle();]=])
foreach(header IN ITEMS ProjectSession LiveProjectSave SessionHistory)
    file(CONFIGURE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${header}.h" CONTENT "${${header}}" @ONLY)
endforeach()
option(SOL_RETAIL_LICENSE "Build the licensed singing bundle" OFF)
if(SOL_RETAIL_LICENSE)
# The retail product grants a separate, scoped SOL DAW Live entitlement.
replace_required(engine_code [=[static sol::License& dawLicense(){static sol::License value{"sol-daw"};return value;}]=] [=[class LiveDawLicense {
public:
    bool allowed() const noexcept { return live.allowed() || full.allowed(); }
    void showActivation() { live.showActivation(); }
private:
    sol::License live{"sol-daw-live"};
    sol::License full{"sol-daw"};
};
static LiveDawLicense& dawLicense(){static LiveDawLicense value;return value;}]=])
replace_required(engine_code [=[auto tool=solInstallAsset("Activation/SOL Bundle Activate.exe");
  return tool.existsAsFile()?tool:solInstallAsset("SOL Bundle Activate.exe");]=] [=[return File::getSpecialLocation(File::currentExecutableFile).getParentDirectory()
    .getParentDirectory().getChildFile("Resources/Activation/SOL Live Activate.exe");]=])
replace_required(engine_code [=[solBundleActivationTool().existsAsFile()?vi("Kích hoạt Bundle Nhạc AI…"):vi("Kích hoạt SOL DAW…")]=] [=[vi("Kích hoạt Phần mềm hát live…")]=])
endif()
file(CONFIGURE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/LiveEngine.inc" CONTENT "${engine_code}" @ONLY)
configure_file("${live}/Source/ProjectHome.h" "${CMAKE_CURRENT_BINARY_DIR}/ProjectHome.h" COPYONLY)
juce_add_gui_app(SOLLiveEngine PRODUCT_NAME "SOL Daw Live" COMPANY_NAME "SOL Studio"
    BUNDLE_ID "audio.sol.daw.live" ICON_BIG "${live}/Assets/sol-live-icon.png" ICON_SMALL "${live}/Assets/sol-live-icon.png")
get_target_property(resource_dir SOLLiveEngine JUCE_GENERATED_SOURCES_DIRECTORY)
get_target_property(info_file SOLLiveEngine JUCE_INFO_FILE)
add_custom_command(OUTPUT "${resource_dir}/SOLLiveEngine_resources.rc" APPEND DEPENDS "${info_file}")
add_custom_command(TARGET SOLLiveEngine POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:SOLLiveEngine>/Resources"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${live}/Assets/sol-live-icon.png" "$<TARGET_FILE_DIR:SOLLiveEngine>/Resources/sol-studio.png"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${live}/Assets/home-content.json" "$<TARGET_FILE_DIR:SOLLiveEngine>/Resources/home-content.json")
juce_add_binary_data(SOLVoicePresets HEADER_NAME VoicePresetsData.h NAMESPACE VoicePresetsData
    SOURCES VoicePresets/bright.soneq VoicePresets/balanced.soneq VoicePresets/warm.soneq)
target_link_libraries(SOLLiveEngine PRIVATE SOLVoicePresets)
target_sources(SOLLiveEngine PRIVATE PanelEngine.cpp MusicEndpoint.cpp HardwareInputs.cpp CleanupRecycle.cpp "${licensing}/SolLicense.cpp")
target_include_directories(SOLLiveEngine PRIVATE "${CMAKE_CURRENT_BINARY_DIR}" "${live}/Source"
    "${licensing}" "${vendor}/signalsmith-stretch" "${vendor}/signalsmith-linear/include")
target_compile_definitions(SOLLiveEngine PRIVATE SOL_DAW_VERSION_STRING="${PROJECT_VERSION}" JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0 JUCE_PLUGINHOST_VST3=1
    JUCE_PLUGINHOST_VST=1 JUCE_PLUGINHOST_ARA=1 JUCE_MODAL_LOOPS_PERMITTED=1 JUCE_DISPLAY_SPLASH_SCREEN=0
    JUCE_REPORT_APP_USAGE=0 JUCE_ASIO=1 JUCE_WASAPI=1)
target_compile_options(SOLLiveEngine PRIVATE /utf-8)
target_link_libraries(SOLLiveEngine PRIVATE juce::juce_audio_utils juce::juce_dsp juce::juce_cryptography
    winhttp crypt32 bcrypt advapi32 user32 gdi32 comdlg32)
