ImportDialog.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ImportDialog.h"
  7. #include "Spreadsheet.h"
  8. #include <AK/JsonParser.h>
  9. #include <AK/LexicalPath.h>
  10. #include <Applications/Spreadsheet/CSVImportGML.h>
  11. #include <Applications/Spreadsheet/FormatSelectionPageGML.h>
  12. #include <LibCore/File.h>
  13. #include <LibGUI/Application.h>
  14. #include <LibGUI/CheckBox.h>
  15. #include <LibGUI/ComboBox.h>
  16. #include <LibGUI/ItemListModel.h>
  17. #include <LibGUI/RadioButton.h>
  18. #include <LibGUI/StackWidget.h>
  19. #include <LibGUI/TableView.h>
  20. #include <LibGUI/TextBox.h>
  21. #include <LibGUI/Window.h>
  22. #include <LibGUI/Wizards/WizardDialog.h>
  23. #include <LibGUI/Wizards/WizardPage.h>
  24. namespace Spreadsheet {
  25. CSVImportDialogPage::CSVImportDialogPage(StringView csv)
  26. : m_csv(csv)
  27. {
  28. m_page = GUI::WizardPage::construct(
  29. "CSV Import Options",
  30. "Please select the options for the csv file you wish to import");
  31. m_page->body_widget().load_from_gml(csv_import_gml);
  32. m_page->set_is_final_page(true);
  33. m_delimiter_comma_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_comma_radio");
  34. m_delimiter_semicolon_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_semicolon_radio");
  35. m_delimiter_tab_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_tab_radio");
  36. m_delimiter_space_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_space_radio");
  37. m_delimiter_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_other_radio");
  38. m_delimiter_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("delimiter_other_text_box");
  39. m_quote_single_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_single_radio");
  40. m_quote_double_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_double_radio");
  41. m_quote_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_other_radio");
  42. m_quote_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("quote_other_text_box");
  43. m_quote_escape_combo_box = m_page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("quote_escape_combo_box");
  44. m_read_header_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("read_header_check_box");
  45. m_trim_leading_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_leading_field_spaces_check_box");
  46. m_trim_trailing_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_trailing_field_spaces_check_box");
  47. m_data_preview_table_view = m_page->body_widget().find_descendant_of_type_named<GUI::TableView>("data_preview_table_view");
  48. m_data_preview_error_label = m_page->body_widget().find_descendant_of_type_named<GUI::Label>("data_preview_error_label");
  49. m_data_preview_widget = m_page->body_widget().find_descendant_of_type_named<GUI::StackWidget>("data_preview_widget");
  50. m_quote_escape_combo_box->set_model(GUI::ItemListModel<String>::create(m_quote_escape_items));
  51. // By default, use commas, double quotes with repeat, and disable headers.
  52. m_delimiter_comma_radio->set_checked(true);
  53. m_quote_double_radio->set_checked(true);
  54. m_quote_escape_combo_box->set_selected_index(0); // Repeat
  55. m_delimiter_comma_radio->on_checked = [&](auto) { update_preview(); };
  56. m_delimiter_semicolon_radio->on_checked = [&](auto) { update_preview(); };
  57. m_delimiter_tab_radio->on_checked = [&](auto) { update_preview(); };
  58. m_delimiter_space_radio->on_checked = [&](auto) { update_preview(); };
  59. m_delimiter_other_radio->on_checked = [&](auto) { update_preview(); };
  60. m_delimiter_other_text_box->on_change = [&] {
  61. if (m_delimiter_other_radio->is_checked())
  62. update_preview();
  63. };
  64. m_quote_single_radio->on_checked = [&](auto) { update_preview(); };
  65. m_quote_double_radio->on_checked = [&](auto) { update_preview(); };
  66. m_quote_other_radio->on_checked = [&](auto) { update_preview(); };
  67. m_quote_other_text_box->on_change = [&] {
  68. if (m_quote_other_radio->is_checked())
  69. update_preview();
  70. };
  71. m_quote_escape_combo_box->on_change = [&](auto&, auto&) { update_preview(); };
  72. m_read_header_check_box->on_checked = [&](auto) { update_preview(); };
  73. m_trim_leading_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  74. m_trim_trailing_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  75. update_preview();
  76. }
  77. auto CSVImportDialogPage::make_reader() -> Optional<Reader::XSV>
  78. {
  79. String delimiter;
  80. String quote;
  81. Reader::ParserTraits::QuoteEscape quote_escape;
  82. // Delimiter
  83. if (m_delimiter_other_radio->is_checked())
  84. delimiter = m_delimiter_other_text_box->text();
  85. else if (m_delimiter_comma_radio->is_checked())
  86. delimiter = ",";
  87. else if (m_delimiter_semicolon_radio->is_checked())
  88. delimiter = ";";
  89. else if (m_delimiter_tab_radio->is_checked())
  90. delimiter = "\t";
  91. else if (m_delimiter_space_radio->is_checked())
  92. delimiter = " ";
  93. else
  94. return {};
  95. // Quote separator
  96. if (m_quote_other_radio->is_checked())
  97. quote = m_quote_other_text_box->text();
  98. else if (m_quote_single_radio->is_checked())
  99. quote = "'";
  100. else if (m_quote_double_radio->is_checked())
  101. quote = "\"";
  102. else
  103. return {};
  104. // Quote escape
  105. auto index = m_quote_escape_combo_box->selected_index();
  106. if (index == 0)
  107. quote_escape = Reader::ParserTraits::Repeat;
  108. else if (index == 1)
  109. quote_escape = Reader::ParserTraits::Backslash;
  110. else
  111. return {};
  112. auto should_read_headers = m_read_header_check_box->is_checked();
  113. auto should_trim_leading = m_trim_leading_field_spaces_check_box->is_checked();
  114. auto should_trim_trailing = m_trim_trailing_field_spaces_check_box->is_checked();
  115. if (quote.is_empty() || delimiter.is_empty())
  116. return {};
  117. Reader::ParserTraits traits {
  118. move(delimiter),
  119. move(quote),
  120. quote_escape,
  121. };
  122. auto behaviors = Reader::default_behaviors() | Reader::ParserBehavior::Lenient;
  123. if (should_read_headers)
  124. behaviors = behaviors | Reader::ParserBehavior::ReadHeaders;
  125. if (should_trim_leading)
  126. behaviors = behaviors | Reader::ParserBehavior::TrimLeadingFieldSpaces;
  127. if (should_trim_trailing)
  128. behaviors = behaviors | Reader::ParserBehavior::TrimTrailingFieldSpaces;
  129. return Reader::XSV(m_csv, move(traits), behaviors);
  130. };
  131. void CSVImportDialogPage::update_preview()
  132. {
  133. m_previously_made_reader = make_reader();
  134. if (!m_previously_made_reader.has_value()) {
  135. m_data_preview_table_view->set_model(nullptr);
  136. m_data_preview_error_label->set_text("Could not read the given file");
  137. m_data_preview_widget->set_active_widget(m_data_preview_error_label);
  138. return;
  139. }
  140. auto& reader = *m_previously_made_reader;
  141. if (reader.has_error()) {
  142. m_data_preview_table_view->set_model(nullptr);
  143. m_data_preview_error_label->set_text(String::formatted("XSV parse error:\n{}", reader.error_string()));
  144. m_data_preview_widget->set_active_widget(m_data_preview_error_label);
  145. return;
  146. }
  147. auto headers = reader.headers();
  148. m_data_preview_table_view->set_model(
  149. GUI::ItemListModel<Reader::XSV::Row, Reader::XSV, Vector<String>>::create(reader, headers, min(8ul, reader.size())));
  150. m_data_preview_widget->set_active_widget(m_data_preview_table_view);
  151. m_data_preview_table_view->update();
  152. }
  153. Result<NonnullRefPtrVector<Sheet>, String> ImportDialog::make_and_run_for(GUI::Window& parent, StringView mime, Core::File& file, Workbook& workbook)
  154. {
  155. auto wizard = GUI::WizardDialog::construct(&parent);
  156. wizard->set_title("File Import Wizard");
  157. wizard->set_icon(GUI::Icon::default_icon("app-spreadsheet").bitmap_for_size(16));
  158. auto import_xsv = [&]() -> Result<NonnullRefPtrVector<Sheet>, String> {
  159. auto contents = file.read_all();
  160. CSVImportDialogPage page { contents };
  161. wizard->replace_page(page.page());
  162. auto result = wizard->exec();
  163. if (result == GUI::Dialog::ExecResult::OK) {
  164. auto& reader = page.reader();
  165. NonnullRefPtrVector<Sheet> sheets;
  166. if (reader.has_value()) {
  167. reader->parse();
  168. if (reader.value().has_error())
  169. return String::formatted("CSV Import failed: {}", reader.value().error_string());
  170. auto sheet = Sheet::from_xsv(reader.value(), workbook);
  171. if (sheet)
  172. sheets.append(sheet.release_nonnull());
  173. }
  174. return sheets;
  175. } else {
  176. return String { "CSV Import was cancelled" };
  177. }
  178. };
  179. auto import_worksheet = [&]() -> Result<NonnullRefPtrVector<Sheet>, String> {
  180. auto json_value_option = JsonParser(file.read_all()).parse();
  181. if (json_value_option.is_error()) {
  182. StringBuilder sb;
  183. sb.append("Failed to parse ");
  184. sb.append(file.filename());
  185. return sb.to_string();
  186. }
  187. auto& json_value = json_value_option.value();
  188. if (!json_value.is_array()) {
  189. StringBuilder sb;
  190. sb.append("Did not find a spreadsheet in ");
  191. sb.append(file.filename());
  192. return sb.to_string();
  193. }
  194. NonnullRefPtrVector<Sheet> sheets;
  195. auto& json_array = json_value.as_array();
  196. json_array.for_each([&](auto& sheet_json) {
  197. if (!sheet_json.is_object())
  198. return IterationDecision::Continue;
  199. if (auto sheet = Sheet::from_json(sheet_json.as_object(), workbook))
  200. sheets.append(sheet.release_nonnull());
  201. return IterationDecision::Continue;
  202. });
  203. return sheets;
  204. };
  205. if (mime == "text/csv") {
  206. return import_xsv();
  207. } else if (mime == "text/plain" && file.filename().ends_with(".sheets")) {
  208. return import_worksheet();
  209. } else {
  210. auto page = GUI::WizardPage::construct(
  211. "Import File Format",
  212. String::formatted("Select the format you wish to import '{}' as", LexicalPath::basename(file.filename())));
  213. page->on_next_page = [] { return nullptr; };
  214. page->body_widget().load_from_gml(select_format_page_gml);
  215. auto format_combo_box = page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("select_format_page_format_combo_box");
  216. Vector<String> supported_formats {
  217. "CSV (text/csv)",
  218. "Spreadsheet Worksheet",
  219. };
  220. format_combo_box->set_model(GUI::ItemListModel<String>::create(supported_formats));
  221. wizard->push_page(page);
  222. if (wizard->exec() != GUI::Dialog::ExecResult::OK)
  223. return String { "Import was cancelled" };
  224. if (format_combo_box->selected_index() == 0)
  225. return import_xsv();
  226. if (format_combo_box->selected_index() == 1)
  227. return import_worksheet();
  228. VERIFY_NOT_REACHED();
  229. }
  230. }
  231. };