EditPage.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. try {
  20. const auto& text = co_await FileIO::ReadTextAsync(param.File(), UnicodeEncoding::Utf8);
  21. EditBox().Document().SetText(TextSetOptions::None, text);
  22. }
  23. catch (const winrt::hresult_error&) {
  24. EditBox().Document().SetText(TextSetOptions::None, L"Invalid configuration file");
  25. }
  26. const auto weakThis = lifetime->get_weak();
  27. m_saveModifiedContent = [weakThis]() -> IAsyncAction {
  28. if (const auto self{ weakThis.get() }) {
  29. return self->SaveDocument();
  30. }
  31. return {};
  32. };
  33. }
  34. void EditPage::OnNavigatingFrom(NavigatingCancelEventArgs const&) {
  35. if (m_file == nullptr || !m_file.IsAvailable()) {
  36. return;
  37. }
  38. SaveDocument();
  39. }
  40. void EditPage::EditBox_TextChanging(IInspectable const&, RichEditBoxTextChangingEventArgs const&)
  41. {
  42. if (m_loaded == 2) {
  43. SaveModifiedContent = m_saveModifiedContent;
  44. SaveButton().IsEnabled(true);
  45. }
  46. else {
  47. m_loaded++;
  48. }
  49. }
  50. void EditPage::SaveButton_Click(IInspectable const&, RoutedEventArgs const&) {
  51. SaveDocument();
  52. }
  53. void EditPage::HelpButton_Click(IInspectable const&, RoutedEventArgs const&) {
  54. const auto _ = winrt::Windows::System::Launcher::LaunchUriAsync(Uri{ L"https://github.com/eycorsican/leaf/blob/master/README.zh.md" });
  55. }
  56. IAsyncAction EditPage::SaveDocument()
  57. {
  58. if (!SaveButton().IsEnabled()) {
  59. co_return;
  60. }
  61. SaveModifiedContent = nullptr;
  62. SaveButton().IsEnabled(false);
  63. hstring content{};
  64. EditBox().Document().GetText(TextGetOptions::NoHidden | TextGetOptions::UseCrlf | TextGetOptions::AllowFinalEop, content);
  65. const auto data = to_string(content);
  66. co_return co_await FileIO::WriteBytesAsync(
  67. m_file,
  68. std::vector<uint8_t>(data.begin(), data.end()));
  69. }
  70. }