Also hide the scroll marks when hiding the scrollbar (#13454)

<|original_code|>
    // - <none>
    void TermControl::_ApplyUISettings()
    {
        _InitializeBackgroundBrush();

        // settings might be out-of-proc in the future
        auto settings{ _core.Settings() };

        // Apply padding as swapChainPanel's margin
        const auto newMargin = ParseThicknessFromPadding(settings.Padding());
        SwapChainPanel().Margin(newMargin);

        TSFInputControl().Margin(newMargin);

        // Apply settings for scrollbar
        if (settings.ScrollState() == ScrollbarState::Hidden)
        {
            // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the
            // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to
            // achieve the intended effect.
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);
            ScrollBar().Visibility(Visibility::Collapsed);
        }
        else // (default or Visible)
        {
            // Default behavior
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);
            ScrollBar().Visibility(Visibility::Visible);
        }

        _interactivity.UpdateSettings();
        if (_automationPeer)
        {
            _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,
                                                             newMargin.Top,
                                                             newMargin.Right,
                                                             newMargin.Bottom });
        }

        _showMarksInScrollbar = settings.ShowMarks();
        // Clear out all the current marks
        ScrollBarCanvas().Children().Clear();
        // When we hot reload the settings, the core will send us a scrollbar
        // update. If we enabled scrollbar marks, then great, when we handle
        // that message, we'll redraw them.
    }

    // Method Description:
    // - Sets background image and applies its settings (stretch, opacity and alignment)
    // - Checks path validity
    // Arguments:
    // - newAppearance
<|edits_diff|>
--- src/cascadia/TerminalControl/TermControl.cpp
+++ src/cascadia/TerminalControl/TermControl.cpp
@@ -20,6 +20,7 @@
             // achieve the intended effect.
             ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);
             ScrollBar().Visibility(Visibility::Collapsed);
+            ScrollMarksGrid().Visibility(Visibility::Collapsed);
         }
         else // (default or Visible)
         {
<|current_version|>
    // - <none>
    void TermControl::_ApplyUISettings()
    {
        _InitializeBackgroundBrush();

        // settings might be out-of-proc in the future
        auto settings{ _core.Settings() };

        // Apply padding as swapChainPanel's margin
        const auto newMargin = ParseThicknessFromPadding(settings.Padding());
        SwapChainPanel().Margin(newMargin);

        TSFInputControl().Margin(newMargin);

        // Apply settings for scrollbar
        if (settings.ScrollState() == ScrollbarState::Hidden)
        {
            // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the
            // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to
            // achieve the intended effect.
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);
            ScrollBar().Visibility(Visibility::Collapsed);
            ScrollMarksGrid().Visibility(Visibility::Collapsed);
        }
        else // (default or Visible)
        {
            // Default behavior
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);
            ScrollBar().Visibility(Visibility::Visible);
        }

        _interactivity.UpdateSettings();
        if (_automationPeer)
        {
            _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,
                                                             newMargin.Top,
                                                             newMargin.Right,
                                                             newMargin.Bottom });
        }

        _showMarksInScrollbar = settings.ShowMarks();
        // Clear out all the current marks
        ScrollBarCanvas().Children().Clear();
        // When we hot reload the settings, the core will send us a scrollbar
        // update. If we enabled scrollbar marks, then great, when we handle
        // that message, we'll redraw them.
    }

    // Method Description:
    // - Sets background image and applies its settings (stretch, opacity and alignment)
    // - Checks path validity
    // Arguments:
    // - newAppearance
<|next_version|>
    // - <none>
    void TermControl::_ApplyUISettings()
    {
        _InitializeBackgroundBrush();

        // settings might be out-of-proc in the future
        auto settings{ _core.Settings() };

        // Apply padding as swapChainPanel's margin
        const auto newMargin = ParseThicknessFromPadding(settings.Padding());
        SwapChainPanel().Margin(newMargin);

        TSFInputControl().Margin(newMargin);

        // Apply settings for scrollbar
        if (settings.ScrollState() == ScrollbarState::Hidden)
        {
            // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the
            // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to
            // achieve the intended effect.
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);
            ScrollBar().Visibility(Visibility::Collapsed);
            ScrollMarksGrid().Visibility(Visibility::Collapsed);
        }
        else // (default or Visible)
        {
            // Default behavior
            ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);
            ScrollBar().Visibility(Visibility::Visible);
            ScrollMarksGrid().Visibility(Visibility::Visible);
        }

        _interactivity.UpdateSettings();
        if (_automationPeer)
        {
            _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,
                                                             newMargin.Top,
                                                             newMargin.Right,
                                                             newMargin.Bottom });
        }

        _showMarksInScrollbar = settings.ShowMarks();
        // Clear out all the current marks
        ScrollBarCanvas().Children().Clear();
        // When we hot reload the settings, the core will send us a scrollbar
        // update. If we enabled scrollbar marks, then great, when we handle
        // that message, we'll redraw them.
    }

    // Method Description:
    // - Sets background image and applies its settings (stretch, opacity and alignment)
    // - Checks path validity
    // Arguments:
    // - newAppearance


Update the scrollbar postiton on `scrollToMark` (#13291)

<|original_code|>
                    minDistance = delta;
                }
            }
            break;
        }
        case ScrollToMarkDirection::Previous:
        default:
        {
            int minDistance = INT_MAX;
            for (const auto& mark : marks)
            {
                const auto delta = currentOffset - mark.start.y;
                if (delta > 0 && delta < minDistance)
                {
                    tgt = mark;
                    minDistance = delta;
                }
            }
            break;
        }
        }

        if (tgt.has_value())
        {
            UserScrollViewport(tgt->start.y);
        }
        else
        {
            if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)
            {
                UserScrollViewport(BufferHeight());
            }
            else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)
            {
                UserScrollViewport(0);
            }
        }
    }
}

<|edits_diff|>
--- src/cascadia/TerminalControl/ControlCore.cpp
+++ src/cascadia/TerminalControl/ControlCore.cpp
@@ -20,15 +20,22 @@
         }
         }

+        const auto viewHeight = ViewHeight();
+        const auto bufferSize = BufferHeight();
+
+        // UserScrollViewport, to update the Terminal about where the viewport should be
+        // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.
         if (tgt.has_value())
         {
             UserScrollViewport(tgt->start.y);
+            _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);
         }
         else
         {
             if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)
             {
                 UserScrollViewport(BufferHeight());
+                _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);
             }
             else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)
             {
<|current_version|>
                    minDistance = delta;
                }
            }
            break;
        }
        case ScrollToMarkDirection::Previous:
        default:
        {
            int minDistance = INT_MAX;
            for (const auto& mark : marks)
            {
                const auto delta = currentOffset - mark.start.y;
                if (delta > 0 && delta < minDistance)
                {
                    tgt = mark;
                    minDistance = delta;
                }
            }
            break;
        }
        }

        const auto viewHeight = ViewHeight();
        const auto bufferSize = BufferHeight();

        // UserScrollViewport, to update the Terminal about where the viewport should be
        // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.
        if (tgt.has_value())
        {
            UserScrollViewport(tgt->start.y);
            _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);
        }
        else
        {
            if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)
            {
                UserScrollViewport(BufferHeight());
                _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);
            }
            else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)
            {
                UserScrollViewport(0);
            }
        }
    }
}

<|next_version|>
                    minDistance = delta;
                }
            }
            break;
        }
        case ScrollToMarkDirection::Previous:
        default:
        {
            int minDistance = INT_MAX;
            for (const auto& mark : marks)
            {
                const auto delta = currentOffset - mark.start.y;
                if (delta > 0 && delta < minDistance)
                {
                    tgt = mark;
                    minDistance = delta;
                }
            }
            break;
        }
        }

        const auto viewHeight = ViewHeight();
        const auto bufferSize = BufferHeight();

        // UserScrollViewport, to update the Terminal about where the viewport should be
        // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.
        if (tgt.has_value())
        {
            UserScrollViewport(tgt->start.y);
            _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);
        }
        else
        {
            if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)
            {
                UserScrollViewport(BufferHeight());
                _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);
            }
            else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)
            {
                UserScrollViewport(0);
                _terminalScrollPositionChanged(0, viewHeight, bufferSize);
            }
        }
    }
}


Add tooltips for nav items in the SUI (#12448)

<|original_code|>
                _Navigate(*profileViewModel, subPage);
            }
            else
            {
                _Navigate(tag.as<hstring>(), subPage);
            }
        }
    }

    void MainPage::_InitializeProfilesList()
    {
        const auto menuItems = SettingsNav().MenuItems();

        // Manually create a NavigationViewItem for each profile
        // and keep a reference to them in a map so that we
        // can easily modify the correct one when the associated
        // profile changes.
        for (const auto& profile : _settingsClone.AllProfiles())
        {
            if (!profile.Deleted())
            {
                auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));
                menuItems.Append(navItem);
            }
        }

        // Top off (the end of the nav view) with the Add Profile item
        MUX::Controls::NavigationViewItem addProfileItem;
        addProfileItem.Content(box_value(RS_(L"Nav_AddNewProfile/Content")));
        addProfileItem.Tag(box_value(addProfileTag));

        FontIcon icon;
        // This is the "Add" symbol
        icon.Glyph(L"\xE710");
        addProfileItem.Icon(icon);

        menuItems.Append(addProfileItem);
    }

    void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)
    {
        const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };
        const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };
        const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };
        SettingsNav().MenuItems().InsertAt(index, navItem);

        // Select and navigate to the new profile
        SettingsNav().SelectedItem(navItem);
        _Navigate(profileViewModel, BreadcrumbSubPage::None);
    }

    MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)
    {
<|edits_diff|>
--- src/cascadia/TerminalSettingsEditor/MainPage.cpp
+++ src/cascadia/TerminalSettingsEditor/MainPage.cpp
@@ -20,6 +20,7 @@
             if (!profile.Deleted())
             {
                 auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));
+                Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));
                 menuItems.Append(navItem);
             }
         }
<|current_version|>
                _Navigate(*profileViewModel, subPage);
            }
            else
            {
                _Navigate(tag.as<hstring>(), subPage);
            }
        }
    }

    void MainPage::_InitializeProfilesList()
    {
        const auto menuItems = SettingsNav().MenuItems();

        // Manually create a NavigationViewItem for each profile
        // and keep a reference to them in a map so that we
        // can easily modify the correct one when the associated
        // profile changes.
        for (const auto& profile : _settingsClone.AllProfiles())
        {
            if (!profile.Deleted())
            {
                auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));
                Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));
                menuItems.Append(navItem);
            }
        }

        // Top off (the end of the nav view) with the Add Profile item
        MUX::Controls::NavigationViewItem addProfileItem;
        addProfileItem.Content(box_value(RS_(L"Nav_AddNewProfile/Content")));
        addProfileItem.Tag(box_value(addProfileTag));

        FontIcon icon;
        // This is the "Add" symbol
        icon.Glyph(L"\xE710");
        addProfileItem.Icon(icon);

        menuItems.Append(addProfileItem);
    }

    void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)
    {
        const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };
        const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };
        const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };
        SettingsNav().MenuItems().InsertAt(index, navItem);

        // Select and navigate to the new profile
        SettingsNav().SelectedItem(navItem);
        _Navigate(profileViewModel, BreadcrumbSubPage::None);
    }

    MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)
    {
<|next_version|>
                _Navigate(*profileViewModel, subPage);
            }
            else
            {
                _Navigate(tag.as<hstring>(), subPage);
            }
        }
    }

    void MainPage::_InitializeProfilesList()
    {
        const auto menuItems = SettingsNav().MenuItems();

        // Manually create a NavigationViewItem for each profile
        // and keep a reference to them in a map so that we
        // can easily modify the correct one when the associated
        // profile changes.
        for (const auto& profile : _settingsClone.AllProfiles())
        {
            if (!profile.Deleted())
            {
                auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));
                Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));
                menuItems.Append(navItem);
            }
        }

        // Top off (the end of the nav view) with the Add Profile item
        MUX::Controls::NavigationViewItem addProfileItem;
        addProfileItem.Content(box_value(RS_(L"Nav_AddNewProfile/Content")));
        Controls::ToolTipService::SetToolTip(addProfileItem, box_value(RS_(L"Nav_AddNewProfile/Content")));
        addProfileItem.Tag(box_value(addProfileTag));

        FontIcon icon;
        // This is the "Add" symbol
        icon.Glyph(L"\xE710");
        addProfileItem.Icon(icon);

        menuItems.Append(addProfileItem);
    }

    void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)
    {
        const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };
        const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };
        const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };
        SettingsNav().MenuItems().InsertAt(index, navItem);

        // Select and navigate to the new profile
        SettingsNav().SelectedItem(navItem);
        _Navigate(profileViewModel, BreadcrumbSubPage::None);
    }

    MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)
    {


Persist Runtime TabTitle and  Maximize/Focus/Fullscreen states (#12073)

<|original_code|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "ApplicationState.h"
#include "CascadiaSettings.h"
#include "ApplicationState.g.cpp"
#include "WindowLayout.g.cpp"
#include "ActionAndArgs.h"
#include "JsonUtils.h"
#include "FileUtils.h"
#include "../../types/inc/utils.hpp"

static constexpr std::wstring_view stateFileName{ L"state.json" };
static constexpr std::wstring_view elevatedStateFileName{ L"elevated-state.json" };

static constexpr std::string_view TabLayoutKey{ "tabLayout" };
static constexpr std::string_view InitialPositionKey{ "initialPosition" };
static constexpr std::string_view InitialSizeKey{ "initialSize" };

namespace Microsoft::Terminal::Settings::Model::JsonUtils
{
    using namespace winrt::Microsoft::Terminal::Settings::Model;

    template<>
    struct ConversionTrait<WindowLayout>
    {
        WindowLayout FromJson(const Json::Value& json)
        {
            auto layout = winrt::make_self<implementation::WindowLayout>();

            GetValueForKey(json, TabLayoutKey, layout->_TabLayout);
            GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);
            GetValueForKey(json, InitialSizeKey, layout->_InitialSize);

            return *layout;
        }

        bool CanConvert(const Json::Value& json)
        {
            return json.isObject();
        }

        Json::Value ToJson(const WindowLayout& val)
        {
            Json::Value json{ Json::objectValue };

            SetValueForKey(json, TabLayoutKey, val.TabLayout());
            SetValueForKey(json, InitialPositionKey, val.InitialPosition());
            SetValueForKey(json, InitialSizeKey, val.InitialSize());

            return json;
        }

        std::string TypeDescription() const
        {
            return "WindowLayout";
        }
    };
}

using namespace ::Microsoft::Terminal::Settings::Model;

namespace winrt::Microsoft::Terminal::Settings::Model::implementation
{
    winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)
    {
        JsonUtils::ConversionTrait<Model::WindowLayout> trait;
        auto json = trait.ToJson(layout);

        Json::StreamWriterBuilder wbuilder;
        const auto content = Json::writeString(wbuilder, json);
        return hstring{ til::u8u16(content) };
<|edits_diff|>
--- src/cascadia/TerminalSettingsModel/ApplicationState.cpp
+++ src/cascadia/TerminalSettingsModel/ApplicationState.cpp
@@ -17,6 +17,7 @@
 static constexpr std::string_view TabLayoutKey{ "tabLayout" };
 static constexpr std::string_view InitialPositionKey{ "initialPosition" };
 static constexpr std::string_view InitialSizeKey{ "initialSize" };
+static constexpr std::string_view LaunchModeKey{ "launchMode" };

 namespace Microsoft::Terminal::Settings::Model::JsonUtils
 {
@@ -31,6 +32,7 @@

             GetValueForKey(json, TabLayoutKey, layout->_TabLayout);
             GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);
+            GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);
             GetValueForKey(json, InitialSizeKey, layout->_InitialSize);

             return *layout;
<|current_version|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "ApplicationState.h"
#include "CascadiaSettings.h"
#include "ApplicationState.g.cpp"
#include "WindowLayout.g.cpp"
#include "ActionAndArgs.h"
#include "JsonUtils.h"
#include "FileUtils.h"
#include "../../types/inc/utils.hpp"

static constexpr std::wstring_view stateFileName{ L"state.json" };
static constexpr std::wstring_view elevatedStateFileName{ L"elevated-state.json" };

static constexpr std::string_view TabLayoutKey{ "tabLayout" };
static constexpr std::string_view InitialPositionKey{ "initialPosition" };
static constexpr std::string_view InitialSizeKey{ "initialSize" };
static constexpr std::string_view LaunchModeKey{ "launchMode" };

namespace Microsoft::Terminal::Settings::Model::JsonUtils
{
    using namespace winrt::Microsoft::Terminal::Settings::Model;

    template<>
    struct ConversionTrait<WindowLayout>
    {
        WindowLayout FromJson(const Json::Value& json)
        {
            auto layout = winrt::make_self<implementation::WindowLayout>();

            GetValueForKey(json, TabLayoutKey, layout->_TabLayout);
            GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);
            GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);
            GetValueForKey(json, InitialSizeKey, layout->_InitialSize);

            return *layout;
        }

        bool CanConvert(const Json::Value& json)
        {
            return json.isObject();
        }

        Json::Value ToJson(const WindowLayout& val)
        {
            Json::Value json{ Json::objectValue };

            SetValueForKey(json, TabLayoutKey, val.TabLayout());
            SetValueForKey(json, InitialPositionKey, val.InitialPosition());
            SetValueForKey(json, InitialSizeKey, val.InitialSize());

            return json;
        }

        std::string TypeDescription() const
        {
            return "WindowLayout";
        }
    };
}

using namespace ::Microsoft::Terminal::Settings::Model;

namespace winrt::Microsoft::Terminal::Settings::Model::implementation
{
    winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)
    {
        JsonUtils::ConversionTrait<Model::WindowLayout> trait;
        auto json = trait.ToJson(layout);

        Json::StreamWriterBuilder wbuilder;
        const auto content = Json::writeString(wbuilder, json);
        return hstring{ til::u8u16(content) };
<|next_version|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "ApplicationState.h"
#include "CascadiaSettings.h"
#include "ApplicationState.g.cpp"
#include "WindowLayout.g.cpp"
#include "ActionAndArgs.h"
#include "JsonUtils.h"
#include "FileUtils.h"
#include "../../types/inc/utils.hpp"

static constexpr std::wstring_view stateFileName{ L"state.json" };
static constexpr std::wstring_view elevatedStateFileName{ L"elevated-state.json" };

static constexpr std::string_view TabLayoutKey{ "tabLayout" };
static constexpr std::string_view InitialPositionKey{ "initialPosition" };
static constexpr std::string_view InitialSizeKey{ "initialSize" };
static constexpr std::string_view LaunchModeKey{ "launchMode" };

namespace Microsoft::Terminal::Settings::Model::JsonUtils
{
    using namespace winrt::Microsoft::Terminal::Settings::Model;

    template<>
    struct ConversionTrait<WindowLayout>
    {
        WindowLayout FromJson(const Json::Value& json)
        {
            auto layout = winrt::make_self<implementation::WindowLayout>();

            GetValueForKey(json, TabLayoutKey, layout->_TabLayout);
            GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);
            GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);
            GetValueForKey(json, InitialSizeKey, layout->_InitialSize);

            return *layout;
        }

        bool CanConvert(const Json::Value& json)
        {
            return json.isObject();
        }

        Json::Value ToJson(const WindowLayout& val)
        {
            Json::Value json{ Json::objectValue };

            SetValueForKey(json, TabLayoutKey, val.TabLayout());
            SetValueForKey(json, InitialPositionKey, val.InitialPosition());
            SetValueForKey(json, LaunchModeKey, val.LaunchMode());
            SetValueForKey(json, InitialSizeKey, val.InitialSize());

            return json;
        }

        std::string TypeDescription() const
        {
            return "WindowLayout";
        }
    };
}

using namespace ::Microsoft::Terminal::Settings::Model;

namespace winrt::Microsoft::Terminal::Settings::Model::implementation
{
    winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)
    {
        JsonUtils::ConversionTrait<Model::WindowLayout> trait;
        auto json = trait.ToJson(layout);

        Json::StreamWriterBuilder wbuilder;
        const auto content = Json::writeString(wbuilder, json);
        return hstring{ til::u8u16(content) };


Add profile generators for Visual Studio (#7774)

<|original_code|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "CascadiaSettings.h"
#include "CascadiaSettings.g.cpp"

#include <LibraryResources.h>

#include "AzureCloudShellGenerator.h"
#include "PowershellCoreProfileGenerator.h"
#include "WslDistroGenerator.h"

using namespace ::Microsoft::Terminal::Settings::Model;
using namespace winrt::Microsoft::Terminal;
using namespace winrt::Microsoft::Terminal::Control;
using namespace winrt::Microsoft::Terminal::Settings::Model::implementation;
using namespace winrt::Windows::Foundation::Collections;
using namespace Microsoft::Console;

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L"ms-appx:///ProfileIcons/" };

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" };
static constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L"{9acb9455-ca41-5af7-950f-6bca1bc9722f}" };

// make sure this matches defaults.json.
static constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}" };

CascadiaSettings::CascadiaSettings() :
    CascadiaSettings(true)
{
}

// Constructor Description:
// - Creates a new settings object. If addDynamicProfiles is true, we'll
//   automatically add the built-in profile generators to our list of profile
//   generators. Set this to `false` for unit testing.
// Arguments:
// - addDynamicProfiles: if true, we'll add the built-in DPGs.
CascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :
    _globals{ winrt::make_self<implementation::GlobalAppSettings>() },
    _allProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _activeProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _warnings{ winrt::single_threaded_vector<SettingsLoadWarnings>() },
    _deserializationErrorMessage{ L"" },
    _defaultTerminals{ winrt::single_threaded_observable_vector<Model::DefaultTerminal>() },
    _currentDefaultTerminal{ nullptr }
{
    if (addDynamicProfiles)
    {
        _profileGenerators.emplace_back(std::make_unique<PowershellCoreProfileGenerator>());
        _profileGenerators.emplace_back(std::make_unique<WslDistroGenerator>());
        _profileGenerators.emplace_back(std::make_unique<AzureCloudShellGenerator>());
    }
}

CascadiaSettings::CascadiaSettings(winrt::hstring json) :
    CascadiaSettings(false)
{
    const auto jsonString{ til::u16u8(json) };
    _ParseJsonString(jsonString, false);
    _ApplyDefaultsFromUserSettings();
    LayerJson(_userSettings);
    _ValidateSettings();
}

winrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const
{
    // dynamic profile generators added by default
    auto settings{ winrt::make_self<CascadiaSettings>() };
    settings->_globals = _globals->Copy();
    for (auto warning : _warnings)
    {
        settings->_warnings.Append(warning);
    }
    settings->_loadError = _loadError;
    settings->_deserializationErrorMessage = _deserializationErrorMessage;
<|edits_diff|>
--- src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp
+++ src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp
@@ -9,6 +9,8 @@

 #include "AzureCloudShellGenerator.h"
 #include "PowershellCoreProfileGenerator.h"
+#include "VsDevCmdGenerator.h"
+#include "VsDevShellGenerator.h"
 #include "WslDistroGenerator.h"

 using namespace ::Microsoft::Terminal::Settings::Model;
<|current_version|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "CascadiaSettings.h"
#include "CascadiaSettings.g.cpp"

#include <LibraryResources.h>

#include "AzureCloudShellGenerator.h"
#include "PowershellCoreProfileGenerator.h"
#include "VsDevCmdGenerator.h"
#include "VsDevShellGenerator.h"
#include "WslDistroGenerator.h"

using namespace ::Microsoft::Terminal::Settings::Model;
using namespace winrt::Microsoft::Terminal;
using namespace winrt::Microsoft::Terminal::Control;
using namespace winrt::Microsoft::Terminal::Settings::Model::implementation;
using namespace winrt::Windows::Foundation::Collections;
using namespace Microsoft::Console;

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L"ms-appx:///ProfileIcons/" };

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" };
static constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L"{9acb9455-ca41-5af7-950f-6bca1bc9722f}" };

// make sure this matches defaults.json.
static constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}" };

CascadiaSettings::CascadiaSettings() :
    CascadiaSettings(true)
{
}

// Constructor Description:
// - Creates a new settings object. If addDynamicProfiles is true, we'll
//   automatically add the built-in profile generators to our list of profile
//   generators. Set this to `false` for unit testing.
// Arguments:
// - addDynamicProfiles: if true, we'll add the built-in DPGs.
CascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :
    _globals{ winrt::make_self<implementation::GlobalAppSettings>() },
    _allProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _activeProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _warnings{ winrt::single_threaded_vector<SettingsLoadWarnings>() },
    _deserializationErrorMessage{ L"" },
    _defaultTerminals{ winrt::single_threaded_observable_vector<Model::DefaultTerminal>() },
    _currentDefaultTerminal{ nullptr }
{
    if (addDynamicProfiles)
    {
        _profileGenerators.emplace_back(std::make_unique<PowershellCoreProfileGenerator>());
        _profileGenerators.emplace_back(std::make_unique<WslDistroGenerator>());
        _profileGenerators.emplace_back(std::make_unique<AzureCloudShellGenerator>());
    }
}

CascadiaSettings::CascadiaSettings(winrt::hstring json) :
    CascadiaSettings(false)
{
    const auto jsonString{ til::u16u8(json) };
    _ParseJsonString(jsonString, false);
    _ApplyDefaultsFromUserSettings();
    LayerJson(_userSettings);
    _ValidateSettings();
}

winrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const
{
    // dynamic profile generators added by default
    auto settings{ winrt::make_self<CascadiaSettings>() };
    settings->_globals = _globals->Copy();
    for (auto warning : _warnings)
    {
        settings->_warnings.Append(warning);
    }
    settings->_loadError = _loadError;
    settings->_deserializationErrorMessage = _deserializationErrorMessage;
<|next_version|>
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include "pch.h"
#include "CascadiaSettings.h"
#include "CascadiaSettings.g.cpp"

#include <LibraryResources.h>

#include "AzureCloudShellGenerator.h"
#include "PowershellCoreProfileGenerator.h"
#include "VsDevCmdGenerator.h"
#include "VsDevShellGenerator.h"
#include "WslDistroGenerator.h"

using namespace ::Microsoft::Terminal::Settings::Model;
using namespace winrt::Microsoft::Terminal;
using namespace winrt::Microsoft::Terminal::Control;
using namespace winrt::Microsoft::Terminal::Settings::Model::implementation;
using namespace winrt::Windows::Foundation::Collections;
using namespace Microsoft::Console;

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L"ms-appx:///ProfileIcons/" };

static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" };
static constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L"{9acb9455-ca41-5af7-950f-6bca1bc9722f}" };

// make sure this matches defaults.json.
static constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}" };

CascadiaSettings::CascadiaSettings() :
    CascadiaSettings(true)
{
}

// Constructor Description:
// - Creates a new settings object. If addDynamicProfiles is true, we'll
//   automatically add the built-in profile generators to our list of profile
//   generators. Set this to `false` for unit testing.
// Arguments:
// - addDynamicProfiles: if true, we'll add the built-in DPGs.
CascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :
    _globals{ winrt::make_self<implementation::GlobalAppSettings>() },
    _allProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _activeProfiles{ winrt::single_threaded_observable_vector<Model::Profile>() },
    _warnings{ winrt::single_threaded_vector<SettingsLoadWarnings>() },
    _deserializationErrorMessage{ L"" },
    _defaultTerminals{ winrt::single_threaded_observable_vector<Model::DefaultTerminal>() },
    _currentDefaultTerminal{ nullptr }
{
    if (addDynamicProfiles)
    {
        _profileGenerators.emplace_back(std::make_unique<PowershellCoreProfileGenerator>());
        _profileGenerators.emplace_back(std::make_unique<WslDistroGenerator>());
        _profileGenerators.emplace_back(std::make_unique<AzureCloudShellGenerator>());
        _profileGenerators.emplace_back(std::make_unique<VsDevCmdGenerator>());
        _profileGenerators.emplace_back(std::make_unique<VsDevShellGenerator>());
    }
}

CascadiaSettings::CascadiaSettings(winrt::hstring json) :
    CascadiaSettings(false)
{
    const auto jsonString{ til::u16u8(json) };
    _ParseJsonString(jsonString, false);
    _ApplyDefaultsFromUserSettings();
    LayerJson(_userSettings);
    _ValidateSettings();
}

winrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const
{
    // dynamic profile generators added by default
    auto settings{ winrt::make_self<CascadiaSettings>() };
    settings->_globals = _globals->Copy();
    for (auto warning : _warnings)
    {
        settings->_warnings.Append(warning);
    }
    settings->_loadError = _loadError;
    settings->_deserializationErrorMessage = _deserializationErrorMessage;


Add the ability to quit all terminal instances (#11143)

<|original_code|>
    // class can be used to replace a peasant inside a Monarch, to emulate that
    // peasant process dying. Any time the monarch tries to do something to this
    // peasant, it'll throw an exception.
    struct DeadPeasant : implements<DeadPeasant, winrt::Microsoft::Terminal::Remoting::IPeasant>
    {
        DeadPeasant() = default;
        void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };
        uint64_t GetID() { throw winrt::hresult_error{}; };
        winrt::hstring WindowName() { throw winrt::hresult_error{}; };
        winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };
        void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };
        uint64_t GetPID() { throw winrt::hresult_error{}; };
        bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }
        void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }
        void RequestIdentifyWindows() { throw winrt::hresult_error{}; };
        void DisplayWindowId() { throw winrt::hresult_error{}; };
        Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }
        Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }
        void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }
        void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };
        void RequestShowTrayIcon() { throw winrt::hresult_error{}; };
        void RequestHideTrayIcon() { throw winrt::hresult_error{}; };
        TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);
        TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);
        TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);
        TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);
        TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
    };

    class RemotingTests
    {
        BEGIN_TEST_CLASS(RemotingTests)
        END_TEST_CLASS()

        TEST_METHOD(CreateMonarch);
        TEST_METHOD(CreatePeasant);
        TEST_METHOD(CreatePeasantWithNew);
        TEST_METHOD(AddPeasants);
        TEST_METHOD(GetPeasantsByID);
        TEST_METHOD(AddPeasantsToNewMonarch);
        TEST_METHOD(RemovePeasantFromMonarchWhenFreed);

        TEST_METHOD(ProposeCommandlineNoWindow);
        TEST_METHOD(ProposeCommandlineGivenWindow);
        TEST_METHOD(ProposeCommandlineNegativeWindow);
        TEST_METHOD(ProposeCommandlineCurrentWindow);
        TEST_METHOD(ProposeCommandlineNonExistentWindow);
        TEST_METHOD(ProposeCommandlineDeadWindow);

        TEST_METHOD(MostRecentWindowSameDesktops);
        TEST_METHOD(MostRecentWindowDifferentDesktops);
<|edits_diff|>
--- src/cascadia/UnitTests_Remoting/RemotingTests.cpp
+++ src/cascadia/UnitTests_Remoting/RemotingTests.cpp
@@ -20,6 +20,8 @@
         void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };
         void RequestShowTrayIcon() { throw winrt::hresult_error{}; };
         void RequestHideTrayIcon() { throw winrt::hresult_error{}; };
+        void RequestQuitAll() { throw winrt::hresult_error{}; };
+        void Quit() { throw winrt::hresult_error{}; };
         TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);
         TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);
         TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
<|current_version|>
    // class can be used to replace a peasant inside a Monarch, to emulate that
    // peasant process dying. Any time the monarch tries to do something to this
    // peasant, it'll throw an exception.
    struct DeadPeasant : implements<DeadPeasant, winrt::Microsoft::Terminal::Remoting::IPeasant>
    {
        DeadPeasant() = default;
        void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };
        uint64_t GetID() { throw winrt::hresult_error{}; };
        winrt::hstring WindowName() { throw winrt::hresult_error{}; };
        winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };
        void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };
        uint64_t GetPID() { throw winrt::hresult_error{}; };
        bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }
        void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }
        void RequestIdentifyWindows() { throw winrt::hresult_error{}; };
        void DisplayWindowId() { throw winrt::hresult_error{}; };
        Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }
        Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }
        void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }
        void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };
        void RequestShowTrayIcon() { throw winrt::hresult_error{}; };
        void RequestHideTrayIcon() { throw winrt::hresult_error{}; };
        void RequestQuitAll() { throw winrt::hresult_error{}; };
        void Quit() { throw winrt::hresult_error{}; };
        TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);
        TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);
        TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);
        TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);
        TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
    };

    class RemotingTests
    {
        BEGIN_TEST_CLASS(RemotingTests)
        END_TEST_CLASS()

        TEST_METHOD(CreateMonarch);
        TEST_METHOD(CreatePeasant);
        TEST_METHOD(CreatePeasantWithNew);
        TEST_METHOD(AddPeasants);
        TEST_METHOD(GetPeasantsByID);
        TEST_METHOD(AddPeasantsToNewMonarch);
        TEST_METHOD(RemovePeasantFromMonarchWhenFreed);

        TEST_METHOD(ProposeCommandlineNoWindow);
        TEST_METHOD(ProposeCommandlineGivenWindow);
        TEST_METHOD(ProposeCommandlineNegativeWindow);
        TEST_METHOD(ProposeCommandlineCurrentWindow);
        TEST_METHOD(ProposeCommandlineNonExistentWindow);
        TEST_METHOD(ProposeCommandlineDeadWindow);

        TEST_METHOD(MostRecentWindowSameDesktops);
        TEST_METHOD(MostRecentWindowDifferentDesktops);
<|next_version|>
    // class can be used to replace a peasant inside a Monarch, to emulate that
    // peasant process dying. Any time the monarch tries to do something to this
    // peasant, it'll throw an exception.
    struct DeadPeasant : implements<DeadPeasant, winrt::Microsoft::Terminal::Remoting::IPeasant>
    {
        DeadPeasant() = default;
        void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };
        uint64_t GetID() { throw winrt::hresult_error{}; };
        winrt::hstring WindowName() { throw winrt::hresult_error{}; };
        winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };
        void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };
        uint64_t GetPID() { throw winrt::hresult_error{}; };
        bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }
        void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }
        void RequestIdentifyWindows() { throw winrt::hresult_error{}; };
        void DisplayWindowId() { throw winrt::hresult_error{}; };
        Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }
        Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }
        void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }
        void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };
        void RequestShowTrayIcon() { throw winrt::hresult_error{}; };
        void RequestHideTrayIcon() { throw winrt::hresult_error{}; };
        void RequestQuitAll() { throw winrt::hresult_error{}; };
        void Quit() { throw winrt::hresult_error{}; };
        TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);
        TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);
        TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);
        TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);
        TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(QuitAllRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
        TYPED_EVENT(QuitRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
    };

    class RemotingTests
    {
        BEGIN_TEST_CLASS(RemotingTests)
        END_TEST_CLASS()

        TEST_METHOD(CreateMonarch);
        TEST_METHOD(CreatePeasant);
        TEST_METHOD(CreatePeasantWithNew);
        TEST_METHOD(AddPeasants);
        TEST_METHOD(GetPeasantsByID);
        TEST_METHOD(AddPeasantsToNewMonarch);
        TEST_METHOD(RemovePeasantFromMonarchWhenFreed);

        TEST_METHOD(ProposeCommandlineNoWindow);
        TEST_METHOD(ProposeCommandlineGivenWindow);
        TEST_METHOD(ProposeCommandlineNegativeWindow);
        TEST_METHOD(ProposeCommandlineCurrentWindow);
        TEST_METHOD(ProposeCommandlineNonExistentWindow);
        TEST_METHOD(ProposeCommandlineDeadWindow);

        TEST_METHOD(MostRecentWindowSameDesktops);
        TEST_METHOD(MostRecentWindowDifferentDesktops);


llama-tts : avoid crashes related to bad model file paths (#12482)

<|original_code|>

    const int n_parallel = params.n_parallel;
    const int n_predict  = params.n_predict;

    common_init();

    // init LLM

    llama_backend_init();
    llama_numa_init(params.numa);

    llama_model * model_ttc = NULL; // text-to-codes
    llama_model * model_cts = NULL; // codes-to-speech

    llama_context * ctx_ttc = NULL;
    llama_context * ctx_cts = NULL;

    common_init_result llama_init_ttc = common_init_from_params(params);

    model_ttc = llama_init_ttc.model.get();
    ctx_ttc   = llama_init_ttc.context.get();

    const llama_vocab * vocab = llama_model_get_vocab(model_ttc);

    // TODO: refactor in a common struct
    params.model     = params.vocoder.model;
    params.model_url = params.vocoder.model_url;
    params.hf_repo   = params.vocoder.hf_repo;
    params.hf_file   = params.vocoder.hf_file;

    params.embedding = true;

    common_init_result llama_init_cts = common_init_from_params(params);

    model_cts = llama_init_cts.model.get();
    ctx_cts   = llama_init_cts.context.get();

    std::vector<common_sampler *> smpl(n_parallel);
    for (int i = 0; i < n_parallel; ++i) {
        params.sampling.no_perf = (i != 0);
        params.sampling.seed = params.sampling.seed + 1;

        smpl[i] = common_sampler_init(model_ttc, params.sampling);
    }

    LOG_INF("sampler seed: %u\n",     common_sampler_get_seed(smpl[0]));
    LOG_INF("sampler params: \n%s\n", params.sampling.print().c_str());
    LOG_INF("sampler chain: %s\n",    common_sampler_print(smpl[0]).c_str());

    LOG_INF("%s: loading done\n", __func__);

    const auto t_main_start = ggml_time_us();

    std::vector<llama_token> codes;
    std::vector<llama_token> guide_tokens;

    // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json
    std::string audio_text = "<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>";
    std::string audio_data = R"(<|audio_start|>
the<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>
<|edits_diff|>
--- examples/tts/tts.cpp
+++ examples/tts/tts.cpp
@@ -19,6 +19,10 @@

     model_ttc = llama_init_ttc.model.get();
     ctx_ttc   = llama_init_ttc.context.get();
+
+    if (model_ttc == nullptr || ctx_ttc == nullptr) {
+        return ENOENT;
+    }

     const llama_vocab * vocab = llama_model_get_vocab(model_ttc);

<|current_version|>

    const int n_parallel = params.n_parallel;
    const int n_predict  = params.n_predict;

    common_init();

    // init LLM

    llama_backend_init();
    llama_numa_init(params.numa);

    llama_model * model_ttc = NULL; // text-to-codes
    llama_model * model_cts = NULL; // codes-to-speech

    llama_context * ctx_ttc = NULL;
    llama_context * ctx_cts = NULL;

    common_init_result llama_init_ttc = common_init_from_params(params);

    model_ttc = llama_init_ttc.model.get();
    ctx_ttc   = llama_init_ttc.context.get();

    if (model_ttc == nullptr || ctx_ttc == nullptr) {
        return ENOENT;
    }

    const llama_vocab * vocab = llama_model_get_vocab(model_ttc);

    // TODO: refactor in a common struct
    params.model     = params.vocoder.model;
    params.model_url = params.vocoder.model_url;
    params.hf_repo   = params.vocoder.hf_repo;
    params.hf_file   = params.vocoder.hf_file;

    params.embedding = true;

    common_init_result llama_init_cts = common_init_from_params(params);

    model_cts = llama_init_cts.model.get();
    ctx_cts   = llama_init_cts.context.get();

    std::vector<common_sampler *> smpl(n_parallel);
    for (int i = 0; i < n_parallel; ++i) {
        params.sampling.no_perf = (i != 0);
        params.sampling.seed = params.sampling.seed + 1;

        smpl[i] = common_sampler_init(model_ttc, params.sampling);
    }

    LOG_INF("sampler seed: %u\n",     common_sampler_get_seed(smpl[0]));
    LOG_INF("sampler params: \n%s\n", params.sampling.print().c_str());
    LOG_INF("sampler chain: %s\n",    common_sampler_print(smpl[0]).c_str());

    LOG_INF("%s: loading done\n", __func__);

    const auto t_main_start = ggml_time_us();

    std::vector<llama_token> codes;
    std::vector<llama_token> guide_tokens;

    // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json
    std::string audio_text = "<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>";
    std::string audio_data = R"(<|audio_start|>
the<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>
<|next_version|>

    const int n_parallel = params.n_parallel;
    const int n_predict  = params.n_predict;

    common_init();

    // init LLM

    llama_backend_init();
    llama_numa_init(params.numa);

    llama_model * model_ttc = NULL; // text-to-codes
    llama_model * model_cts = NULL; // codes-to-speech

    llama_context * ctx_ttc = NULL;
    llama_context * ctx_cts = NULL;

    common_init_result llama_init_ttc = common_init_from_params(params);

    model_ttc = llama_init_ttc.model.get();
    ctx_ttc   = llama_init_ttc.context.get();

    if (model_ttc == nullptr || ctx_ttc == nullptr) {
        return ENOENT;
    }

    const llama_vocab * vocab = llama_model_get_vocab(model_ttc);

    // TODO: refactor in a common struct
    params.model     = params.vocoder.model;
    params.model_url = params.vocoder.model_url;
    params.hf_repo   = params.vocoder.hf_repo;
    params.hf_file   = params.vocoder.hf_file;

    params.embedding = true;

    common_init_result llama_init_cts = common_init_from_params(params);

    model_cts = llama_init_cts.model.get();
    ctx_cts   = llama_init_cts.context.get();

    if (model_cts == nullptr || ctx_cts == nullptr) {
        return ENOENT;
    }

    std::vector<common_sampler *> smpl(n_parallel);
    for (int i = 0; i < n_parallel; ++i) {
        params.sampling.no_perf = (i != 0);
        params.sampling.seed = params.sampling.seed + 1;

        smpl[i] = common_sampler_init(model_ttc, params.sampling);
    }

    LOG_INF("sampler seed: %u\n",     common_sampler_get_seed(smpl[0]));
    LOG_INF("sampler params: \n%s\n", params.sampling.print().c_str());
    LOG_INF("sampler chain: %s\n",    common_sampler_print(smpl[0]).c_str());

    LOG_INF("%s: loading done\n", __func__);

    const auto t_main_start = ggml_time_us();

    std::vector<llama_token> codes;
    std::vector<llama_token> guide_tokens;

    // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json
    std::string audio_text = "<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>";
    std::string audio_data = R"(<|audio_start|>
the<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>


check for nans in imatrix and quantize (#7807)

<|original_code|>
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);
        }
        // loop over all possible experts, regardless if they are used or not in the batch
        for (int ex = 0; ex < n_as; ++ex) {
            size_t e_start = ex*src1->ne[0];

            for (int idx = 0; idx < n_ids; ++idx) {
                for (int row = 0; row < (int)src1->ne[2]; ++row) {
                    const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);

                    GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check

                    if (excur != ex) continue;

                    const int64_t i11 = idx % src1->ne[1];
                    const int64_t i12 = row;
                    const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);

                    for (int j = 0; j < (int)src1->ne[0]; ++j) {
                        e.values[e_start + j] += x[j]*x[j];
                        e.counts[e_start + j]++;
                    }
                }
            }
            if (e.ncall > m_last_call) {
                m_last_call = e.ncall;
                if (m_last_call % m_params.n_out_freq == 0) {
                    save_imatrix();
                }
                if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                    save_imatrix(m_last_call);
                }
            }
        }
    } else {
        auto & e = m_stats[wname];
        if (e.values.empty()) {
            e.values.resize(src1->ne[0], 0);
            e.counts.resize(src1->ne[0], 0);
        }
        else if (e.values.size() != (size_t)src1->ne[0]) {
            fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
            exit(1); //GGML_ASSERT(false);
        }
        ++e.ncall;
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
        }
        for (int row = 0; row < (int)src1->ne[1]; ++row) {
            const float * x = data + row * src1->ne[0];
            for (int j = 0; j < (int)src1->ne[0]; ++j) {
                e.values[j] += x[j]*x[j];
                e.counts[j]++;
            }
        }
        if (e.ncall > m_last_call) {
            m_last_call = e.ncall;
            if (m_last_call % m_params.n_out_freq == 0) {
                save_imatrix();
            }
            if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                save_imatrix(m_last_call);
            }
        }
    }

    return true;
}

void IMatrixCollector::save_imatrix(int ncall) const {
    auto fname = m_params.out_file;
    if (fname.empty()) {
        fname = "imatrix.dat";
    }

    if (ncall > 0) {
        fname += ".at_";
<|edits_diff|>
--- examples/imatrix/imatrix.cpp
+++ examples/imatrix/imatrix.cpp
@@ -20,6 +20,10 @@
                     for (int j = 0; j < (int)src1->ne[0]; ++j) {
                         e.values[e_start + j] += x[j]*x[j];
                         e.counts[e_start + j]++;
+                        if (!std::isfinite(e.values[e_start + j])) {
+                            fprintf(stderr, "%f detected in %s\n", e.values[e_start + j], wname.c_str());
+                            exit(1);
+                        }
                     }
                 }
             }
<|current_version|>
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);
        }
        // loop over all possible experts, regardless if they are used or not in the batch
        for (int ex = 0; ex < n_as; ++ex) {
            size_t e_start = ex*src1->ne[0];

            for (int idx = 0; idx < n_ids; ++idx) {
                for (int row = 0; row < (int)src1->ne[2]; ++row) {
                    const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);

                    GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check

                    if (excur != ex) continue;

                    const int64_t i11 = idx % src1->ne[1];
                    const int64_t i12 = row;
                    const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);

                    for (int j = 0; j < (int)src1->ne[0]; ++j) {
                        e.values[e_start + j] += x[j]*x[j];
                        e.counts[e_start + j]++;
                        if (!std::isfinite(e.values[e_start + j])) {
                            fprintf(stderr, "%f detected in %s\n", e.values[e_start + j], wname.c_str());
                            exit(1);
                        }
                    }
                }
            }
            if (e.ncall > m_last_call) {
                m_last_call = e.ncall;
                if (m_last_call % m_params.n_out_freq == 0) {
                    save_imatrix();
                }
                if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                    save_imatrix(m_last_call);
                }
            }
        }
    } else {
        auto & e = m_stats[wname];
        if (e.values.empty()) {
            e.values.resize(src1->ne[0], 0);
            e.counts.resize(src1->ne[0], 0);
        }
        else if (e.values.size() != (size_t)src1->ne[0]) {
            fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
            exit(1); //GGML_ASSERT(false);
        }
        ++e.ncall;
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
        }
        for (int row = 0; row < (int)src1->ne[1]; ++row) {
            const float * x = data + row * src1->ne[0];
            for (int j = 0; j < (int)src1->ne[0]; ++j) {
                e.values[j] += x[j]*x[j];
                e.counts[j]++;
            }
        }
        if (e.ncall > m_last_call) {
            m_last_call = e.ncall;
            if (m_last_call % m_params.n_out_freq == 0) {
                save_imatrix();
            }
            if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                save_imatrix(m_last_call);
            }
        }
    }

    return true;
}

void IMatrixCollector::save_imatrix(int ncall) const {
    auto fname = m_params.out_file;
    if (fname.empty()) {
        fname = "imatrix.dat";
    }

    if (ncall > 0) {
        fname += ".at_";
<|next_version|>
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);
        }
        // loop over all possible experts, regardless if they are used or not in the batch
        for (int ex = 0; ex < n_as; ++ex) {
            size_t e_start = ex*src1->ne[0];

            for (int idx = 0; idx < n_ids; ++idx) {
                for (int row = 0; row < (int)src1->ne[2]; ++row) {
                    const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);

                    GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check

                    if (excur != ex) continue;

                    const int64_t i11 = idx % src1->ne[1];
                    const int64_t i12 = row;
                    const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);

                    for (int j = 0; j < (int)src1->ne[0]; ++j) {
                        e.values[e_start + j] += x[j]*x[j];
                        e.counts[e_start + j]++;
                        if (!std::isfinite(e.values[e_start + j])) {
                            fprintf(stderr, "%f detected in %s\n", e.values[e_start + j], wname.c_str());
                            exit(1);
                        }
                    }
                }
            }
            if (e.ncall > m_last_call) {
                m_last_call = e.ncall;
                if (m_last_call % m_params.n_out_freq == 0) {
                    save_imatrix();
                }
                if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                    save_imatrix(m_last_call);
                }
            }
        }
    } else {
        auto & e = m_stats[wname];
        if (e.values.empty()) {
            e.values.resize(src1->ne[0], 0);
            e.counts.resize(src1->ne[0], 0);
        }
        else if (e.values.size() != (size_t)src1->ne[0]) {
            fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
            exit(1); //GGML_ASSERT(false);
        }
        ++e.ncall;
        if (m_params.verbosity > 1) {
            printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
        }
        for (int row = 0; row < (int)src1->ne[1]; ++row) {
            const float * x = data + row * src1->ne[0];
            for (int j = 0; j < (int)src1->ne[0]; ++j) {
                e.values[j] += x[j]*x[j];
                e.counts[j]++;
                if (!std::isfinite(e.values[j])) {
                    fprintf(stderr, "%f detected in %s\n", e.values[j], wname.c_str());
                    exit(1);
                }
            }
        }
        if (e.ncall > m_last_call) {
            m_last_call = e.ncall;
            if (m_last_call % m_params.n_out_freq == 0) {
                save_imatrix();
            }
            if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
                save_imatrix(m_last_call);
            }
        }
    }

    return true;
}

void IMatrixCollector::save_imatrix(int ncall) const {
    auto fname = m_params.out_file;
    if (fname.empty()) {
        fname = "imatrix.dat";
    }

    if (ncall > 0) {
        fname += ".at_";


llama : ggml-backend integration (#4766)

<|original_code|>
    }

    if (argc >= 7) {
        n_pp = parse_list(argv[6]);
    }

    if (argc >= 8) {
        n_tg = parse_list(argv[7]);
    }

    if (argc >= 9) {
        n_pl = parse_list(argv[8]);
    }

    // init LLM

    llama_backend_init(params.numa);

    // initialize the model

    llama_model_params model_params = llama_model_default_params();

    model_params.n_gpu_layers = n_gpu_layers;

    llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);

    if (model == NULL) {
        fprintf(stderr , "%s: error: unable to load model\n" , __func__);
        return 1;
    }

    llama_context_params ctx_params = llama_context_default_params();

    ctx_params.seed      = 1234;
    ctx_params.n_ctx     = n_kv_max;
    ctx_params.n_batch   = 512;
    ctx_params.mul_mat_q = mmq;

    ctx_params.n_threads       = params.n_threads;
    ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;

    llama_context * ctx = llama_new_context_with_model(model, ctx_params);

    if (ctx == NULL) {
        fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
        return 1;
    }
<|edits_diff|>
--- examples/batched-bench/batched-bench.cpp
+++ examples/batched-bench/batched-bench.cpp
@@ -19,6 +19,8 @@
     // initialize the model

     llama_model_params model_params = llama_model_default_params();
+
+    const std::vector<float> t_split (LLAMA_MAX_DEVICES, 0.0f);

     model_params.n_gpu_layers = n_gpu_layers;

<|current_version|>
    }

    if (argc >= 7) {
        n_pp = parse_list(argv[6]);
    }

    if (argc >= 8) {
        n_tg = parse_list(argv[7]);
    }

    if (argc >= 9) {
        n_pl = parse_list(argv[8]);
    }

    // init LLM

    llama_backend_init(params.numa);

    // initialize the model

    llama_model_params model_params = llama_model_default_params();

    const std::vector<float> t_split (LLAMA_MAX_DEVICES, 0.0f);

    model_params.n_gpu_layers = n_gpu_layers;

    llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);

    if (model == NULL) {
        fprintf(stderr , "%s: error: unable to load model\n" , __func__);
        return 1;
    }

    llama_context_params ctx_params = llama_context_default_params();

    ctx_params.seed      = 1234;
    ctx_params.n_ctx     = n_kv_max;
    ctx_params.n_batch   = 512;
    ctx_params.mul_mat_q = mmq;

    ctx_params.n_threads       = params.n_threads;
    ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;

    llama_context * ctx = llama_new_context_with_model(model, ctx_params);

    if (ctx == NULL) {
        fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
        return 1;
    }
<|next_version|>
    }

    if (argc >= 7) {
        n_pp = parse_list(argv[6]);
    }

    if (argc >= 8) {
        n_tg = parse_list(argv[7]);
    }

    if (argc >= 9) {
        n_pl = parse_list(argv[8]);
    }

    // init LLM

    llama_backend_init(params.numa);

    // initialize the model

    llama_model_params model_params = llama_model_default_params();

    const std::vector<float> t_split (LLAMA_MAX_DEVICES, 0.0f);

    model_params.n_gpu_layers = n_gpu_layers;
    model_params.tensor_split = t_split.data();

    llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);

    if (model == NULL) {
        fprintf(stderr , "%s: error: unable to load model\n" , __func__);
        return 1;
    }

    llama_context_params ctx_params = llama_context_default_params();

    ctx_params.seed      = 1234;
    ctx_params.n_ctx     = n_kv_max;
    ctx_params.n_batch   = 512;
    ctx_params.mul_mat_q = mmq;

    ctx_params.n_threads       = params.n_threads;
    ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;

    llama_context * ctx = llama_new_context_with_model(model, ctx_params);

    if (ctx == NULL) {
        fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
        return 1;
    }


llama : remember and restore kv cache data pointers (#1104)

<|original_code|>
// ongoing prediction with the model.
const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.addr;
}

// Returns the size of the KV cache
size_t llama_get_kv_cache_size(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.size;
}

int llama_get_kv_cache_token_count(struct llama_context * ctx) {
    return ctx->model.kv_self.n;
}

// Sets the KV cache containing the current context for the model
void llama_set_kv_cache(
        struct llama_context * ctx,
               const uint8_t * kv_cache,
                      size_t   n_size,
                         int   n_token_count) {
    // Make sure we have the same kv cache setup
    LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
    memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
    ctx->model.kv_self.n = n_token_count;
}

int llama_eval(
        struct llama_context * ctx,
           const llama_token * tokens,
                         int   n_tokens,
                         int   n_past,
                         int   n_threads) {
    if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
        fprintf(stderr, "%s: failed to eval\n", __func__);
        return 1;
    }
    // get a more accurate load time, upon first eval
    if (!ctx->has_evaluated_once) {
        ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
        ctx->has_evaluated_once = true;
    }
    return 0;
}

int llama_tokenize(
        struct llama_context * ctx,
                  const char * text,
<|edits_diff|>
--- llama.cpp
+++ llama.cpp
@@ -20,6 +20,8 @@
                          int   n_token_count) {
     // Make sure we have the same kv cache setup
     LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
+    void * k_data = ctx->model.kv_self.k->data; // remember data pointers
+    void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy
     memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
     ctx->model.kv_self.n = n_token_count;
 }
<|current_version|>
// ongoing prediction with the model.
const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.addr;
}

// Returns the size of the KV cache
size_t llama_get_kv_cache_size(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.size;
}

int llama_get_kv_cache_token_count(struct llama_context * ctx) {
    return ctx->model.kv_self.n;
}

// Sets the KV cache containing the current context for the model
void llama_set_kv_cache(
        struct llama_context * ctx,
               const uint8_t * kv_cache,
                      size_t   n_size,
                         int   n_token_count) {
    // Make sure we have the same kv cache setup
    LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
    void * k_data = ctx->model.kv_self.k->data; // remember data pointers
    void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy
    memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
    ctx->model.kv_self.n = n_token_count;
}

int llama_eval(
        struct llama_context * ctx,
           const llama_token * tokens,
                         int   n_tokens,
                         int   n_past,
                         int   n_threads) {
    if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
        fprintf(stderr, "%s: failed to eval\n", __func__);
        return 1;
    }
    // get a more accurate load time, upon first eval
    if (!ctx->has_evaluated_once) {
        ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
        ctx->has_evaluated_once = true;
    }
    return 0;
}

int llama_tokenize(
        struct llama_context * ctx,
                  const char * text,
<|next_version|>
// ongoing prediction with the model.
const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.addr;
}

// Returns the size of the KV cache
size_t llama_get_kv_cache_size(struct llama_context * ctx) {
    return ctx->model.kv_self.buf.size;
}

int llama_get_kv_cache_token_count(struct llama_context * ctx) {
    return ctx->model.kv_self.n;
}

// Sets the KV cache containing the current context for the model
void llama_set_kv_cache(
        struct llama_context * ctx,
               const uint8_t * kv_cache,
                      size_t   n_size,
                         int   n_token_count) {
    // Make sure we have the same kv cache setup
    LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
    void * k_data = ctx->model.kv_self.k->data; // remember data pointers
    void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy
    memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
    ctx->model.kv_self.k->data = k_data; // restore correct data pointers
    ctx->model.kv_self.v->data = v_data;
    ctx->model.kv_self.n = n_token_count;
}

int llama_eval(
        struct llama_context * ctx,
           const llama_token * tokens,
                         int   n_tokens,
                         int   n_past,
                         int   n_threads) {
    if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
        fprintf(stderr, "%s: failed to eval\n", __func__);
        return 1;
    }
    // get a more accurate load time, upon first eval
    if (!ctx->has_evaluated_once) {
        ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
        ctx->has_evaluated_once = true;
    }
    return 0;
}

int llama_tokenize(
        struct llama_context * ctx,
                  const char * text,


Allow for text angle/gradient to be retrieved (#4070)

<|original_code|>
    , double_MEMBER(lstm_rating_coefficient, 5,
                    "Sets the rating coefficient for the lstm choices. The smaller the "
                    "coefficient, the better are the ratings for each choice and less "
                    "information is lost due to the cut off at 0. The standard value is "
                    "5",
                    this->params())
    , BOOL_MEMBER(pageseg_apply_music_mask, false,
                  "Detect music staff and remove intersecting components", this->params())
    ,

    backup_config_file_(nullptr)
    , pix_binary_(nullptr)
    , pix_grey_(nullptr)
    , pix_original_(nullptr)
    , pix_thresholds_(nullptr)
    , source_resolution_(0)
    , textord_(this)
    , right_to_left_(false)
    , scaled_color_(nullptr)
    , scaled_factor_(-1)
    , deskew_(1.0f, 0.0f)
    , reskew_(1.0f, 0.0f)
    , most_recently_used_(this)
    , font_table_size_(0)
#ifndef DISABLED_LEGACY_ENGINE
    , equ_detect_(nullptr)
#endif // ndef DISABLED_LEGACY_ENGINE
    , lstm_recognizer_(nullptr)
    , train_line_page_num_(0) {}

Tesseract::~Tesseract() {
  Clear();
  pix_original_.destroy();
  end_tesseract();
  for (auto *lang : sub_langs_) {
    delete lang;
  }
  delete lstm_recognizer_;
  lstm_recognizer_ = nullptr;
}

Dict &Tesseract::getDict() {
  if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {
    if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {
      return *lstm_recognizer_->GetDict();
    }
  }
  return Classify::getDict();
}

void Tesseract::Clear() {
  std::string debug_name = imagebasename + "_debug.pdf";
  pixa_debug_.WritePDF(debug_name.c_str());
  pix_binary_.destroy();
  pix_grey_.destroy();
  pix_thresholds_.destroy();
  scaled_color_.destroy();
  deskew_ = FCOORD(1.0f, 0.0f);
  reskew_ = FCOORD(1.0f, 0.0f);
  splitter_.Clear();
  scaled_factor_ = -1;
  for (auto &sub_lang : sub_langs_) {
    sub_lang->Clear();
  }
}

#ifndef DISABLED_LEGACY_ENGINE

void Tesseract::SetEquationDetect(EquationDetect *detector) {
  equ_detect_ = detector;
  equ_detect_->SetLangTesseract(this);
}

// Clear all memory of adaption for this and all subclassifiers.
void Tesseract::ResetAdaptiveClassifier() {
  ResetAdaptiveClassifierInternal();
  for (auto &sub_lang : sub_langs_) {
    sub_lang->ResetAdaptiveClassifierInternal();
  }
}

#endif // ndef DISABLED_LEGACY_ENGINE

<|edits_diff|>
--- src/ccmain/tesseractclass.cpp
+++ src/ccmain/tesseractclass.cpp
@@ -20,6 +20,7 @@
     , scaled_factor_(-1)
     , deskew_(1.0f, 0.0f)
     , reskew_(1.0f, 0.0f)
+    , gradient_(0.0f)
     , most_recently_used_(this)
     , font_table_size_(0)
 #ifndef DISABLED_LEGACY_ENGINE
<|current_version|>
    , double_MEMBER(lstm_rating_coefficient, 5,
                    "Sets the rating coefficient for the lstm choices. The smaller the "
                    "coefficient, the better are the ratings for each choice and less "
                    "information is lost due to the cut off at 0. The standard value is "
                    "5",
                    this->params())
    , BOOL_MEMBER(pageseg_apply_music_mask, false,
                  "Detect music staff and remove intersecting components", this->params())
    ,

    backup_config_file_(nullptr)
    , pix_binary_(nullptr)
    , pix_grey_(nullptr)
    , pix_original_(nullptr)
    , pix_thresholds_(nullptr)
    , source_resolution_(0)
    , textord_(this)
    , right_to_left_(false)
    , scaled_color_(nullptr)
    , scaled_factor_(-1)
    , deskew_(1.0f, 0.0f)
    , reskew_(1.0f, 0.0f)
    , gradient_(0.0f)
    , most_recently_used_(this)
    , font_table_size_(0)
#ifndef DISABLED_LEGACY_ENGINE
    , equ_detect_(nullptr)
#endif // ndef DISABLED_LEGACY_ENGINE
    , lstm_recognizer_(nullptr)
    , train_line_page_num_(0) {}

Tesseract::~Tesseract() {
  Clear();
  pix_original_.destroy();
  end_tesseract();
  for (auto *lang : sub_langs_) {
    delete lang;
  }
  delete lstm_recognizer_;
  lstm_recognizer_ = nullptr;
}

Dict &Tesseract::getDict() {
  if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {
    if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {
      return *lstm_recognizer_->GetDict();
    }
  }
  return Classify::getDict();
}

void Tesseract::Clear() {
  std::string debug_name = imagebasename + "_debug.pdf";
  pixa_debug_.WritePDF(debug_name.c_str());
  pix_binary_.destroy();
  pix_grey_.destroy();
  pix_thresholds_.destroy();
  scaled_color_.destroy();
  deskew_ = FCOORD(1.0f, 0.0f);
  reskew_ = FCOORD(1.0f, 0.0f);
  splitter_.Clear();
  scaled_factor_ = -1;
  for (auto &sub_lang : sub_langs_) {
    sub_lang->Clear();
  }
}

#ifndef DISABLED_LEGACY_ENGINE

void Tesseract::SetEquationDetect(EquationDetect *detector) {
  equ_detect_ = detector;
  equ_detect_->SetLangTesseract(this);
}

// Clear all memory of adaption for this and all subclassifiers.
void Tesseract::ResetAdaptiveClassifier() {
  ResetAdaptiveClassifierInternal();
  for (auto &sub_lang : sub_langs_) {
    sub_lang->ResetAdaptiveClassifierInternal();
  }
}

#endif // ndef DISABLED_LEGACY_ENGINE

<|next_version|>
    , double_MEMBER(lstm_rating_coefficient, 5,
                    "Sets the rating coefficient for the lstm choices. The smaller the "
                    "coefficient, the better are the ratings for each choice and less "
                    "information is lost due to the cut off at 0. The standard value is "
                    "5",
                    this->params())
    , BOOL_MEMBER(pageseg_apply_music_mask, false,
                  "Detect music staff and remove intersecting components", this->params())
    ,

    backup_config_file_(nullptr)
    , pix_binary_(nullptr)
    , pix_grey_(nullptr)
    , pix_original_(nullptr)
    , pix_thresholds_(nullptr)
    , source_resolution_(0)
    , textord_(this)
    , right_to_left_(false)
    , scaled_color_(nullptr)
    , scaled_factor_(-1)
    , deskew_(1.0f, 0.0f)
    , reskew_(1.0f, 0.0f)
    , gradient_(0.0f)
    , most_recently_used_(this)
    , font_table_size_(0)
#ifndef DISABLED_LEGACY_ENGINE
    , equ_detect_(nullptr)
#endif // ndef DISABLED_LEGACY_ENGINE
    , lstm_recognizer_(nullptr)
    , train_line_page_num_(0) {}

Tesseract::~Tesseract() {
  Clear();
  pix_original_.destroy();
  end_tesseract();
  for (auto *lang : sub_langs_) {
    delete lang;
  }
  delete lstm_recognizer_;
  lstm_recognizer_ = nullptr;
}

Dict &Tesseract::getDict() {
  if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {
    if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {
      return *lstm_recognizer_->GetDict();
    }
  }
  return Classify::getDict();
}

void Tesseract::Clear() {
  std::string debug_name = imagebasename + "_debug.pdf";
  pixa_debug_.WritePDF(debug_name.c_str());
  pix_binary_.destroy();
  pix_grey_.destroy();
  pix_thresholds_.destroy();
  scaled_color_.destroy();
  deskew_ = FCOORD(1.0f, 0.0f);
  reskew_ = FCOORD(1.0f, 0.0f);
  gradient_ = 0.0f;
  splitter_.Clear();
  scaled_factor_ = -1;
  for (auto &sub_lang : sub_langs_) {
    sub_lang->Clear();
  }
}

#ifndef DISABLED_LEGACY_ENGINE

void Tesseract::SetEquationDetect(EquationDetect *detector) {
  equ_detect_ = detector;
  equ_detect_->SetLangTesseract(this);
}

// Clear all memory of adaption for this and all subclassifiers.
void Tesseract::ResetAdaptiveClassifier() {
  ResetAdaptiveClassifierInternal();
  for (auto &sub_lang : sub_langs_) {
    sub_lang->ResetAdaptiveClassifierInternal();
  }
}

#endif // ndef DISABLED_LEGACY_ENGINE


Fix vector resize with init for all elements (issue #3473) (#3474)

<|original_code|>
}

// Computes the precise bounding box of the coords that are generated by
// GetEdgeCoords. This may be different from the bounding box of the polygon.
void TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {
  TBOX box = bounding_box();
  *precise_box = TBOX();
  CollectEdges(box, precise_box, nullptr, nullptr, nullptr);
  precise_box->move(box.botleft());
}

// Adds edges to the given vectors.
// For all the edge steps in all the outlines, or polygonal approximation
// where there are no edge steps, collects the steps into x_coords/y_coords.
// x_coords is a collection of the x-coords of vertical edges for each
// y-coord starting at box.bottom().
// y_coords is a collection of the y-coords of horizontal edges for each
// x-coord starting at box.left().
// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.
// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
void TBLOB::GetEdgeCoords(const TBOX &box, std::vector<std::vector<int>> &x_coords,
                          std::vector<std::vector<int>> &y_coords) const {
  x_coords.resize(box.height());
  y_coords.resize(box.width());
  CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);
  // Sort the output vectors.
  for (auto &coord : x_coords) {
    std::sort(coord.begin(), coord.end());
  }
  for (auto &coord : y_coords) {
    std::sort(coord.begin(), coord.end());
  }
}

// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over
// the integer coordinate grid to properly weight long vectors.
static void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {
  FCOORD step(pt2);
  step -= pt1;
  int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));
  int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));
  int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));
  int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));
  if (xstart == xend && ystart == yend) {
    return; // Nothing to do.
  }
  double weight = step.length() / (xend - xstart + yend - ystart);
<|edits_diff|>
--- src/ccstruct/blobs.cpp
+++ src/ccstruct/blobs.cpp
@@ -20,6 +20,7 @@
 // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
 void TBLOB::GetEdgeCoords(const TBOX &box, std::vector<std::vector<int>> &x_coords,
                           std::vector<std::vector<int>> &y_coords) const {
+  x_coords.clear();
   x_coords.resize(box.height());
   y_coords.resize(box.width());
   CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);
<|current_version|>
}

// Computes the precise bounding box of the coords that are generated by
// GetEdgeCoords. This may be different from the bounding box of the polygon.
void TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {
  TBOX box = bounding_box();
  *precise_box = TBOX();
  CollectEdges(box, precise_box, nullptr, nullptr, nullptr);
  precise_box->move(box.botleft());
}

// Adds edges to the given vectors.
// For all the edge steps in all the outlines, or polygonal approximation
// where there are no edge steps, collects the steps into x_coords/y_coords.
// x_coords is a collection of the x-coords of vertical edges for each
// y-coord starting at box.bottom().
// y_coords is a collection of the y-coords of horizontal edges for each
// x-coord starting at box.left().
// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.
// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
void TBLOB::GetEdgeCoords(const TBOX &box, std::vector<std::vector<int>> &x_coords,
                          std::vector<std::vector<int>> &y_coords) const {
  x_coords.clear();
  x_coords.resize(box.height());
  y_coords.resize(box.width());
  CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);
  // Sort the output vectors.
  for (auto &coord : x_coords) {
    std::sort(coord.begin(), coord.end());
  }
  for (auto &coord : y_coords) {
    std::sort(coord.begin(), coord.end());
  }
}

// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over
// the integer coordinate grid to properly weight long vectors.
static void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {
  FCOORD step(pt2);
  step -= pt1;
  int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));
  int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));
  int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));
  int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));
  if (xstart == xend && ystart == yend) {
    return; // Nothing to do.
  }
  double weight = step.length() / (xend - xstart + yend - ystart);
<|next_version|>
}

// Computes the precise bounding box of the coords that are generated by
// GetEdgeCoords. This may be different from the bounding box of the polygon.
void TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {
  TBOX box = bounding_box();
  *precise_box = TBOX();
  CollectEdges(box, precise_box, nullptr, nullptr, nullptr);
  precise_box->move(box.botleft());
}

// Adds edges to the given vectors.
// For all the edge steps in all the outlines, or polygonal approximation
// where there are no edge steps, collects the steps into x_coords/y_coords.
// x_coords is a collection of the x-coords of vertical edges for each
// y-coord starting at box.bottom().
// y_coords is a collection of the y-coords of horizontal edges for each
// x-coord starting at box.left().
// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.
// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
void TBLOB::GetEdgeCoords(const TBOX &box, std::vector<std::vector<int>> &x_coords,
                          std::vector<std::vector<int>> &y_coords) const {
  x_coords.clear();
  x_coords.resize(box.height());
  y_coords.clear();
  y_coords.resize(box.width());
  CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);
  // Sort the output vectors.
  for (auto &coord : x_coords) {
    std::sort(coord.begin(), coord.end());
  }
  for (auto &coord : y_coords) {
    std::sort(coord.begin(), coord.end());
  }
}

// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over
// the integer coordinate grid to properly weight long vectors.
static void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {
  FCOORD step(pt2);
  step -= pt1;
  int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));
  int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));
  int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));
  int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));
  if (xstart == xend && ystart == yend) {
    return; // Nothing to do.
  }
  double weight = step.length() / (xend - xstart + yend - ystart);