struct System { TSFrame *frame {nullptr}; wxString defaultfont { #ifdef WIN32 "Lucida Sans Unicode" #else "Verdana" #endif }; wxString defaultfixedfont {"Courier New"}; wxString defaultlang {wxEmptyString}; wxString searchstring; unique_ptr cfg; wxArrayString scripts; wxArrayString templates; // TreeSheets files that File > New from Template copies wxString lastopenfile; Evaluator evaluator; wxString clipboardcopy; unique_ptr cellclipboard; int cellclipboardcolwidth {0}; // Column width of a single copied cell. vector> imagelist; vector loadimageids; uchar versionlastloaded {0}; wxLongLong fakelasteditonload; wxPen pen_tinytext {wxColour(0x808080UL)}; wxPen pen_gridborder {wxColour(0xb5a6a4)}; wxPen pen_thinselect {*wxLIGHT_GREY}; wxPen pen_tinygridlines; wxPen pen_gridlines; wxColour rubberbandcolor; wxPen pen_rubberband; wxBrush brush_rubberband; int roundness {3}; int defaultmaxcolwidth {80}; bool makebaks {true}; bool totray {false}; bool autosave {true}; bool savedismiss {false}; bool globalkey {false}; #ifdef __WXMAC__ wxString globalkeyname {"RAWCTRL+ALT+SHIFT+SPACE"}; #else wxString globalkeyname {"CTRL+ALT+SHIFT+SPACE"}; #endif bool zoomscroll {false}; bool thinselc {true}; bool hoverzoom {false}; bool hovershadow {false}; bool formulasseen {false}; // whether any cell has been a formula, see Cell::SyncFormula() bool minclose {false}; bool singletray {false}; bool bottomtabs {true}; bool startminimized {false}; bool centered {true}; bool fswatch {true}; // The global autoexport settings from before they became per document (file version 30), // for documents loaded from older files. int autohtmlexport {0}; bool autopdfexport {false}; int defaultimageformat {0}; bool casesensitivesearch {true}; bool darkennonmatchingcells {false}; bool fastrender {true}; bool shrinktext {true}; bool showtoolbar {true}; bool showstatusbar {true}; bool followdarkmode {false}; bool innerbordercolor {false}; bool restrictview {false}; bool flatcopy {false}; bool filtershowrows {false}; bool filtershowsubgrids {false}; bool filterunion {false}; uint colormask {0}; int notesizex {300}; int notesizey {255}; std::set watchedpaths; bool insidefiledialog {false}; struct TimerStruct : wxTimer { void Notify() override { sys->SaveCheck(); sys->cfg->Flush(); } } every_second_timer; int lastcellcolor {0xFFFFFF}; int lasttextcolor {0}; int lastbordcolor {0xA0A0A0}; Image *lastimage {nullptr}; int customcolor {0}; int cursorcolor {0}; int hovershadowcolor {0}; int searchcolor {0}; int linkcolor {0}; int operationcolor {0}; int varassigncolor {0}; int varreadcolor {0}; int viewcolor {0}; struct ColorSetting { const char *key; int System::*color; int def; wxString label; }; // The colors of Options > Colors..., with their settings keys and defaults. static vector ColorSettings() { return {{"cursorcolor", &System::cursorcolor, 0x00FF00, _("Cursor")}, {"hovershadowcolor", &System::hovershadowcolor, 0x808080, _("Hover shadow")}, {"searchcolor", &System::searchcolor, 0x0000FF, _("Search results")}, {"linkcolor", &System::linkcolor, 0xCC6600, _("Links")}, {"operationcolor", &System::operationcolor, 0x8080FF, _("Operations")}, {"varassigncolor", &System::varassigncolor, 0xFF8080, _("Variable assignments")}, {"varreadcolor", &System::varreadcolor, 0xFFA0A0, _("Variable reads")}, {"viewcolor", &System::viewcolor, 0x80FF80, _("Views")}, {"customcolor", &System::customcolor, 0xFFFFFF, _("Custom dropdown color")}}; } System(bool portable) : cfg(portable ? new wxFileConfig("", "", wxGetCwd() + "/TreeSheets.ini", "", 0) : new wxFileConfig("TreeSheets")) { static const wxDash tspattern[] = {2, 4}; pen_thinselect.SetDashes(2, tspattern); pen_thinselect.SetStyle(wxPENSTYLE_USER_DASH); roundness = static_cast(cfg->Read("roundness", roundness)); autohtmlexport = static_cast(cfg->Read("autohtmlexport", autohtmlexport)); cfg->Read("autopdfexport", &autopdfexport, autopdfexport); defaultimageformat = static_cast(cfg->Read("defaultimageformat", defaultimageformat)); defaultfont = cfg->Read("defaultfont", defaultfont); defaultfixedfont = cfg->Read("defaultfixedfont", defaultfixedfont); defaultlang = cfg->Read("defaultlang", defaultlang); cfg->Read("defaultmaxcolwidth", &defaultmaxcolwidth, defaultmaxcolwidth); cfg->Read("makebaks", &makebaks, makebaks); cfg->Read("totray", &totray, totray); cfg->Read("zoomscroll", &zoomscroll, zoomscroll); cfg->Read("thinselc", &thinselc, thinselc); cfg->Read("hoverzoom", &hoverzoom, hoverzoom); cfg->Read("hovershadow", &hovershadow, hovershadow); cfg->Read("autosave", &autosave, autosave); cfg->Read("savedismiss", &savedismiss, savedismiss); cfg->Read("globalkey", &globalkey, globalkey); globalkeyname = cfg->Read("globalkeyname", globalkeyname); cfg->Read("fastrender", &fastrender, fastrender); cfg->Read("shrinktext", &shrinktext, shrinktext); cfg->Read("innerbordercolor", &innerbordercolor, innerbordercolor); cfg->Read("followdarkmode", &followdarkmode, followdarkmode); cfg->Read("minclose", &minclose, minclose); cfg->Read("singletray", &singletray, singletray); cfg->Read("bottomtabs", &bottomtabs, bottomtabs); cfg->Read("startminimized", &startminimized, startminimized); cfg->Read("centered", ¢ered, centered); cfg->Read("fswatch", &fswatch, fswatch); cfg->Read("casesensitivesearch", &casesensitivesearch, casesensitivesearch); cfg->Read("restrictview", &restrictview, restrictview); cfg->Read("flatcopy", &flatcopy, flatcopy); cfg->Read("filtershowrows", &filtershowrows, filtershowrows); cfg->Read("filtershowsubgrids", &filtershowsubgrids, filtershowsubgrids); cfg->Read("filterunion", &filterunion, filterunion); cfg->Read("defaultfontsize", &g_deftextsize_default, g_deftextsize_default); g_deftextsize = g_deftextsize_default; for (const auto &cs : ColorSettings()) { cfg->Read(cs.key, &(this->*cs.color), cs.def); } cfg->Read("showtoolbar", &showtoolbar, showtoolbar); cfg->Read("showstatusbar", &showstatusbar, showstatusbar); cfg->Read("notesizex", ¬esizex, notesizex); cfg->Read("notesizey", ¬esizey, notesizey); cfg->Read("lastcellcolor", &lastcellcolor, lastcellcolor); cfg->Read("lasttextcolor", &lasttextcolor, lasttextcolor); cfg->Read("lastbordcolor", &lastbordcolor, lastbordcolor); #ifdef ENABLE_LOBSTER ReadList("script", scripts); #endif ReadList("template", templates); // fsw.Connect(wxID_ANY, wxID_ANY, wxEVT_FSWATCHER, // wxFileSystemWatcherEventHandler(System::OnFileChanged)); } void UpdatePens() { colormask = (followdarkmode && wxSystemSettings::GetAppearance().IsDark()) ? 0x00FFFFFF : 0; pen_tinygridlines = wxPen(wxColour(LightColor(0xf2dcd8UL))); pen_gridlines = wxPen(wxColour(LightColor(0xe5b7b0UL))); static const wxDash glpattern[] = {1, 3}; pen_gridlines.SetDashes(2, glpattern); pen_gridlines.SetStyle(wxPENSTYLE_USER_DASH); rubberbandcolor = LightColor(0x000000); brush_rubberband = wxBrush(rubberbandcolor); pen_rubberband = wxPen(rubberbandcolor); } Document *NewTabDoc(bool append = false, int insert_at = -1) const { auto doc = make_unique(); auto *canvas = frame->NewTab(std::move(doc), append, insert_at); return canvas->doc.get(); } void Init(const wxString &filename) { evaluator.Init(); auto numfiles = static_cast(cfg->Read("numopenfiles", static_cast(0))); lastopenfile = cfg->Read("lastopenfile", ""); int selection = -1; vector loaded; // per remembered file: its page index, or -1 loop(i, numfiles) { wxString filename; cfg->Read(wxString::Format("lastopenfile_%d", i), &filename); loaded.push_back(LoadDB(filename).IsEmpty() ? static_cast(frame->notebook->GetPageCount()) - 1 : -1); if (filename == lastopenfile) { selection = loaded.back(); } } // Restore the tab groups as saved by RememberOpenFiles(). struct : wxAuiBookDeserializer { vector loaded; wxString layout; vector LoadNotebookTabs(const wxString &) override { vector tabs; for (auto &group : wxSplit(layout, ';')) { vector v; for (auto &n : wxSplit(group, ' ')) { v.push_back(wxAtoi(n)); } if (v.size() < 7) { continue; } auto page = [&](int file) { return file >= 0 && file < ssize(loaded) ? loaded[file] : -1; }; auto &tab = tabs.emplace_back(); tab.dock_direction = v[0]; tab.dock_layer = v[1]; tab.dock_row = v[2]; tab.dock_pos = v[3]; tab.dock_proportion = v[4]; tab.dock_size = v[5]; tab.active = max(page(v[6]), 0); for (auto f = v.begin() + 7; f != v.end(); f++) { if (auto p = page(*f); p >= 0) { tab.pages.push_back(p); } } if (tab.pages.empty() && tab.dock_direction != wxAUI_DOCK_CENTER) { tabs.pop_back(); } } return tabs; } } deserializer; deserializer.loaded = std::move(loaded); deserializer.layout = cfg->Read("tablayout", ""); frame->notebook->LoadLayout("notebook", deserializer); if (!filename.IsEmpty()) { Open(filename); } else if (selection >= 0) { frame->notebook->SetSelection(selection); } // LoadLayout() activates the saved tab without a page changed event. if (auto *canvas = frame->GetCurrentTab()) { frame->ActivateTab(canvas); } if (frame->notebook->GetPageCount() == 0U) { LoadTutorial(); } if (frame->notebook->GetPageCount() == 0U) { InitDB(10); } // Refresh(); every_second_timer.Start(1000); } void LoadTutorial() { if (sys->defaultlang == "en") { LoadDB(frame->app->GetDocPath("examples/tutorial.cts")); return; } auto *trans = wxTranslations::Get(); auto language = trans != nullptr ? trans->GetBestTranslation("ts") : wxString(""); if (language.Len() == 5 && !LoadDB(frame->app->GetDocPath("examples/tutorial-" + language + ".cts"))[0]) { return; } language.Truncate(2); if (language.Len() == 2 && !LoadDB(frame->app->GetDocPath("examples/tutorial-" + language + ".cts"))[0]) { return; } LoadDB(frame->app->GetDocPath("examples/tutorial.cts")); } void LoadOpRef() { LoadDB(frame->app->GetDocPath("examples/operation-reference.cts")); } unique_ptr &InitDB(int sizex, int sizey = 0) const { unique_ptr c = make_unique( nullptr, nullptr, CT_DATA, make_shared(sizex, sizey != 0 ? sizey : sizex)); c->cellcolor = 0xCCDCE2; c->grid->InitCells(); auto *doc = NewTabDoc(); doc->InitWith(std::move(c), "", nullptr, 1, 1); doc->UpdateLayout(); doc->ScrollIfSelectionOutOfView(); doc->canvas->Refresh(); return doc->root; } static wxString BakName(const wxString &filename) { return ExtName(filename, ".bak"); } static wxString TmpName(const wxString &filename) { return ExtName(filename, ".tmp"); } static wxString NewName(const wxString &filename) { return filename + ".new"; } static wxString ExtName(const wxString &filename, const wxString &ext) { wxFileName fn(filename); return fn.GetPathWithSep() + fn.GetName() + ext; } // An encrypted file is decrypted with password if given, or else asks for it. As a template, // the file becomes a new document without a filename, also when it is open already. wxString LoadDB(const wxString &filename, bool fromreload = false, int insert_at = -1, const wxString *password = nullptr, bool astemplate = false) { auto fn = filename; auto loadedfromtmp = false; if (!fromreload && !astemplate) { if (frame->GetTabByFileName(filename) != nullptr) { return wxEmptyString; //"this file is already loaded"; } if (::wxFileExists(TmpName(filename))) { if (::wxMessageBox( _("A temporary autosave file exists, would you like to load it instead?"), _("Autosave load"), wxYES_NO, frame) == wxYES) { fn = TmpName(filename); loadedfromtmp = true; } } } Document *doc = nullptr; auto anyimagesfailed = false; auto start_loading_time = wxGetLocalTimeMillis(); int zoomlevel = 0; { // limit destructors wxBusyCursor wait; Cell *ics = nullptr; unique_ptr ffisp; if (auto *file = ::wxFileExists(fn) ? nullptr : GetEmbeddedExample(fn)) { ffisp = make_unique(file->data, file->size); } else { ffisp = make_unique(fn); } auto &ffis = *ffisp; if (!ffis.IsOk()) { for (int i = static_cast(frame->filehistory.GetCount()) - 1; i >= 0; i--) { if (frame->filehistory.GetHistoryFile(i) == filename) { frame->filehistory.RemoveFileFromHistory(i); } } return _("Cannot open file."); } char buf[4]; ffis.Read(buf, 4); if (strncmp(buf, "TSFF", 4) != 0) { return _("Not a TreeSheets file."); } ffis.Read(&versionlastloaded, 1); if (versionlastloaded > TS_VERSION) { return _("File of newer version."); } unique_ptr encryption; vector body; if (versionlastloaded >= 30) { auto method = ffis.GetC(); if (method == Encryption::method) { encryption = make_unique(); if (!encryption->Read(ffis, versionlastloaded, body)) { return _("File corrupted!"); } if (password && !encryption->Decrypt(*password, body)) { return _("Wrong password (or the file is corrupted)."); } for (auto prompt = wxString::Format(_("Password for %s:"), filename); !password;) { wxPasswordEntryDialog dlg(frame, prompt, _("Encrypted document")); if (dlg.ShowModal() != wxID_OK) { return _("Open file cancelled."); } start_loading_time = wxGetLocalTimeMillis(); if (encryption->Decrypt(dlg.GetValue(), body)) { break; } prompt = wxString::Format( _("Wrong password (or the file is corrupted). Password for %s:"), filename); } } else if (method != 0) { return _("File corrupted!"); } } // Of an encrypted file, the decrypted rest. wxMemoryInputStream mis(body.data(), body.size()); auto &fis = encryption ? static_cast(mis) : ffis; wxDataInputStream dis(fis); auto xs = versionlastloaded >= 21 ? dis.Read8() : 1; auto ys = versionlastloaded >= 21 ? dis.Read8() : 1; zoomlevel = versionlastloaded >= 23 ? dis.Read8() : 0; auto autoexport = versionlastloaded >= 30 ? dis.Read8() : autohtmlexport | static_cast(autopdfexport) << 2; fakelasteditonload = wxDateTime::Now().GetValue(); loadimageids.clear(); for (;;) { fis.Read(buf, 1); // Read() leaves buf untouched at EOF, so without this a truncated file would keep // seeing the previous block header and loop forever. if (fis.LastRead() != 1) { return _("File corrupted!"); } switch (*buf) { case 'I': case 'J': { char iti = *buf; if (!imagetypes.contains(iti)) { return _("Found an image type that is not defined in this program."); } if (versionlastloaded < 9) { dis.ReadString(); } auto sc = versionlastloaded >= 19 ? dis.ReadDouble() : 1.0; vector image_data; if (versionlastloaded >= 22) { auto imagelen = static_cast(dis.Read64()); auto filelen = fis.GetLength(); if (filelen == wxInvalidOffset || imagelen > static_cast(filelen)) { return _("File corrupted!"); } image_data.resize(imagelen); fis.Read(image_data.data(), imagelen); } else { off_t beforeimage = fis.TellI(); if (iti == 'I') { uchar header[8]; fis.Read(header, 8); uchar expected[] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}; if (memcmp(header, expected, 8) != 0) { return _("Corrupt PNG header."); } dis.BigEndianOrdered(true); for (;;) { // Skip all chunks. wxInt32 len = dis.Read32(); char fourcc[4]; fis.Read(fourcc, 4); // Else a truncated or corrupt file would loop forever. if (fis.LastRead() != 4 || len < 0) { return _("Corrupt PNG header."); } fis.SeekI(len, wxFromCurrent); // skip data dis.Read32(); // skip CRC if (memcmp(fourcc, "IEND", 4) == 0) { break; } } } else if (iti == 'J') { wxImage im; im.LoadFile(fis); if (!im.IsOk()) { return _("JPEG file is corrupted!"); } } off_t afterimage = fis.TellI(); fis.SeekI(beforeimage); auto sz = afterimage - beforeimage; image_data.resize(sz); fis.Read(image_data.data(), sz); fis.SeekI(afterimage); } if (!fis.IsOk()) { image_data.clear(); anyimagesfailed = true; } loadimageids.push_back(AddImageToList(sc, std::move(image_data), iti)); break; } case 'D': { wxZlibInputStream zis(fis); if (!zis.IsOk()) { return _("Cannot decompress file."); } wxDataInputStream dis(zis); auto numcells = 0; auto textbytes = 0; unique_ptr root(Cell::LoadWhich(dis, nullptr, numcells, textbytes, ics)); // The rest of the program assumes the root cell has a grid. if (!root || !root->grid) { return _("File corrupted!"); } doc = NewTabDoc(true, insert_at); doc->encryption = std::move(encryption); doc->autohtmlexport = autoexport & 3; doc->autopdfexport = (autoexport & 4) != 0; if (loadedfromtmp) { doc->undolistsizeatfullsave = -1; // if not, user will lose tmp without warning when he closes doc->modified = true; } if (versionlastloaded >= 11) { for (;;) { auto tag = dis.ReadString(); if (tag.IsEmpty()) { break; } Text::FilterControls(tag); doc->tags[tag] = { versionlastloaded >= 24 ? dis.Read32() : g_cellcolor_default, versionlastloaded >= 24 ? dis.Read32() : g_tagtextcolor_default}; } } doc->InitWith(std::move(root), astemplate ? wxString() : filename, ics, xs, ys); auto end_loading_time = wxGetLocalTimeMillis(); frame->SetStatus(wxString::Format( _("Loaded %s (%d cells, %d characters) in %lld milliseconds."), filename, numcells, textbytes, end_loading_time - start_loading_time)); goto done; } default: return _("Corrupt block header."); } } } done: doc->RefreshImageRefCount(false); if (zoomlevel == 0) { doc->UpdateLayout(); doc->ScrollIfSelectionOutOfView(); doc->canvas->Refresh(); } else { doc->Zoom(zoomlevel, true); } if (anyimagesfailed) { wxMessageBox(_("PNG decode failed on some images in this document\nThey have been replaced by red squares."), _("PNG decoder failure"), wxOK, frame); } if (!astemplate) { FileUsed(filename, doc); } return wxEmptyString; } void FileUsed(const wxString &filename, Document *doc) { frame->filehistory.AddFileToHistory(filename); WatchFile(filename, doc); } void WatchFile(const wxString &filename, Document *doc) { if (!fswatch || !::wxFileExists(filename)) { return; } doc->lastmodificationtime = wxFileName(filename).GetModificationTime(); const auto &directorypath = wxFileName(filename).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR); if (watchedpaths.insert(directorypath).second) { frame->watcher->Add(wxFileName(directorypath), wxFSW_EVENT_ALL); } } void UpdateFileSystemWatching() { if (fswatch) { loop(i, frame->notebook->GetPageCount()) { auto *doc = dynamic_cast(frame->notebook->GetPage(i))->doc.get(); WatchFile(doc->filename, doc); } } else { frame->watcher->RemoveAll(); watchedpaths.clear(); } } wxString Open(const wxString &filename, bool astemplate = false) { if (!filename.empty()) { auto msg = LoadDB(filename, false, -1, nullptr, astemplate); if (!msg.IsEmpty()) { wxMessageBox(msg, filename, wxOK, frame); } else if (!astemplate) { lastopenfile = filename; } return msg; } return _("Open file cancelled."); } void RememberOpenFiles() const { auto *nb = frame->notebook; cfg->Write("lastopenfile", frame->GetCurrentTab()->doc->filename); // The tab groups as "direction layer row position proportion size active file...;" for // each group, where active and the files are numbers of the remembered files. struct : wxAuiBookSerializer { vector saved; // per page: its number among the remembered files, or -1 wxString layout; void BeforeSaveNotebook(const wxString &) override {} void SaveNotebookTabControl(const wxAuiTabLayoutInfo &tab) override { auto pages = tab.pages; // empty means all pages in order if (pages.empty()) { loop(i, saved.size()) pages.push_back(i); } wxString files; auto activefile = -1; for (auto i : pages) { if (saved[i] < 0) { continue; } files << " " << saved[i]; if (i == tab.active) { activefile = saved[i]; } } if (files.IsEmpty() && tab.dock_direction != wxAUI_DOCK_CENTER) { return; } layout << wxString::Format("%d %d %d %d %d %d %d", tab.dock_direction, tab.dock_layer, tab.dock_row, tab.dock_pos, tab.dock_proportion, tab.dock_size, activefile) << files << ";"; } } serializer; serializer.saved.resize(nb->GetPageCount(), -1); auto namedfiles = 0; for (auto *tabctrl : nb->GetAllTabCtrls()) { for (auto i : nb->GetPagesInDisplayOrder(tabctrl)) { auto *canvas = dynamic_cast(nb->GetPage(i)); if (!canvas->doc->filename.IsEmpty()) { cfg->Write(wxString::Format("lastopenfile_%d", namedfiles), canvas->doc->filename); serializer.saved[i] = namedfiles++; } } } nb->SaveLayout("notebook", serializer); cfg->Write("numopenfiles", namedfiles); cfg->Write("tablayout", serializer.layout); cfg->Flush(); } // The files of a menu, e.g. the scripts as numscripts and script_0, script_1, ... void WriteList(const wxString &name, const wxArrayString &list) const { cfg->Write("num" + name + "s", list.GetCount()); for (auto i = 0; i < list.GetCount(); ++i) { cfg->Write(wxString::Format("%s_%d", name, i), list[i]); } } void ReadList(const wxString &name, wxArrayString &list) const { auto num = 0; if (cfg->Read("num" + name + "s", &num)) { loop(i, num) { wxString filename {}; cfg->Read(wxString::Format("%s_%d", name, i), &filename); if (!filename.IsEmpty()) { list.Add(filename); } } } } void SaveCheck() const { loop(i, frame->notebook->GetPageCount()) { dynamic_cast(frame->notebook->GetPage(i)) ->doc->AutoSave(!frame->IsActive(), i); } } void SaveModified() const { loop(i, frame->notebook->GetPageCount()) { auto &doc = dynamic_cast(frame->notebook->GetPage(i))->doc; if (doc->modified && !doc->filename.empty()) { doc->SaveDB(nullptr, false, i); } } } void SaveAll() const { loop(i, frame->notebook->GetPageCount()) { frame->GetCurrentTab()->doc->Save(false); frame->CycleTabs(1); } } wxString Import(const wxString &filename, int action) { if (!filename.empty()) { wxBusyCursor wait; switch (action) { case A_IMPXML: case A_IMPXMLA: { wxXmlDocument doc; if (!doc.Load(filename)) { goto problem; } unique_ptr &root = InitDB(1); Cell *c = root->grid->cells[0].get(); FillXML(c, doc.GetRoot(), action == A_IMPXMLA, c->Depth()); if (!c->HasText() && c->grid) { unique_ptr child = std::move(root->grid->cells[0]); root = std::move(child); root->parent = nullptr; } break; } case A_IMPTXTI: case A_IMPTXTC: case A_IMPTXTS: case A_IMPTXTT: { wxFFile file(filename); if (!file.IsOpened()) { goto problem; } wxString content; if (!file.ReadAll(&content)) { goto problem; } const auto &lines = wxStringTokenize(content, LINE_DELIMITERS); if (!lines.empty()) { switch (action) { case A_IMPTXTI: { FillRows(InitDB(1)->grid.get(), lines, CountCol(lines[0]), 0, 0); }; break; case A_IMPTXTC: InitDB(1, static_cast(lines.size())) ->grid->CSVImport(lines, L','); break; case A_IMPTXTS: InitDB(1, static_cast(lines.size())) ->grid->CSVImport(lines, L';'); break; case A_IMPTXTT: InitDB(1, static_cast(lines.size())) ->grid->CSVImport(lines, L'\t'); break; } } break; } } Document *doc = frame->GetCurrentTab()->doc.get(); doc->modified = true; doc->UpdateFileName(); doc->root->ResetChildren(); doc->UpdateLayout(); doc->SetSelect(Selection(doc->root->grid, 0, 0, 1, 1)); doc->canvas->Refresh(); } return wxEmptyString; problem: wxMessageBox(_("couldn't import file!"), filename, wxOK, frame); return _("File load error."); } // elements inside a TreeSheets are styled text, not sub-cells. static bool IsRunNode(wxXmlNode *node, wxXmlNode *child) { return node->GetName() == "cell" && child->GetType() == wxXML_ELEMENT_NODE && child->GetName() == "run"; } static int GetXMLNodes(wxXmlNode *node, vector &nodes, vector *const attributes = nullptr, bool attributestoo = false) { for (auto *child = node->GetChildren(); child != nullptr; child = child->GetNext()) { if (child->GetType() == wxXML_ELEMENT_NODE && !IsRunNode(node, child)) { nodes.push_back(child); } } if (attributestoo && attributes != nullptr) { for (auto *attribute = node->GetAttributes(); attribute != nullptr; attribute = attribute->GetNext()) { attributes->push_back(attribute); } } return nodes.size() + (attributes != nullptr ? attributes->size() : 0); } static uint ParseColorAttribute(wxXmlNode *node, const wxString &name, uint def) { unsigned long color = 0; return node->GetAttribute(name, wxEmptyString).ToULong(&color, 0) ? static_cast(color) : def; } // Text with elements keeps whitespace positions, since they matter at run boundaries. static void FillXMLRichText(Text &text, wxXmlNode *node) { vector parts; for (auto *child = node->GetChildren(); child != nullptr; child = child->GetNext()) { auto type = child->GetType(); if (type == wxXML_TEXT_NODE || type == wxXML_CDATA_SECTION_NODE || IsRunNode(node, child)) { parts.push_back(child); } else if (type == wxXML_ELEMENT_NODE) { break; // what follows are sub-cells, and the indentation in front of them } } loopv(i, parts) { auto *part = parts[i]; if (part->GetType() == wxXML_ELEMENT_NODE) { auto content = part->GetNodeContent(); if (content.IsEmpty()) { continue; } TextRun r; r.start = static_cast(text.t.Len()); r.len = static_cast(content.Len()); r.stylebits = wxAtoi(part->GetAttribute("stylebits", "0")); r.hascolor = part->HasAttribute("colorfg"); r.color = ParseColorAttribute(part, "colorfg", 0) & 0xFFFFFF; text.t.Append(content); text.runs.v.push_back(r); } else { auto content = part->GetContent(); // Whatever text follows the last run is padded by the exporter. if (i + 1 == parts.size()) { content.Trim(); } text.t.Append(content); } } } // depth is at least that of c, and also counts the elements that only nest in c. void FillXML(Cell *c, wxXmlNode *node, bool attributestoo, int depth) { auto hasruns = false; if (node->GetName() == "cell") { for (auto *child = node->GetChildren(); child != nullptr; child = child->GetNext()) { if (IsRunNode(node, child)) { hasruns = true; } } } if (hasruns) { FillXMLRichText(c->text, node); } else { const auto &words = wxStringTokenize(node->GetType() == wxXML_ELEMENT_NODE ? node->GetNodeContent() : node->GetContent()); loop(i, words.GetCount()) { if (!c->text.t.IsEmpty()) { c->text.t.Append(L' '); } c->text.t.Append(words[i]); } } Text::FilterControls(c->text.t); if (node->GetName() == "cell") { c->text.relsize = -wxAtoi(node->GetAttribute("relsize", "0")); c->text.stylebits = wxAtoi(node->GetAttribute("stylebits", "0")); c->cellcolor = ParseColorAttribute(node, "colorbg", g_cellcolor_default); c->textcolor = ParseColorAttribute(node, "colorfg", g_textcolor_default); c->celltype = wxAtoi(node->GetAttribute("type", "0")); c->SyncFormula(); auto align = wxAtoi(node->GetAttribute("align", "0")); c->textalign = align >= TEXTALIGN_AUTO && align <= TEXTALIGN_RIGHT ? align : TEXTALIGN_AUTO; auto valign = wxAtoi(node->GetAttribute("valign", "0")); c->vertalign = valign >= VERTALIGN_AUTO && valign <= VERTALIGN_BOTTOM ? valign : VERTALIGN_AUTO; } c->text.runs.Normalize(c->text.stylebits); vector nodes; vector attributes; auto numrows = GetXMLNodes(node, nodes, &attributes, attributestoo); if (numrows == 0 || depth >= g_max_depth) { return; } if (nodes.size() == 1 && (c->text.t.IsEmpty() || nodes[0]->IsWhitespaceOnly()) && nodes[0]->GetName() != "row") { FillXML(c, nodes[0], attributestoo, depth + 1); } else { auto allrow = node->GetName() == "grid"; for (auto *node : nodes) { if (node->GetName() != "row") { allrow = false; break; } } if (allrow) { int desiredxs = 0; loopv(i, nodes) { vector ins; auto xs = GetXMLNodes(nodes[i], ins); if (i == 0) { desiredxs = xs != 0 ? xs : 1; c->AddGrid(desiredxs, nodes.size()); SetGridSettingsFromXML(c, node); } loop(j, desiredxs) if (ins.size() > j) { FillXML(c->grid->C(j, i).get(), ins[j], attributestoo, depth + 1); } } } else { c->AddGrid(1, numrows); SetGridSettingsFromXML(c, node); loopv(i, attributes) c->grid->C(0, i)->text.SetText(attributes[i]->GetValue()); loopv(i, nodes) FillXML(c->grid->C(0, i + attributes.size()).get(), nodes[i], attributestoo, depth + 1); } } } static void SetGridSettingsFromXML(Cell *c, wxXmlNode *node) { c->grid->folded = wxAtoi(node->GetAttribute("folded", "0")) != 0; c->grid->bordercolor = ParseColorAttribute(node, "bordercolor", g_bordercolor_default); c->grid->user_grid_outer_spacing = std::clamp( wxAtoi(node->GetAttribute("outerspacing", wxString() << g_usergridouterspacing_default)), 0, g_max_grid_outer_spacing); } static int CountCol(const wxString &s) { auto col = 0; while (s[col] == ' ' || s[col] == '\t') { col++; } return col; } // Tab separated text, unlike indented text, has tabs after the indentation of a line. static bool IsTSV(const wxArrayString &as) { for (auto &s : as) { if (s.find('\t', CountCol(s)) != wxString::npos) { return true; } } return false; } int FillRows(Grid *g, const wxArrayString &as, int column, int startrow, int starty) { auto y = starty; for (int i = startrow, n = as.size(); i < n; i++) { auto s = as[i]; auto col = CountCol(s); if (col < column && startrow != 0) { return i; } // Lines indented beyond the deepest nesting allowed become rows of that level. if (auto *c = col > column ? g->C(0, y - 1).get() : nullptr; c != nullptr && c->Depth() < g_max_depth) { auto *sg = c->grid.get(); i = FillRows(sg != nullptr ? sg : c->AddGrid(), as, col, i, sg != nullptr ? sg->ys : 0) - 1; } else { if (g->ys <= y) { g->InsertCells(-1, y, 0, 1); } auto &t = g->C(0, y)->text; t.SetText(s.Mid(col)); y++; } } return static_cast(as.size()); } int AddImageToList(double scale, vector &&data, char type) { // A scale from a file can be anything, and a tiny one makes a huge bitmap. scale = isfinite(scale) ? std::clamp(scale, g_min_image_scale, g_max_image_scale) : 1.0; auto hash = CalculateHash(data); loopv(i, imagelist) { // The scale is part of an image's identity: cells showing the same picture at // different sizes must not be merged, here or when the document is loaded again. if (imagelist[i]->hash == hash && imagelist[i]->type == type && imagelist[i]->display_scale == scale) { return i; } } imagelist.push_back(make_unique(hash, scale, std::move(data), type)); return imagelist.size() - 1; } // Cells refer to images with a raw pointer, so everything that can own cells has to be // counted here before anything is erased: the open documents, the clones held by their undo // and redo lists, and the cell clipboard. lastimage is counted in as well so that inserting // the last image still works after the document it came from was closed. void PurgeUnusedImages() { loopv(i, imagelist) imagelist[i]->trefc = 0; loop(i, frame->notebook->GetPageCount()) { auto *doc = dynamic_cast(frame->notebook->GetPage(i))->doc.get(); if (doc->root) { doc->root->ImageRefCount(true); } for (auto &undoitem : doc->undolist) { undoitem->clone->ImageRefCount(true); } for (auto &redoitem : doc->redolist) { redoitem->clone->ImageRefCount(true); } } if (cellclipboard) { cellclipboard->ImageRefCount(true); } if (lastimage != nullptr) { lastimage->trefc++; } std::erase_if(imagelist, [](const unique_ptr &image) { return image->trefc == 0; }); } static void ImageSize(wxBitmap *bm, int &xs, int &ys) { if (bm == nullptr) { return; } xs = bm->GetLogicalWidth(); // returns GetWidth on wxMSW ys = bm->GetLogicalHeight(); } static void ImageDraw(wxBitmap *bm, wxDC &dc, int x, int y, const Image *image = nullptr) { dc.DrawBitmap(*bm, x, y); } #ifdef ENABLE_WXPDFDOC // wxPdfDC ignores wxBitmap::GetScaleFactor() and sizes images by their pixel size, but // it honors the DC's user scale, so shrink the user scale instead of the pixels. static void DrawBitmapPdf(wxPdfDC &dc, const wxBitmap &bm, int x, int y, double f) { double sx, sy; dc.GetUserScale(&sx, &sy); dc.SetUserScale(sx / f, sy / f); dc.DrawBitmap(bm, wxRound(x * f), wxRound(y * f)); dc.SetUserScale(sx, sy); } #ifndef __WXMSW__ static void ImageDraw(wxBitmap *bm, wxPdfDC &dc, int x, int y, const Image *image = nullptr) { DrawBitmapPdf(dc, *bm, x, y, bm->GetScaleFactor()); } #else static void ImageDraw(wxBitmap *bm, wxPdfDC &dc, int x, int y, const Image *image = nullptr) { // Image::Display() pre-scales the bitmap on wxMSW, so decode the original // pixels again to avoid blurry images in the PDF. if (image != nullptr) { auto original = ConvertBufferToWxBitmap(image->data, imagetypes.at(image->type).first); if (original.IsOk()) { const double f = static_cast(original.GetWidth()) / std::max(1, bm->GetWidth()); DrawBitmapPdf(dc, original, x, y, f); return; } } dc.DrawBitmap(*bm, x, y); } #endif #endif };