EditPage.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "pch.h"
  2. #include "EditPage.h"
  3. #if __has_include("EditPage.g.cpp")
  4. #include "EditPage.g.cpp"
  5. #endif
  6. using namespace winrt;
  7. using namespace winrt::Windows::Storage::Streams;
  8. using namespace winrt::Windows::UI::Text;
  9. namespace winrt::Maple_App::implementation
  10. {
  11. EditPage::EditPage()
  12. {
  13. InitializeComponent();
  14. }
  15. fire_and_forget EditPage::OnNavigatedTo(NavigationEventArgs const& e) {
  16. const auto lifetime = get_strong();
  17. const auto& param = e.Parameter().as<Maple_App::ConfigViewModel>();
  18. m_file = param.File();
  19. const auto& text = co_await FileIO::ReadTextAsync(param.File(), UnicodeEncoding::Utf8);
  20. EditBox().Document().SetText(TextSetOptions::None, text);
  21. const auto weakThis = lifetime->get_weak();
  22. m_saveModifiedContent = [weakThis]() -> IAsyncAction {
  23. if (const auto self{ weakThis.get() }) {
  24. return self->SaveDocument();
  25. }
  26. return {};
  27. };
  28. }
  29. void EditPage::OnNavigatingFrom(NavigatingCancelEventArgs const&) {
  30. if (m_file == nullptr || !m_file.IsAvailable()) {
  31. return;
  32. }
  33. SaveDocument();
  34. }
  35. void EditPage::EditBox_TextChanging(IInspectable const&, RichEditBoxTextChangingEventArgs const&)
  36. {
  37. if (m_loaded == 2) {
  38. SaveModifiedContent = m_saveModifiedContent;
  39. SaveButton().IsEnabled(true);
  40. }
  41. else {
  42. m_loaded++;
  43. }
  44. }
  45. void EditPage::SaveButton_Click(IInspectable const&, RoutedEventArgs const&) {
  46. SaveDocument();
  47. }
  48. void EditPage::HelpButton_Click(IInspectable const&, RoutedEventArgs const&) {
  49. const auto _ = winrt::Windows::System::Launcher::LaunchUriAsync(Uri{ L"https://github.com/eycorsican/leaf/blob/master/README.zh.md" });
  50. }
  51. IAsyncAction EditPage::SaveDocument()
  52. {
  53. if (!SaveButton().IsEnabled()) {
  54. co_return;
  55. }
  56. SaveModifiedContent = nullptr;
  57. SaveButton().IsEnabled(false);
  58. hstring content{};
  59. EditBox().Document().GetText(TextGetOptions::NoHidden | TextGetOptions::UseCrlf | TextGetOptions::AllowFinalEop, content);
  60. const auto data = to_string(content);
  61. co_return co_await FileIO::WriteBytesAsync(
  62. m_file,
  63. std::vector<uint8_t>(data.begin(), data.end()));
  64. }
  65. }