// Text control for the toolbar: on Windows, menu accelerators (LEFT, HOME, BACK, CTRL+A, ...) are // translated before the focused control sees the key. Opting out of message pre-processing for // text editing keys lets the control handle them natively instead of emulating them in OnMenu. struct TSTextCtrl : wxTextCtrl { using wxTextCtrl::wxTextCtrl; #ifdef __WXMSW__ bool MSWShouldPreProcessMessage(WXMSG *msg) override { if (msg->message == WM_KEYDOWN) { switch (msg->wParam) { case VK_LEFT: case VK_RIGHT: case VK_HOME: case VK_END: case VK_BACK: case VK_DELETE: return false; case 'A': if (wxGetKeyState(WXK_CONTROL)) return false; break; } } return wxTextCtrl::MSWShouldPreProcessMessage(msg); } #endif }; // Suggests functions and names while typing into the formula bar. On Windows, GetCompletions() // runs in a worker thread, so it only reads the names that the UI thread sets. struct FormulaCompleter : wxTextCompleterSimple { std::mutex mutex; vector names; void SetNames(vector n) { std::lock_guard lock(mutex); names = std::move(n); } void GetCompletions(const wxString &prefix, wxArrayString &res) override { std::lock_guard lock(mutex); FormulaEvaluator::Completions(names, prefix, res); } }; struct TSFrame : wxFrame { TSApp *app; #ifdef __WXMSW__ // Whether Alt was used with the mouse since it was pressed, e.g. Alt+mousewheel to // change the width of a column (see TSCanvas::AltWithMouse()). Windows opens the menu // bar when Alt is released without another key in between, mouse buttons and the // mousewheel don't count, and then the menu bar takes the mousewheel (issue #268). bool altwithmouse {false}; WXLRESULT MSWWindowProc(WXUINT message, WXWPARAM wparam, WXLPARAM lparam) override { // Opening the menu bar by releasing Alt: lparam is 0 when it's from the keyboard. if (message == WM_SYSCOMMAND && (wparam & 0xFFF0) == SC_KEYMENU && lparam == 0 && altwithmouse) { altwithmouse = false; return 0; } return wxFrame::MSWWindowProc(message, wparam, lparam); } #endif wxIcon icon; wxTaskBarIcon taskbaricon; wxMenu *editmenupopup; wxMenu *templatemenu {nullptr}; #ifdef ENABLE_LOBSTER wxMenu *scriptmenu {nullptr}; wxString scriptcode; // The last code of Script > Run Code, and the file it is from. wxString scriptfile; #endif wxFileHistory filehistory; wxFileSystemWatcher *watcher {nullptr}; wxAuiNotebook *notebook {nullptr}; wxAuiManager aui {this}; wxBitmap line_nw; wxBitmap line_sw; wxBitmap foldicon; map foldicons; // scaled variants, keyed by text size bool fromclosebox {true}; bool globalkeyregistered {false}; bool watcherwaitingforuser {false}; wxColour toolbarbackgroundcolor {0xD8C7BC}; TSTextCtrl *filter {nullptr}; TSTextCtrl *replaces {nullptr}; TSTextCtrl *formulabar {nullptr}; FormulaCompleter *formulacompleter {nullptr}; // owned by formulabar static constexpr auto releasesurl = L"https://github.com/aardappel/treesheets/releases"; #if wxUSE_WEBREQUEST wxWebRequest updaterequest; // see CheckForUpdates() #endif #ifdef __WXMAC__ bool formulabarskip {false}; // the text changes by deleting or moving in the list bool formulabarcompleting {false}; #endif ColorDropdown *cellcolordropdown {nullptr}; ColorDropdown *textcolordropdown {nullptr}; ColorDropdown *bordercolordropdown {nullptr}; ImageDropdown *imagedropdown {nullptr}; struct ToolbarIcon { wxAuiToolBar *toolbar; int action; wxString icon; }; std::vector toolbaricons; int refreshhack {0}; int refreshhackinstances {0}; std::map menustrings; TSFrame(TSApp *_app) : wxFrame((wxFrame *)nullptr, wxID_ANY, "TreeSheets", wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE), app(_app) { sys->frame = this; class MyLog : public wxLog { void DoLogString(const wxChar *message, time_t timestamp) { DoLogText(*message); } void DoLogText(const wxString &message) override { #ifdef WIN32 OutputDebugString(message.c_str()); OutputDebugString(L"\n"); #else fputws(message.c_str(), stderr); fputws(L"\n", stderr); #endif } }; wxLog::SetActiveTarget(new MyLog()); wxLogMessage("%s", wxVERSION_STRING); aui.SetManagedWindow(this); wxInitAllImageHandlers(); wxIconBundle icons; wxIcon iconbig; icon.CopyFromBitmap(LoadEmbeddedBitmap("icon16.png")); iconbig.CopyFromBitmap(LoadEmbeddedBitmap("icon32.png")); icons.AddIcon(icon); icons.AddIcon(iconbig); SetIcons(icons); RenderFolderIcon(); line_nw = LoadEmbeddedBitmap("render/line_nw.png"); line_sw = LoadEmbeddedBitmap("render/line_sw.png"); UpdateTaskBarIconEvents(); bool showtbar = false; bool showsbar = false; sys->cfg->Read("showtbar", &showtbar, true); sys->cfg->Read("showsbar", &showsbar, true); #ifdef __WXMAC__ #define CTRLORALT "CTRL" #else #define CTRLORALT "ALT" #endif #ifdef __WXMAC__ #define ALTORCTRL "ALT" #else #define ALTORCTRL "CTRL" #endif auto *expmenu = new wxMenu(); MyAppend(expmenu, A_EXPXML, _("&XML..."), _("Export the current view as XML (which can also be reimported without losing structure)")); expmenu->AppendSeparator(); MyAppend(expmenu, A_EXPHTMLT, _("&HTML (Tables+Styling)..."), _("Export the current view as HTML using nested tables, that will look somewhat like the TreeSheet")); MyAppend(expmenu, A_EXPHTMLTE, _("&HTML (Tables+Styling+Images)..."), _("Export the curent view as HTML using nested tables and exported images")); MyAppend(expmenu, A_EXPHTMLB, _("HTML (&Bullet points)..."), _("Export the current view as HTML as nested bullet points.")); MyAppend(expmenu, A_EXPHTMLO, _("HTML (&Outline)..."), _("Export the current view as HTML as nested headers, suitable for importing into Word's outline mode")); expmenu->AppendSeparator(); MyAppend( expmenu, A_EXPTEXT, _("Indented &Text..."), _("Export the current view as tree structured text, using spaces for each indentation level. Suitable for importing into mindmanagers and general text programs")); MyAppend( expmenu, A_EXPCSV, _("&Comma delimited text (CSV, flat)..."), _("Export the grid of the current view as CSV, skipping sub-grids. Good for spreadsheets and databases (use the Flatten operation first to include sub-grids)")); MyAppend( expmenu, A_EXPTSV, _("Tab &delimited text (TSV, flat)..."), _("Export the grid of the current view as tab separated text, skipping sub-grids. Good for spreadsheets (use the Flatten operation first to include sub-grids)")); expmenu->AppendSeparator(); MyAppend(expmenu, A_EXPIMAGE, _("&Image..."), _("Export the current view as an image. Useful for faithful renderings of the TreeSheet, and programs that don't accept any of the above options")); MyAppend(expmenu, A_EXPSVG, _("&Vector graphics..."), _("Export the current view to a SVG vector file.")); #ifdef ENABLE_WXPDFDOC MyAppend(expmenu, A_EXPPDF, _("&PDF..."), _("Export the current view to a PDF file.")); #endif auto *impmenu = new wxMenu(); MyAppend(impmenu, A_IMPXML, _("XML...")); MyAppend(impmenu, A_IMPXMLA, _("XML (attributes too, for OPML etc)...")); MyAppend(impmenu, A_IMPTXTI, _("Indented text...")); MyAppend(impmenu, A_IMPTXTC, _("Comma delimited text (CSV)...")); MyAppend(impmenu, A_IMPTXTS, _("Semi-Colon delimited text (CSV)...")); MyAppend(impmenu, A_IMPTXTT, _("Tab delimited text...")); auto *recentmenu = new wxMenu(); filehistory.UseMenu(recentmenu); filehistory.AddFilesToMenu(); auto *autoexportmenu = new wxMenu(); autoexportmenu->AppendRadioItem(A_AUTOEXPORT_HTML_NONE, _("No autoexport")); autoexportmenu->AppendRadioItem(A_AUTOEXPORT_HTML_WITH_IMAGES, _("Export with images"), _("Export to a HTML file with exported images alongside " "the original TreeSheets file when document is saved")); autoexportmenu->AppendRadioItem(A_AUTOEXPORT_HTML_WITHOUT_IMAGES, _("Export without images"), _("Export to a HTML file alongside the original " "TreeSheets file when document is saved")); auto *filemenu = new wxMenu(); MyAppend(filemenu, wxID_NEW, _("&New") + "\tCTRL+N", _("Create a new document")); templatemenu = new wxMenu(); UpdateTemplateMenu(); filemenu->AppendSubMenu(templatemenu, _("New from &Template")); MyAppend(filemenu, wxID_OPEN, _("&Open...") + "\tCTRL+O", _("Open an existing document")); MyAppend(filemenu, wxID_CLOSE, _("&Close") + "\tCTRL+W", _("Close current document")); filemenu->AppendSubMenu(recentmenu, _("&Recent files")); MyAppend(filemenu, wxID_SAVE, _("&Save") + "\tCTRL+S", _("Save current document")); MyAppend(filemenu, wxID_SAVEAS, _("Save &As..."), _("Save current document with a different filename")); MyAppend(filemenu, A_SAVEALL, _("Save All")); MyAppend(filemenu, A_SETPASSWORD, _("Set Pass&word..."), _("Encrypt the current document with a password when saving it")); filemenu->AppendSubMenu(autoexportmenu, _("Autoexport to HTML")); #ifdef ENABLE_WXPDFDOC filemenu->AppendCheckItem(A_AUTOEXPORT_PDF, _("Autoexport to PDF")); #endif filemenu->AppendSeparator(); MyAppend(filemenu, A_PAGESETUP, _("Page Setup...")); MyAppend(filemenu, A_PRINTSCALE, _("Set Print Scale...")); MyAppend(filemenu, wxID_PREVIEW, _("Print preview...")); MyAppend(filemenu, wxID_PRINT, _("&Print...") + "\tCTRL+P"); filemenu->AppendSeparator(); filemenu->AppendSubMenu(expmenu, _("Export &view as")); filemenu->AppendSubMenu(impmenu, _("Import from")); filemenu->AppendSeparator(); MyAppend(filemenu, wxID_EXIT, _("&Exit") + "\tCTRL+Q", _("Quit this program")); wxMenu *editmenu = nullptr; loop(twoeditmenus, 2) { auto *sizemenu = new wxMenu(); MyAppend(sizemenu, A_INCSIZE, _("&Increase text size (SHIFT+mousewheel)") + "\tSHIFT+PGUP"); MyAppend(sizemenu, A_DECSIZE, _("&Decrease text size (SHIFT+mousewheel)") + "\tSHIFT+PGDN"); MyAppend(sizemenu, A_INCSIZENH, _("Increase text size (no sub grids, CTRL+SHIFT+mousewheel)") + "\tCTRL+SHIFT+PGUP"); MyAppend(sizemenu, A_DECSIZENH, _("Decrease text size (no sub grids, CTRL+SHIFT+mousewheel)") + "\tCTRL+SHIFT+PGDN"); MyAppend(sizemenu, A_RESETSIZE, _("&Reset text sizes") + "\tCTRL+SHIFT+S"); MyAppend(sizemenu, A_MINISIZE, _("&Shrink text of all sub-grids") + "\tCTRL+SHIFT+M"); sizemenu->AppendSeparator(); MyAppend(sizemenu, A_INCWIDTH, _("Increase column width (ALT+mousewheel)") + "\tALT+PGUP"); MyAppend(sizemenu, A_DECWIDTH, _("Decrease column width (ALT+mousewheel)") + "\tALT+PGDN"); MyAppend( sizemenu, A_INCWIDTHNH, _("Increase column width (no sub grids, CTRL+ALT+mousewheel)") + "\tCTRL+ALT+PGUP"); MyAppend( sizemenu, A_DECWIDTHNH, _("Decrease column width (no sub grids, CTRL+ALT+mousewheel)") + "\tCTRL+ALT+PGDN"); // ALT+UP/DOWN scroll. sizemenu->FindItem(A_INCWIDTH)->AddExtraAccel({wxACCEL_ALT | wxACCEL_SHIFT, WXK_UP}); sizemenu->FindItem(A_DECWIDTH)->AddExtraAccel({wxACCEL_ALT | wxACCEL_SHIFT, WXK_DOWN}); // Mac keyboards mostly lack Page Up/Down. Elsewhere, CTRL+ALT+UP/DOWN often switch // workspaces. #ifdef __WXMAC__ int nhaccel = wxACCEL_CTRL | wxACCEL_ALT; #else int nhaccel = wxACCEL_CTRL | wxACCEL_ALT | wxACCEL_SHIFT; #endif sizemenu->FindItem(A_INCWIDTHNH)->AddExtraAccel({nhaccel, WXK_UP}); sizemenu->FindItem(A_DECWIDTHNH)->AddExtraAccel({nhaccel, WXK_DOWN}); MyAppend(sizemenu, A_RESETWIDTH, _("Reset column widths") + "\tCTRL+R", _("Reset the column widths in the selection to the default column width")); auto *bordmenu = new wxMenu(); MyAppend(bordmenu, A_BORD0, _("Border &0") + "\tCTRL+SHIFT+9", "", wxITEM_CHECK); MyAppend(bordmenu, A_BORD1, _("Border &1") + "\tCTRL+SHIFT+1", "", wxITEM_CHECK); MyAppend(bordmenu, A_BORD2, _("Border &2") + "\tCTRL+SHIFT+2", "", wxITEM_CHECK); MyAppend(bordmenu, A_BORD3, _("Border &3") + "\tCTRL+SHIFT+3", "", wxITEM_CHECK); MyAppend(bordmenu, A_BORD4, _("Border &4") + "\tCTRL+SHIFT+4", "", wxITEM_CHECK); MyAppend(bordmenu, A_BORD5, _("Border &5") + "\tCTRL+SHIFT+5", "", wxITEM_CHECK); auto *selmenu = new wxMenu(); MyAppend(selmenu, A_NEXT, #ifdef __WXGTK__ _("Move to next cell (TAB)") #else _("Move to next cell") + "\tTAB" #endif ); MyAppend(selmenu, A_PREV, #ifdef __WXGTK__ _("Move to previous cell (SHIFT+TAB)") #else _("Move to previous cell") + "\tSHIFT+TAB" #endif ); selmenu->AppendSeparator(); MyAppend(selmenu, wxID_SELECTALL, _("Select &all in current grid/cell") + "\tCTRL+A"); selmenu->AppendSeparator(); MyAppend(selmenu, A_LEFT, #ifdef __WXGTK__ _("Move Selection Left (LEFT)") #else _("Move Selection Left") + "\tLEFT" #endif ); MyAppend(selmenu, A_RIGHT, #ifdef __WXGTK__ _("Move Selection Right (RIGHT)") #else _("Move Selection Right") + "\tRIGHT" #endif ); MyAppend(selmenu, A_UP, #ifdef __WXGTK__ _("Move Selection Up (UP)") #else _("Move Selection Up") + "\tUP" #endif ); MyAppend(selmenu, A_DOWN, #ifdef __WXGTK__ _("Move Selection Down (DOWN)") #else _("Move Selection Down") + "\tDOWN" #endif ); selmenu->AppendSeparator(); MyAppend(selmenu, A_MLEFT, _("Move Cells Left") + "\tCTRL+LEFT"); MyAppend(selmenu, A_MRIGHT, _("Move Cells Right") + "\tCTRL+RIGHT"); MyAppend(selmenu, A_MUP, _("Move Cells Up") + "\tCTRL+UP"); MyAppend(selmenu, A_MDOWN, _("Move Cells Down") + "\tCTRL+DOWN"); selmenu->AppendSeparator(); MyAppend(selmenu, A_SLEFT, _("Extend Selection Left") + "\tSHIFT+LEFT"); MyAppend(selmenu, A_SRIGHT, _("Extend Selection Right") + "\tSHIFT+RIGHT"); MyAppend(selmenu, A_SUP, _("Extend Selection Up") + "\tSHIFT+UP"); MyAppend(selmenu, A_SDOWN, _("Extend Selection Down") + "\tSHIFT+DOWN"); selmenu->AppendSeparator(); MyAppend(selmenu, A_SROWS, _("Extend Selection Full Rows") + "\tCTRL+SHIFT+B"); MyAppend(selmenu, A_SCLEFT, _("Extend Selection Rows Left") + "\tCTRL+SHIFT+LEFT"); MyAppend(selmenu, A_SCRIGHT, _("Extend Selection Rows Right") + "\tCTRL+SHIFT+RIGHT"); selmenu->AppendSeparator(); MyAppend(selmenu, A_SCOLS, _("Extend Selection Full Columns") + "\tCTRL+SHIFT+A"); MyAppend(selmenu, A_SCUP, _("Extend Selection Columns Up") + "\tCTRL+SHIFT+UP"); MyAppend(selmenu, A_SCDOWN, _("Extend Selection Columns Down") + "\tCTRL+SHIFT+DOWN"); selmenu->AppendSeparator(); MyAppend(selmenu, A_CANCELEDIT, _("Select &Parent") + "\tESC"); MyAppend(selmenu, A_ENTERGRID, _("Select First &Child") + "\tSHIFT+ENTER"); selmenu->AppendSeparator(); MyAppend(selmenu, A_LINK, _("Go To &Matching Cell (Text)") + "\tF6"); MyAppend(selmenu, A_LINKREV, _("Go To Matching Cell (Text, Reverse)") + "\tSHIFT+F6"); MyAppend(selmenu, A_LINKIMG, _("Go To Matching Cell (Image)") + "\tF7"); MyAppend(selmenu, A_LINKIMGREV, _("Go To Matching Cell (Image, Reverse)") + "\tSHIFT+F7"); auto *temenu = new wxMenu(); MyAppend(temenu, A_LEFT, _("Cursor Left") + "\tLEFT"); MyAppend(temenu, A_RIGHT, _("Cursor Right") + "\tRIGHT"); MyAppend(temenu, A_MLEFT, _("Word Left") + "\tCTRL+LEFT"); MyAppend(temenu, A_MRIGHT, _("Word Right") + "\tCTRL+RIGHT"); temenu->AppendSeparator(); MyAppend(temenu, A_SLEFT, _("Extend Selection Left") + "\tSHIFT+LEFT"); MyAppend(temenu, A_SRIGHT, _("Extend Selection Right") + "\tSHIFT+RIGHT"); MyAppend(temenu, A_SCLEFT, _("Extend Selection Word Left") + "\tCTRL+SHIFT+LEFT"); MyAppend(temenu, A_SCRIGHT, _("Extend Selection Word Right") + "\tCTRL+SHIFT+RIGHT"); MyAppend(temenu, A_SHOME, _("Extend Selection to Start") + "\tSHIFT+HOME"); MyAppend(temenu, A_SEND, _("Extend Selection to End") + "\tSHIFT+END"); temenu->AppendSeparator(); MyAppend(temenu, A_HOME, _("Start of line of text") + "\tHOME"); MyAppend(temenu, A_END, _("End of line of text") + "\tEND"); MyAppend(temenu, A_CHOME, _("Start of text") + "\tCTRL+HOME"); MyAppend(temenu, A_CEND, _("End of text") + "\tCTRL+END"); temenu->AppendSeparator(); MyAppend(temenu, A_ENTERCELL, _("Enter/exit text edit mode") + "\tENTER"); MyAppend(temenu, A_ENTERCELL_JUMPTOEND, _("...and jump to the end of the text") + "\tF2"); MyAppend( temenu, A_ENTERCELL_JUMPTOSTART, _("...and progress to the first cell in the new row") + "\t" ALTORCTRL "+ENTER"); MyAppend(temenu, A_PROGRESSCELL, _("...and progress to the next cell on the right") + "\t" CTRLORALT "+ENTER"); MyAppend(temenu, A_SPLITCELL, _("Split cell at the cursor") + "\tALT+SHIFT+ENTER", _("Splits the text into two cells side by side in a subgrid")); MyAppend(temenu, A_CANCELEDIT, _("Cancel text edits") + "\tESC"); auto *stmenu = new wxMenu(); MyAppend(stmenu, wxID_BOLD, _("Toggle cell &BOLD") + "\tCTRL+B", "", wxITEM_CHECK); MyAppend(stmenu, wxID_ITALIC, _("Toggle cell &ITALIC") + "\tCTRL+I", "", wxITEM_CHECK); MyAppend(stmenu, A_TT, _("Toggle cell &typewriter") + "\tCTRL+ALT+T", "", wxITEM_CHECK); MyAppend(stmenu, wxID_UNDERLINE, _("Toggle cell &underlined") + "\tCTRL+U", "", wxITEM_CHECK); MyAppend(stmenu, wxID_STRIKETHROUGH, _("Toggle cell &strikethrough") + "\tCTRL+T", "", wxITEM_CHECK); MyAppend(stmenu, A_TOGGLECHECK, _("Toggle todo chec&kbox") + "\tCTRL+SHIFT+X", _("Starts the cell text with a checkbox, ticks it, or removes it (a click " "on it ticks or unticks it)")); stmenu->AppendSeparator(); auto *alignmenu = new wxMenu(); MyAppend(alignmenu, A_ALIGNAUTO, _("Align &automatically") + "\tCTRL+SHIFT+D", _("Align right-to-left text (such as Arabic or Hebrew) right, and all other " "text left"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNLEFT, _("Align &left") + "\tCTRL+SHIFT+L", _("Align the text of the cell left"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNCENTER, _("Align ¢er") + "\tCTRL+SHIFT+E", _("Center the text of the cell"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNRIGHT, _("Align &right") + "\tCTRL+SHIFT+R", _("Align the text of the cell right"), wxITEM_CHECK); alignmenu->AppendSeparator(); // Y, H and N are above each other on the keyboard. (Not U: CTRL+SHIFT+U starts // entering a character by its code in GTK.) MyAppend(alignmenu, A_VALIGNAUTO, _("Align vertically aut&omatically"), _("Align the content of the cell at the top, or in the middle in line style " "if it has no grid"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNTOP, _("Align &top") + "\tCTRL+SHIFT+Y", _("Align the content of the cell at the top"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNMIDDLE, _("Align &middle") + "\tCTRL+SHIFT+H", _("Align the content of the cell in the middle"), wxITEM_CHECK); MyAppend(alignmenu, A_ALIGNBOTTOM, _("Align &bottom") + "\tCTRL+SHIFT+N", _("Align the content of the cell at the bottom"), wxITEM_CHECK); stmenu->AppendSubMenu(alignmenu, _("Text &alignment")); stmenu->AppendSeparator(); MyAppend(stmenu, A_RESETSTYLE, _("&Reset text styles") + "\tCTRL+SHIFT+K"); MyAppend(stmenu, A_RESETCOLOR, _("Reset &colors") + "\tCTRL+SHIFT+C"); stmenu->AppendSeparator(); MyAppend(stmenu, A_LASTCELLCOLOR, _("Apply last cell color") + "\tSHIFT+ALT+C"); MyAppend(stmenu, A_LASTTEXTCOLOR, _("Apply last text color") + "\tSHIFT+ALT+T"); MyAppend(stmenu, A_LASTBORDCOLOR, _("Apply last border color") + "\tSHIFT+ALT+B"); MyAppend(stmenu, A_OPENCELLCOLOR, _("Open cell colors") + "\tSHIFT+ALT+F9"); MyAppend(stmenu, A_OPENTEXTCOLOR, _("Open text colors") + "\tSHIFT+ALT+F10"); MyAppend(stmenu, A_OPENBORDCOLOR, _("Open border colors") + "\tSHIFT+ALT+F11"); MyAppend(stmenu, A_OPENIMGDROPDOWN, _("Open image dropdown") + "\tSHIFT+ALT+F12"); auto *tagmenu = new wxMenu(); MyAppend(tagmenu, A_TAGADD, _("&Add Cell Text as Tag")); MyAppend(tagmenu, A_TAGREMOVE, _("&Remove Cell Text from Tags")); MyAppend(tagmenu, A_NOP, _("&Set Cell Text to tag (use CTRL+RMB)"), _("Hold CTRL while pressing right mouse button to quickly set a tag for the current cell using a popup menu")); auto *orgmenu = new wxMenu(); MyAppend(orgmenu, A_TRANSPOSE, _("&Transpose") + "\tCTRL+SHIFT+T", _("changes the orientation of a grid")); MyAppend(orgmenu, A_SORT, _("Sort &Ascending"), _("Make a 1xN selection to indicate which column to sort on, and which rows to affect")); MyAppend(orgmenu, A_SORTD, _("Sort &Descending"), _("Make a 1xN selection to indicate which column to sort on, and which rows to affect")); MyAppend(orgmenu, A_HSWAP, _("Hierarchy &Swap") + "\tF8", _("Swap all cells with this text at this level (or above) with the parent")); MyAppend(orgmenu, A_HIFY, _("&Hierarchify"), _("Convert an NxN grid with repeating elements per column into an 1xN grid with hierarchy, useful to convert data from spreadsheets")); MyAppend(orgmenu, A_FLATTEN, _("&Flatten"), _("Takes a hierarchy (nested 1xN or Nx1 grids) and converts it into a flat NxN grid, useful for export to spreadsheets")); auto *imgmenu = new wxMenu(); MyAppend(imgmenu, A_IMAGE, _("&Add..."), _("Add an image to the selected cell")); MyAppend(imgmenu, A_IMAGESVA, _("&Save as..."), _("Save image(s) from selected cell(s) to disk. Multiple images will be saved with a counter appended to each file name.")); MyAppend(imgmenu, A_IMAGECOPY, _("&Copy to clipboard"), _("Copy the image of the selected cell to the clipboard, at its original size")); imgmenu->AppendSeparator(); MyAppend( imgmenu, A_IMAGESCP, _("Scale (re-sa&mple pixels, by %)"), _("Change the image(s) size if it is too big, by reducing the amount of pixels")); MyAppend( imgmenu, A_IMAGESCW, _("Scale (re-sample pixels, by &width)"), _("Change the image(s) size if it is too big, by reducing the amount of pixels")); MyAppend(imgmenu, A_IMAGESCF, _("Scale (&display only)"), _("Change the image(s) size if it is too big or too small, by changing the size shown on screen. Applies to all uses of this image.")); MyAppend(imgmenu, A_IMAGESCN, _("&Reset Scale (display only)"), _("Change the image(s) scale to match DPI of the current display. Applies to all uses of this image.")); imgmenu->AppendSeparator(); MyAppend( imgmenu, A_SAVE_AS_JPEG, _("Embed as &JPEG"), _("Embed the image(s) in the selected cells in JPEG format (reduces data size)")); MyAppend(imgmenu, A_SAVE_AS_PNG, _("Embed as &PNG"), _("Embed the image(s) in the selected cells in PNG format (default)")); imgmenu->AppendSeparator(); MyAppend(imgmenu, A_LASTIMAGE, _("Insert last image") + "\tSHIFT+ALT+I", _("Insert the last image that has been inserted before in TreeSheets.")); MyAppend(imgmenu, A_IMAGER, _("Remo&ve"), _("Remove image(s) from the selected cells")); auto *navmenu = new wxMenu(); MyAppend(navmenu, A_BROWSE, _("Open link in &browser") + "\tF5", _("Follows the link at the cursor or in the selected cell, or else opens its text in the browser")); MyAppend(navmenu, A_BROWSEF, _("Open &file") + "\tF4", _("Opens up the text from the selected cell in default application for the file type")); MyAppend(navmenu, A_HYPERLINK, _("&Link...") + "\tSHIFT+F5", _("Links the selected text to a web page, a file or the nearest cell with that text (CTRL+click follows it)")); auto *laymenu = new wxMenu(); auto layhelp = _("Hold Shift when choosing it to change the selected cells, not the ones inside"); MyAppend(laymenu, A_V_GS, _("Vertical Layout with Grid Style Rendering") + "\t" CTRLORALT "+1", layhelp); MyAppend(laymenu, A_V_BS, _("Vertical Layout with Bubble Style Rendering") + "\t" CTRLORALT "+2", layhelp); MyAppend(laymenu, A_V_LS, _("Vertical Layout with Line Style Rendering") + "\t" CTRLORALT "+3", layhelp); laymenu->AppendSeparator(); MyAppend(laymenu, A_H_GS, _("Horizontal Layout with Grid Style Rendering") + "\t" CTRLORALT "+4", layhelp); MyAppend(laymenu, A_H_BS, _("Horizontal Layout with Bubble Style Rendering") + "\t" CTRLORALT "+5", layhelp); MyAppend(laymenu, A_H_LS, _("Horizontal Layout with Line Style Rendering") + "\t" CTRLORALT "+6", layhelp); laymenu->AppendSeparator(); MyAppend(laymenu, A_GS, _("Grid Style Rendering") + "\t" CTRLORALT "+7", layhelp); MyAppend(laymenu, A_BS, _("Bubble Style Rendering") + "\t" CTRLORALT "+8", layhelp); MyAppend(laymenu, A_LS, _("Line Style Rendering") + "\t" CTRLORALT "+9", layhelp); laymenu->AppendSeparator(); MyAppend(laymenu, A_TEXTGRID, _("Toggle Vertical Layout") + "\t" CTRLORALT "+0", _("Make a hierarchy layout more vertical (default) or more horizontal")); auto *copymenu = new wxMenu(); MyAppend(copymenu, A_COPYWI, _("Copy with &Images") + "\tCTRL+ALT+C"); MyAppend(copymenu, A_COPYBM, _("&Copy as Bitmap")); MyAppend(copymenu, A_COPYSVG, _("Copy as &SVG"), _("Copy the selection as SVG vector graphics")); MyAppend(copymenu, A_COPYCT, _("Copy As Continuous Text")); auto *pastemenu = new wxMenu(); MyAppend(pastemenu, A_PASTESTYLE, _("Paste Style Only") + "\tCTRL+SHIFT+V", _("only sets the colors and style of the copied cell, and keeps the text")); MyAppend(pastemenu, A_PASTETEXT, _("Paste as &Text"), _("Paste the text of the clipboard without the styles of the copied cells")); MyAppend(pastemenu, A_PASTETSV, _("Paste as Tab-Separated &Grid") + "\tCTRL+ALT+V", _("Paste the text of the clipboard as a grid, with tabs separating the columns " "and lines separating the rows")); editmenu = new wxMenu(); MyAppend(editmenu, wxID_CUT, _("Cu&t") + "\tCTRL+X", _("Cut selection")); MyAppend(editmenu, wxID_COPY, _("&Copy") + "\tCTRL+C", _("Copy selection")); MyAppend(editmenu, wxID_PASTE, _("&Paste") + "\tCTRL+V", _("Paste clipboard contents")); editmenu->AppendSubMenu(copymenu, _("Cop&y Special")); editmenu->AppendSubMenu(pastemenu, _("Paste Speci&al")); editmenu->AppendSeparator(); MyAppend(editmenu, A_COLLAPSE, _("Collapse Ce&lls") + "\tCTRL+L"); editmenu->AppendSeparator(); MyAppend(editmenu, A_EDITNOTE, _("Edit &Note") + "\tCTRL+E", _("Edit the note of the selected cell")); MyAppend(editmenu, wxID_UNDO, _("&Undo") + "\tCTRL+Z", _("revert the changes, one step at a time")); MyAppend(editmenu, wxID_REDO, _("&Redo") + "\tCTRL+Y", _("redo any undo steps, if you haven't made changes since")); editmenu->AppendSeparator(); MyAppend( editmenu, A_DELETE, _("&Delete After") + "\tDEL", _("Deletes the column of cells after the selected grid line, or the row below")); MyAppend( editmenu, A_BACKSPACE, _("Delete Before") + "\tBACK", _("Deletes the column of cells before the selected grid line, or the row above")); MyAppend(editmenu, A_DELETE_WORD, _("Delete Word After") + "\tCTRL+DEL", _("Deletes the entire word after the cursor")); MyAppend(editmenu, A_BACKSPACE_WORD, _("Delete Word Before") + "\tCTRL+BACK", _("Deletes the entire word before the cursor")); editmenu->AppendSeparator(); MyAppend(editmenu, A_ENTERGRID, #ifdef __WXMAC__ _("&Insert New Grid") + "\tCTRL+G", #else _("&Insert New Grid") + "\tINSERT", #endif _("Adds a grid to the selected cell")); MyAppend(editmenu, A_ENTERGRIDN, _("Insert New &NxN Grid") + "\tCTRL+SHIFT+ENTER", _("Adds a NxN grid to the selected cell")); MyAppend(editmenu, A_DELGRID, _("Delete Grid") + "\tSHIFT+DEL", _("Deletes the grids of the selected cells, keeping their text")); MyAppend(editmenu, A_WRAP, _("&Wrap in new parent") + "\tF9", _("Creates a new level of hierarchy around the current selection")); editmenu->AppendSeparator(); // F10 is tied to the OS on both Ubuntu and OS X, and SHIFT+F10 is now right // click on all platforms? MyAppend(editmenu, A_FOLD, #ifndef WIN32 _("Toggle Fold (CTRL+double-click)") + "\tCTRL+F10", #else _("Toggle Fold (CTRL+double-click)") + "\tF10", #endif _("Toggles showing the grid of the selected cell(s)")); MyAppend(editmenu, A_FOLDALL, _("Fold All (CTRL+SHIFT+double-click)") + "\tCTRL+SHIFT+F10", _("Folds the grid of the selected cell(s) recursively")); MyAppend(editmenu, A_UNFOLDALL, _("Unfold All (CTRL+SHIFT+double-click)") + "\tCTRL+ALT+F10", _("Unfolds the grid of the selected cell(s) recursively")); editmenu->AppendSeparator(); editmenu->AppendSubMenu(selmenu, _("&Selection")); editmenu->AppendSubMenu(orgmenu, _("&Grid Reorganization")); editmenu->AppendSubMenu(laymenu, _("&Layout && Render Style")); editmenu->AppendSubMenu(imgmenu, _("&Images")); editmenu->AppendSubMenu(navmenu, _("&Browsing")); editmenu->AppendSubMenu(temenu, _("Text &Editing")); editmenu->AppendSubMenu(sizemenu, _("Text Sizing")); editmenu->AppendSubMenu(stmenu, _("Text Style")); editmenu->AppendSubMenu(bordmenu, _("Set Grid Border Width")); editmenu->AppendSubMenu(tagmenu, _("Tag")); if (twoeditmenus == 0) { editmenupopup = editmenu; } } auto *semenu = new wxMenu(); MyAppend(semenu, wxID_FIND, _("&Search") + "\tCTRL+F", _("Find in document")); semenu->AppendCheckItem(A_CASESENSITIVESEARCH, _("Case-sensitive search")); semenu->Check(A_CASESENSITIVESEARCH, sys->casesensitivesearch); semenu->AppendCheckItem( A_RESTRICTVIEW, _("Restrict search and replace to view"), _("Search and replace in the visible content of the current view (no folded " "grids, no tiny cells)")); semenu->Check(A_RESTRICTVIEW, sys->restrictview); semenu->AppendSeparator(); MyAppend(semenu, A_SEARCHNEXT, _("&Next Match") + "\tF3", _("Go to next search match")); MyAppend(semenu, A_SEARCHPREV, _("&Previous Match") + "\tSHIFT+F3", _("Go to previous search match")); semenu->AppendSeparator(); MyAppend(semenu, wxID_REPLACE, _("&Replace") + "\tCTRL+H", _("Find and replace in document")); MyAppend(semenu, A_REPLACEONCE, _("Replace in Current &Selection") + "\tCTRL+K"); MyAppend(semenu, A_REPLACEONCEJ, _("Replace in Current Selection && &Jump Next") + "\tCTRL+J"); MyAppend(semenu, A_REPLACEALL, _("Replace &All")); auto *scrollmenu = new wxMenu(); MyAppend(scrollmenu, A_AUP, _("Scroll Up (mousewheel)") + "\tPGUP"); MyAppend(scrollmenu, A_AUP, _("Scroll Up (mousewheel)") + "\tALT+UP"); MyAppend(scrollmenu, A_ADOWN, _("Scroll Down (mousewheel)") + "\tPGDN"); MyAppend(scrollmenu, A_ADOWN, _("Scroll Down (mousewheel)") + "\tALT+DOWN"); MyAppend(scrollmenu, A_ALEFT, _("Scroll Left") + "\tALT+LEFT"); MyAppend(scrollmenu, A_ARIGHT, _("Scroll Right") + "\tALT+RIGHT"); auto *filtermenu = new wxMenu(); MyAppend(filtermenu, A_FILTEROFF, _("Turn filter &off") + "\tCTRL+SHIFT+F"); MyAppend(filtermenu, A_FILTERS, _("Show only cells in current search")); filtermenu->AppendSeparator(); MyAppend(filtermenu, A_FILTERRANGE, _("Show last edits in specific date range")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTER5, _("Show 5% of last edits")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTER10, _("Show 10% of last edits")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTER20, _("Show 20% of last edits")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTER50, _("Show 50% of last edits")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTERM, _("Show 1% more than the last filter")); // xgettext:no-c-format MyAppend(filtermenu, A_FILTERL, _("Show 1% less than the last filter")); filtermenu->AppendSeparator(); MyAppend(filtermenu, A_FILTERBYCELLBG, _("Show cells with the same cell color")); MyAppend(filtermenu, A_FILTERBYSTYLE, _("Show cells with the same style")); MyAppend(filtermenu, A_FILTERBYTEXT, _("Show cells with the same text")); MyAppend(filtermenu, A_FILTERNOTE, _("Show cells with notes")); MyAppend(filtermenu, A_FILTERBYTAGS, _("Show cells with tags..."), _("Show the cells whose text is one of the checked tags")); filtermenu->AppendSeparator(); MyAppend(filtermenu, A_FILTERMATCHNEXT, _("Go to next filter match") + "\tCTRL+F3"); filtermenu->AppendSeparator(); filtermenu->AppendCheckItem( A_FILTERSHOWROWS, _("Show entire row on match"), _("When a cell in a row matches the current filter, show the whole row " "normally instead of only the matching cell")); filtermenu->Check(A_FILTERSHOWROWS, sys->filtershowrows); filtermenu->AppendCheckItem( A_FILTERSHOWSUBGRIDS, _("Show sub-grids on match"), _("When a cell matches the current filter, show everything in the grid inside it " "normally instead of filtering it too")); filtermenu->Check(A_FILTERSHOWSUBGRIDS, sys->filtershowsubgrids); filtermenu->AppendCheckItem( A_FILTERUNION, _("Keep previous filter matches"), _("Show the matches of a new filter in addition to those of the active filter")); filtermenu->Check(A_FILTERUNION, sys->filterunion); auto *viewmenu = new wxMenu(); MyAppend(viewmenu, A_ZOOMIN, _("Zoom &In (CTRL+mousewheel)") + "\tCTRL+PGUP"); MyAppend(viewmenu, A_ZOOMOUT, _("Zoom &Out (CTRL+mousewheel)") + "\tCTRL+PGDN"); viewmenu->AppendSeparator(); MyAppend(viewmenu, A_INCFONTSIZE, _("&Increase font size (CTRL+ALT+SHIFT+mousewheel)") + "\tCTRL+."); MyAppend(viewmenu, A_DECFONTSIZE, _("&Decrease font size (CTRL+ALT+SHIFT+mousewheel)") + "\tCTRL+,"); MyAppend(viewmenu, A_RESETFONTSIZE, _("&Reset font size") + "\tCTRL+-"); viewmenu->AppendSeparator(); MyAppend(viewmenu, A_NEXTFILE, _("&Next tab") + "\tCTRL+TAB", _("Go to the document in the next tab")); MyAppend(viewmenu, A_PREVFILE, _("Previous tab") + "\tCTRL+SHIFT+TAB", _("Go to the document in the previous tab")); viewmenu->AppendSeparator(); MyAppend(viewmenu, A_FULLSCREEN, #ifdef __WXMAC__ _("Toggle &Fullscreen View") + "\tCTRL+F11"); #else _("Toggle &Fullscreen View") + "\tF11"); #endif MyAppend(viewmenu, A_SCALED, #ifdef __WXMAC__ _("&Scaled Presentation View") + "\tCTRL+F12", "", wxITEM_CHECK); #else _("&Scaled Presentation View") + "\tF12", "", wxITEM_CHECK); #endif viewmenu->AppendSeparator(); viewmenu->AppendSubMenu(scrollmenu, _("Scroll Sheet")); viewmenu->AppendSubMenu(filtermenu, _("Filter")); auto *roundmenu = new wxMenu(); roundmenu->AppendRadioItem(A_ROUND0, _("Radius &0")); roundmenu->AppendRadioItem(A_ROUND1, _("Radius &1")); roundmenu->AppendRadioItem(A_ROUND2, _("Radius &2")); roundmenu->AppendRadioItem(A_ROUND3, _("Radius &3")); roundmenu->AppendRadioItem(A_ROUND4, _("Radius &4")); roundmenu->AppendRadioItem(A_ROUND5, _("Radius &5")); roundmenu->AppendRadioItem(A_ROUND6, _("Radius &6")); roundmenu->Check(sys->roundness + A_ROUND0, true); auto *defaultimagemenu = new wxMenu(); defaultimagemenu->AppendRadioItem(A_DEFAULTIMAGE_PNG, _("PNG")); defaultimagemenu->AppendRadioItem(A_DEFAULTIMAGE_JPEG, _("JPEG")); defaultimagemenu->Check(sys->defaultimageformat + A_DEFAULTIMAGE_PNG, true); auto *optmenu = new wxMenu(); MyAppend(optmenu, wxID_SELECT_FONT, _("Font..."), _("Set the font the document text is displayed with")); MyAppend(optmenu, A_SET_FIXED_FONT, _("Typewriter font..."), _("Set the font the typewriter text is displayed with.")); MyAppend(optmenu, A_CUSTKEY, _("Key bindings..."), _("Change the key binding of a menu item")); MyAppend(optmenu, A_SETLANG, _("Change language..."), _("Change interface language")); MyAppend(optmenu, A_DEFAULTMAXCOLWIDTH, _("Default column width..."), _("Set the default column width for a new grid")); optmenu->AppendSeparator(); MyAppend(optmenu, A_COLORS, _("&Colors..."), _("Set the colors of the cursor, hover shadow, search results, operations and " "the custom color of the color dropdowns")); MyAppend( optmenu, A_COLCELL, _("&Set custom color from cell background"), _("Set a custom color for the color dropdowns from the selected cell background")); MyAppend(optmenu, A_DEFBGCOL, _("Background color..."), _("Set the color for the document background")); optmenu->AppendSeparator(); MyAppend(optmenu, A_RESETPERSPECTIVE, _("Reset toolbar"), _("Reset the toolbar appearance")); optmenu->AppendCheckItem( A_SHOWTBAR, _("Toolbar"), _("Toggle whether toolbar is shown between menu bar and documents")); optmenu->Check(A_SHOWTBAR, sys->showtoolbar); optmenu->AppendCheckItem(A_SHOWSBAR, _("Statusbar"), _("Toggle whether statusbar is shown below the documents")); optmenu->Check(A_SHOWSBAR, sys->showstatusbar); optmenu->AppendCheckItem( A_BOTTOMTABS, _("File Tabs on the bottom"), _("Toggle whether file tabs are shown on top or on bottom of the documents")); optmenu->Check(A_BOTTOMTABS, sys->bottomtabs); optmenu->AppendCheckItem(A_TOTRAY, _("Minimize to tray"), _("Toogle whether window is minimized to system tray")); optmenu->Check(A_TOTRAY, sys->totray); optmenu->AppendCheckItem(A_MINCLOSE, _("Minimize on close"), _("Toggle whether the window is minimized instead of closed")); optmenu->Check(A_MINCLOSE, sys->minclose); optmenu->AppendCheckItem( A_SINGLETRAY, _("Single click maximize from tray"), _("Toggle whether only one click is required to maximize from system tray")); optmenu->Check(A_SINGLETRAY, sys->singletray); optmenu->AppendCheckItem(A_STARTMINIMIZED, _("Start minimized"), _("Start the application minimized")); optmenu->Check(A_STARTMINIMIZED, sys->startminimized); #if wxUSE_HOTKEY optmenu->AppendCheckItem( A_GLOBALKEY, _("Show and hide from any application"), wxString::Format(_("%s shows TreeSheets or minimizes it, wherever the focus is"), sys->globalkeyname)); optmenu->Check(A_GLOBALKEY, sys->globalkey); #endif optmenu->AppendSeparator(); optmenu->AppendCheckItem(A_ZOOMSCR, _("Swap mousewheel scrolling and zooming")); optmenu->Check(A_ZOOMSCR, sys->zoomscroll); optmenu->AppendCheckItem(A_THINSELC, _("Navigate in between cells with cursor keys"), _("Toggle whether the cursor keys are used for navigation in addition to text editing")); optmenu->Check(A_THINSELC, sys->thinselc); optmenu->AppendCheckItem(A_HOVERZOOM, _("Hover zoom"), _("Zoom on cells cursor hovers on")); optmenu->Check(A_HOVERZOOM, sys->hoverzoom); optmenu->AppendCheckItem(A_HOVERSHADOW, _("Hover shadow"), _("Shade the cell the mouse pointer hovers over")); optmenu->Check(A_HOVERSHADOW, sys->hovershadow); optmenu->AppendSeparator(); optmenu->AppendCheckItem(A_MAKEBAKS, _("Backup files"), _("Create backup file before document is saved to file")); optmenu->Check(A_MAKEBAKS, sys->makebaks); optmenu->AppendCheckItem(A_AUTOSAVE, _("Autosave"), _("Save open documents periodically to temporary files")); optmenu->Check(A_AUTOSAVE, sys->autosave); optmenu->AppendCheckItem( A_SAVEDISMISS, _("Save on minimize and exit"), _("Save changed documents when the window is minimized or TreeSheets is closed")); optmenu->Check(A_SAVEDISMISS, sys->savedismiss); optmenu->AppendCheckItem( A_FSWATCH, _("Autoreload documents"), _("Reload when another computer has changed a file (if you have made changes, asks)")); optmenu->Check(A_FSWATCH, sys->fswatch); optmenu->AppendSubMenu(defaultimagemenu, _("Default image format"), _("Default format when image is pasted from clipboard or dropped")); optmenu->AppendCheckItem(A_FLATCOPY, _("Copy without tiny cells and sub-grids"), _("Leave out tiny and filtered cells and all sub-grids when " "copying cells as text or HTML")); optmenu->Check(A_FLATCOPY, sys->flatcopy); optmenu->AppendSeparator(); optmenu->AppendCheckItem( A_CENTERED, _("Render document centered"), _("Toggle whether documents are rendered centered or left aligned")); optmenu->Check(A_CENTERED, sys->centered); optmenu->AppendCheckItem(A_SHRINKTEXT, _("Shrink text in nested grids"), _("Toggle whether text gets smaller the deeper a grid is nested")); optmenu->Check(A_SHRINKTEXT, sys->shrinktext); optmenu->AppendCheckItem( A_FASTRENDER, _("Faster line rendering"), _("Toggle whether lines are drawn solid (faster rendering) or dashed")); optmenu->Check(A_FASTRENDER, sys->fastrender); optmenu->AppendCheckItem(A_INNERBORDERCOLOR, _("Colorize inner grid border"), _("Also colorize the inner grid border")); optmenu->Check(A_INNERBORDERCOLOR, sys->innerbordercolor); optmenu->AppendCheckItem(A_INVERTRENDER, _("Invert in dark mode"), _("Invert the document in dark mode")); optmenu->Check(A_INVERTRENDER, sys->followdarkmode); optmenu->AppendSubMenu(roundmenu, _("&Roundness of grid borders")); auto *markmenu = new wxMenu(); MyAppend(markmenu, A_MARKDATA, _("&Data") + "\tCTRL+ALT+D", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKCODE, _("&Operation") + "\tCTRL+ALT+O", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKVARD, _("Variable &Assign") + "\tCTRL+ALT+A", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKVARU, _("Variable &Read") + "\tCTRL+ALT+R", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKVIEWH, _("&Horizontal View") + "\tCTRL+ALT+.", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKVIEWV, _("&Vertical View") + "\tCTRL+ALT+,", "", wxITEM_CHECK); MyAppend(markmenu, A_MARKFORMULA, _("&Formula"), "", wxITEM_CHECK); auto *langmenu = new wxMenu(); MyAppend(langmenu, wxID_EXECUTE, _("&Run") + "\tCTRL+ALT+F5"); langmenu->AppendSubMenu(markmenu, _("&Mark as")); MyAppend(langmenu, A_CLRVIEW, _("&Clear Views")); auto *helpmenu = new wxMenu(); MyAppend(helpmenu, wxID_ABOUT, _("&About..."), _("Show About dialog")); MyAppend(helpmenu, A_CHECKUPDATES, _("Check for &Updates..."), _("Check whether there is a newer release of TreeSheets")); helpmenu->AppendSeparator(); MyAppend(helpmenu, wxID_HELP, _("Interactive &tutorial") + "\tF1", _("Load an interactive tutorial in TreeSheets")); MyAppend(helpmenu, A_HELP_OP_REF, _("Operation reference") + "\tCTRL+ALT+F1", _("Load an interactive program operation reference in TreeSheets")); MyAppend(helpmenu, A_HELP_EXAMPLES, _("Open e&xample..."), _("Choose one of the example documents that come with TreeSheets to open")); helpmenu->AppendSeparator(); MyAppend(helpmenu, A_TUTORIALWEBPAGE, _("Tutorial &web page"), _("Open the tutorial web page in browser")); #ifdef ENABLE_LOBSTER MyAppend(helpmenu, A_SCRIPTREFERENCE, _("&Script reference"), _("Open the Lobster script reference in browser")); #endif wxAcceleratorEntry entries[2]; entries[0].Set(wxACCEL_SHIFT, WXK_DELETE, A_DELGRID); entries[1].Set(wxACCEL_NORMAL, WXK_INSERT, A_ENTERGRID); wxAcceleratorTable accel(2, entries); SetAcceleratorTable(accel); auto *menubar = new wxMenuBar(); menubar->Append(filemenu, _("&File")); menubar->Append(editmenu, _("&Edit")); menubar->Append(semenu, _("&Search")); menubar->Append(viewmenu, _("&View")); menubar->Append(optmenu, _("&Options")); #ifdef ENABLE_LOBSTER scriptmenu = new wxMenu(); UpdateScriptMenu(scriptmenu); menubar->Append(scriptmenu, _("S&cript")); #endif menubar->Append(langmenu, _("&Program")); menubar->Append(helpmenu, #ifdef __WXMAC__ wxApp::s_macHelpMenuTitleName // so merges with osx provided help #else _("&Help") #endif ); #ifdef __WXMAC__ // these don't seem to work anymore in the newer wxWidgets, handled in the menu event // handler below instead wxApp::s_macAboutMenuItemId = wxID_ABOUT; wxApp::s_macExitMenuItemId = wxID_EXIT; wxApp::s_macPreferencesMenuItemId = wxID_SELECT_FONT; // we have no prefs, so for now just select the font #endif SetMenuBar(menubar); RefreshToolBar(); auto *sb = CreateStatusBar(5); SetStatusBarPane(0); SetDPIAwareStatusWidths(); sb->Show(sys->showstatusbar); notebook = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TAB_MOVE | wxAUI_NB_TAB_SPLIT | wxAUI_NB_SCROLL_BUTTONS | wxAUI_NB_WINDOWLIST_BUTTON | wxAUI_NB_CLOSE_ON_ALL_TABS | GetTabPosition()); // Where the window was, on the display that showed its middle, made to fit that display. // If that display is gone (or nothing was saved), a default place on the primary one. auto rect = wxDisplay().GetClientArea().Deflate(64); wxRect saved; if (sys->cfg->Read("posx", &saved.x) && sys->cfg->Read("posy", &saved.y) && sys->cfg->Read("resx", &saved.width) && sys->cfg->Read("resy", &saved.height)) { auto display = wxDisplay::GetFromPoint(saved.GetPosition() + saved.GetSize() / 2); if (display != wxNOT_FOUND) { auto area = wxDisplay(display).GetClientArea(); rect.width = std::min(saved.width, area.width); rect.height = std::min(saved.height, area.height); rect.x = std::clamp(saved.x, area.x, area.x + area.width - rect.width); rect.y = std::clamp(saved.y, area.y, area.y + area.height - rect.height); } } SetSize(rect); bool ismax = false; sys->cfg->Read("maximized", &ismax, true); aui.AddPane( notebook, wxAuiPaneInfo().Name("notebook").Caption("Notebook").CenterPane().PaneBorder(false)); auto perspective = sys->cfg->Read("perspective", ""); aui.LoadPerspective(perspective); // LoadPerspective() hides every pane the saved layout doesn't mention, so toolbars // added in a later version would never show up. Show those, right after the toolbar // created before them. if (!perspective.IsEmpty()) { wxAuiPaneInfo *prev = nullptr; for (const auto &name : GetToolbarPaneNames()) { auto &pane = aui.GetPane(name); if (!perspective.Contains("name=" + name + ";")) { pane.Show(); if (prev != nullptr) { auto &panes = aui.GetAllPanes(); for (size_t i = 0; i < panes.GetCount(); i++) { auto &p = panes.Item(i); if (p.IsToolbar() && p.dock_direction == prev->dock_direction && p.dock_row == prev->dock_row && p.dock_pos > prev->dock_pos) { p.dock_pos++; } } pane.Direction(prev->dock_direction) .Row(prev->dock_row) .Position(prev->dock_pos + 1); } } prev = &pane; } // It also has the sizes of the toolbars, which are too small for toolbars that got // buttons in a later version, so these would be cut off. for (const auto &name : GetToolbarPaneNames()) { auto &pane = aui.GetPane(name); if (pane.window != nullptr) { pane.BestSize(pane.window->GetBestSize()); } } } aui.Update(); Show(!IsIconized()); // needs to be after Show() to avoid scrollbars rendered in the wrong place? if (ismax && !IsIconized()) { Maximize(true); } // No size event necessarily follows, so fit the loaded toolbar layout to the window now. ReflowToolbars(); if (sys->startminimized) { #ifdef __WXGTK__ CallAfter([this]() { Iconize(true); }); #else Iconize(true); #endif } SetFileAssoc(app->exename); Bind(wxEVT_DPI_CHANGED, &TSFrame::OnDPIChanged, this); Bind(wxEVT_SIZING, &TSFrame::OnSizing, this); Bind(wxEVT_MENU, &TSFrame::OnMenu, this, wxID_ANY); #ifdef __WXMAC__ BypassMacMenuForFunctionKeys( [] { return dynamic_cast(wxWindow::FindFocus()) != nullptr; }); #endif Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateStyle, this, wxID_BOLD); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateStyle, this, wxID_ITALIC); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateStyle, this, A_TT); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateStyle, this, wxID_UNDERLINE); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateStyle, this, wxID_STRIKETHROUGH); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateTextAlign, this, A_ALIGNAUTO, A_ALIGNRIGHT); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateVertAlign, this, A_VALIGNAUTO, A_ALIGNBOTTOM); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateBorder, this, A_BORD0, A_BORD5); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateNoteOrLink, this, A_EDITNOTE); Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateNoteOrLink, this, A_HYPERLINK); Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && canvas->doc->scaledviewingmode); }, A_SCALED); #if wxUSE_WEBREQUEST Bind(wxEVT_WEBREQUEST_STATE, &TSFrame::OnUpdateCheck, this, A_CHECKUPDATES); #endif for (int id : {A_MARKDATA, A_MARKCODE, A_MARKVARD, A_MARKVARU, A_MARKVIEWH, A_MARKVIEWV, A_MARKFORMULA}) { Bind(wxEVT_UPDATE_UI, &TSFrame::OnUpdateCellType, this, id); } Bind(wxEVT_CHAR_HOOK, &TSFrame::OnCharHook, this, A_SEARCH); Bind(wxEVT_CHAR_HOOK, &TSFrame::OnCharHook, this, A_REPLACE); Bind(wxEVT_CHAR_HOOK, &TSFrame::OnCharHook, this, A_FORMULABAR); #ifdef __WXMSW__ // Wherever the focus is. Holding Alt repeats it, also while using it with the mouse. Bind(wxEVT_CHAR_HOOK, [this](wxKeyEvent &ke) { if (ke.GetKeyCode() == WXK_ALT && !ke.IsAutoRepeat()) { altwithmouse = false; } ke.Skip(); }); #endif Bind(wxEVT_TEXT, &TSFrame::OnSearch, this, A_SEARCH); Bind(wxEVT_CLOSE_WINDOW, &TSFrame::OnClosing, this); Bind(wxEVT_MAXIMIZE, &TSFrame::OnMaximize, this); Bind(wxEVT_ACTIVATE_APP, &TSFrame::OnActivate, this); Bind(wxEVT_COMBOBOX, &TSFrame::OnChangeColor, this, A_CELLCOLOR); Bind(wxEVT_COMBOBOX, &TSFrame::OnChangeColor, this, A_TEXTCOLOR); Bind(wxEVT_COMBOBOX, &TSFrame::OnChangeColor, this, A_BORDCOLOR); Bind(wxEVT_COMBOBOX, &TSFrame::OnDDImage, this, A_DDIMAGE); // Also give the keyboard back to the document when a dropdown closes without a choice. Bind(wxEVT_COMBOBOX_CLOSEUP, [this](wxCommandEvent &) { ReFocus(); }); Bind(wxEVT_ICONIZE, &TSFrame::OnIconize, this); #if wxUSE_HOTKEY Bind(wxEVT_HOTKEY, [this](wxKeyEvent &) { ToggleShown(); }); UpdateGlobalKey(); #endif Bind(wxEVT_SIZE, &TSFrame::OnSize, this); Bind(wxEVT_AUINOTEBOOK_PAGE_CHANGED, &TSFrame::OnTabChange, this, wxID_ANY); Bind(wxEVT_MENU_OPEN, &TSFrame::OnMenuOpen, this); Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSE, &TSFrame::OnTabClose, this, wxID_ANY); Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSED, &TSFrame::OnTabClosed, this, wxID_ANY); Bind(wxEVT_SYS_COLOUR_CHANGED, &TSFrame::OnSysColourChanged, this); wxSafeYield(); } long GetTabPosition() const { return sys->bottomtabs ? wxAUI_NB_BOTTOM : wxAUI_NB_TOP; } wxArrayString GetToolbarPaneNames() { wxArrayString toolbarNames; wxAuiPaneInfoArray &all_panes = aui.GetAllPanes(); for (size_t i = 0; i < all_panes.GetCount(); ++i) { wxAuiPaneInfo &pane = all_panes.Item(i); if (pane.IsToolbar()) { toolbarNames.Add(pane.name); } } return toolbarNames; } void DestroyToolbarPane(const wxString &name) { wxAuiPaneInfo &pane = aui.GetPane(name); if (pane.IsOk()) { wxWindow *wnd = pane.window; aui.DetachPane(wnd); if (wnd != nullptr) { wnd->Destroy(); } } } wxBitmapBundle LoadToolbarIcon(const wxString &icon) const { auto suffix = wxSystemSettings::GetAppearance().IsDark() ? "_dark.svg" : ".svg"; return LoadEmbeddedSVG("material/toolbar/" + icon + suffix, wxSize(24, 24)); } void UpdateToolbarIcons() { for (const auto &icon : toolbaricons) { icon.toolbar->SetToolBitmap(icon.action, LoadToolbarIcon(icon.icon)); } for (const auto &name : GetToolbarPaneNames()) { auto *wnd = aui.GetPane(name).window; if (wnd != nullptr) { wnd->Refresh(); } } } // wxAuiToolBar and wxAuiManager cache pixel sizes, so after a DPI change (e.g. moving the // window to a display with another scale factor) toolbars would keep stale, differing heights. void RefitToolbars() { UpdateToolbarIcons(); for (const auto &name : GetToolbarPaneNames()) { auto &pane = aui.GetPane(name); if (pane.window == nullptr) { continue; } auto *tb = wxDynamicCast(pane.window, wxAuiToolBar); if (tb != nullptr) { tb->Realize(); } pane.window->InvalidateBestSize(); // Not wxDefaultSize: only AddPane() measures that again, Update() would use it as is. pane.BestSize(pane.window->GetBestSize()) .MinSize(wxDefaultSize) .FloatingSize(wxDefaultSize); } aui.Update(); ReflowToolbars(); } void RefreshToolBar() { for (const auto &name : GetToolbarPaneNames()) { DestroyToolbarPane(name); } toolbaricons.clear(); auto AddToolbarIcon = [&](wxAuiToolBar *tb, const wxChar *name, int action, const wxString &icon, wxItemKind kind = wxITEM_NORMAL) { toolbaricons.push_back({tb, action, icon}); tb->AddTool(action, name, LoadToolbarIcon(icon), name, kind); }; auto NewToolbar = [&]() { return new wxAuiToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_PLAIN_BACKGROUND); }; auto FinishToolbar = [&](wxAuiToolBar *tb, const char *name, const wxString &caption) { tb->Realize(); aui.AddPane(tb, wxAuiPaneInfo() .Name(name) .Caption(caption) .ToolbarPane() .Top() .Row(0) .LeftDockable(false) .RightDockable(false) .Gripper(true)); }; auto AddToolbarLabel = [&](wxAuiToolBar *tb, const wxString &label) { tb->AddControl(new wxStaticText(tb, wxID_ANY, label)); }; auto *filetb = NewToolbar(); AddToolbarIcon(filetb, _("New (CTRL+n)"), wxID_NEW, "filenew"); AddToolbarIcon(filetb, _("Open (CTRL+o)"), wxID_OPEN, "fileopen"); AddToolbarIcon(filetb, _("Save (CTRL+s)"), wxID_SAVE, "filesave"); AddToolbarIcon(filetb, _("Save as..."), wxID_SAVEAS, "filesaveas"); FinishToolbar(filetb, "filetb", _("File operations")); auto *edittb = NewToolbar(); AddToolbarIcon(edittb, _("Undo (CTRL+z)"), wxID_UNDO, "undo"); AddToolbarIcon(edittb, _("Copy (CTRL+c)"), wxID_COPY, "editcopy"); AddToolbarIcon(edittb, _("Paste (CTRL+v)"), wxID_PASTE, "editpaste"); AddToolbarIcon(edittb, _("Paste Style Only (CTRL+SHIFT+v)"), A_PASTESTYLE, "pastestyle"); FinishToolbar(edittb, "edittb", _("Edit operations")); auto *zoomtb = NewToolbar(); AddToolbarIcon(zoomtb, _("Zoom In (CTRL+mousewheel)"), A_ZOOMIN, "zoomin"); AddToolbarIcon(zoomtb, _("Zoom Out (CTRL+mousewheel)"), A_ZOOMOUT, "zoomout"); FinishToolbar(zoomtb, "zoomtb", _("Zoom operations")); auto *celltb = NewToolbar(); AddToolbarIcon(celltb, _("New Grid (INS)"), A_ENTERGRID, "newgrid"); AddToolbarIcon(celltb, _("Add Image"), A_IMAGE, "image"); AddToolbarIcon(celltb, _("Run"), wxID_EXECUTE, "run"); FinishToolbar(celltb, "celltb", _("Cell operations")); auto *findtb = NewToolbar(); AddToolbarLabel(findtb, _("Search ")); findtb->AddControl(filter = new TSTextCtrl(findtb, A_SEARCH, "", wxDefaultPosition, FromDIP(wxSize(80, 22)), wxWANTS_CHARS)); AddToolbarIcon(findtb, _("Clear search"), A_CLEARSEARCH, "cancel"); AddToolbarIcon(findtb, _("Go to Next Search Result"), A_SEARCHNEXT, "search"); FinishToolbar(findtb, "findtb", _("Find operations")); auto *repltb = NewToolbar(); AddToolbarLabel(repltb, _("Replace ")); repltb->AddControl(replaces = new TSTextCtrl(repltb, A_REPLACE, "", wxDefaultPosition, FromDIP(wxSize(80, 22)), wxWANTS_CHARS)); AddToolbarIcon(repltb, _("Clear replace"), A_CLEARREPLACE, "cancel"); AddToolbarIcon(repltb, _("Replace in selection"), A_REPLACEONCE, "replace"); AddToolbarIcon(repltb, _("Replace All"), A_REPLACEALL, "replaceall"); FinishToolbar(repltb, "repltb", _("Replace operations")); auto *formulatb = NewToolbar(); AddToolbarLabel(formulatb, _("Formula ")); #if defined(__WXGTK3__) && defined(TREESHEETS_USE_PANGO) // wxGTK turns wxTE_PROCESS_ENTER off while the suggestions are shown, but can lose // count of them, so that ENTER applies the formula rather than picking a suggestion. // GTK emits "activate" only for an ENTER that the suggestions don't take. formulatb->AddControl(formulabar = new TSTextCtrl(formulatb, A_FORMULABAR, "", wxDefaultPosition, FromDIP(wxSize(240, 22)), wxWANTS_CHARS)); g_signal_connect(formulabar->GetHandle(), "activate", G_CALLBACK(+[](GtkEntry *, TSFrame *frame) { frame->OnFormulaBarEnter(); }), this); #else formulatb->AddControl(formulabar = new TSTextCtrl( formulatb, A_FORMULABAR, "", wxDefaultPosition, FromDIP(wxSize(240, 22)), wxWANTS_CHARS | wxTE_PROCESS_ENTER)); formulabar->Bind(wxEVT_TEXT_ENTER, [this](wxCommandEvent &) { OnFormulaBarEnter(); }); #endif formulabar->AutoComplete(formulacompleter = new FormulaCompleter); #ifdef __WXMAC__ // wxOSX shows the suggestions only for Cocoa's complete: (ESCAPE, which leaves the // formula bar), so show them after each change, as on the other platforms, but not // after deleting or while moving in the list. complete: inserts the first one, also // a change, and only works after Cocoa is done with the key or the chosen one. // wxOSX drops suggestions that don't start with the text, also by case. formulabar->Bind(wxEVT_KEY_DOWN, [this](wxKeyEvent &ke) { auto k = ke.GetKeyCode(); formulabarskip = k == WXK_BACK || k == WXK_DELETE || k == WXK_UP || k == WXK_DOWN; ke.Skip(); }); formulabar->Bind(wxEVT_TEXT, [this](wxCommandEvent &ce) { ce.Skip(); if (std::exchange(formulabarskip, false) || formulabarcompleting) { return; } CallAfter([this] { auto s = formulabar->GetValue(); wxArrayString res; formulacompleter->GetCompletions(s, res); if (res.empty()) { return; } if (!res[0].StartsWith(s)) { formulabar->ChangeValue(res[0].Left(s.Len())); formulabar->SetInsertionPointEnd(); } formulabarcompleting = true; ShowMacCompletions(formulabar->GetHandle()); formulabarcompleting = false; }); }); #endif // Keys without CTRL or ALT, such as ENTER and the arrows, are for the formula bar and its // suggestions rather than the menu shortcuts. Others are as in any text control. formulabar->Bind(wxEVT_ACCELERATOR_KEY, [](wxAcceleratorKeyEvent &ae) { if (ae.CmdDown() || ae.AltDown()) { ae.Skip(); } }); // The document doesn't change while typing in the formula bar, so its names don't either. formulabar->Bind(wxEVT_SET_FOCUS, [this](wxFocusEvent &fe) { auto *canvas = GetCurrentTab(); auto *c = canvas != nullptr ? canvas->doc->selected.GetCell() : nullptr; formulacompleter->SetNames(c != nullptr ? FormulaEvaluator::Names(c) : vector()); fe.Skip(); }); FinishToolbar(formulatb, "formulatb", _("Formula bar")); auto GetColorIndex = [&](int targetcolor, int defaultindex) { for (auto i = 1; i < celltextcolors.size(); ++i) { if (celltextcolors[i] == targetcolor) { return i; } } if (sys->customcolor == targetcolor) { return 0; } return defaultindex; }; auto *cellcolortb = NewToolbar(); AddToolbarLabel(cellcolortb, _("Cell ")); cellcolortb->AddControl(cellcolordropdown = new ColorDropdown( cellcolortb, A_CELLCOLOR, GetColorIndex(sys->lastcellcolor, 1))); FinishToolbar(cellcolortb, "cellcolortb", _("Cell color operations")); auto *textcolortb = NewToolbar(); AddToolbarLabel(textcolortb, _("Text ")); textcolortb->AddControl(textcolordropdown = new ColorDropdown( textcolortb, A_TEXTCOLOR, GetColorIndex(sys->lasttextcolor, 2))); FinishToolbar(textcolortb, "textcolortb", _("Text color operations")); auto *bordercolortb = NewToolbar(); AddToolbarLabel(bordercolortb, _("Border ")); bordercolortb->AddControl(bordercolordropdown = new ColorDropdown( bordercolortb, A_BORDCOLOR, GetColorIndex(sys->lastbordcolor, 7))); FinishToolbar(bordercolortb, "bordercolortb", _("Border color operations")); auto *imagetb = NewToolbar(); AddToolbarLabel(imagetb, _("Image ")); imagetb->AddControl(imagedropdown = new ImageDropdown(imagetb, "nuvola/dropdown/")); FinishToolbar(imagetb, "imagetb", _("Image operations")); // Last, so that on narrow windows, where toolbars get cut off, it doesn't push the others // out. The pressed state of these follows the selected text, see OnUpdateStyle. auto *styletb = NewToolbar(); AddToolbarIcon(styletb, _("Bold (CTRL+b)"), wxID_BOLD, "bold", wxITEM_CHECK); AddToolbarIcon(styletb, _("Italic (CTRL+i)"), wxID_ITALIC, "italic", wxITEM_CHECK); AddToolbarIcon(styletb, _("Underline (CTRL+u)"), wxID_UNDERLINE, "underline", wxITEM_CHECK); AddToolbarIcon(styletb, _("Strikethrough (CTRL+t)"), wxID_STRIKETHROUGH, "strikethrough", wxITEM_CHECK); AddToolbarIcon(styletb, _("Typewriter (CTRL+ALT+t)"), A_TT, "typewriter", wxITEM_CHECK); // Pressed when the selected text has a link, see OnUpdateNoteOrLink. AddToolbarIcon(styletb, _("Link (SHIFT+F5)"), A_HYPERLINK, "link", wxITEM_CHECK); FinishToolbar(styletb, "styletb", _("Text style operations")); auto *notetb = NewToolbar(); // Pressed when the selected cell has a note, see OnUpdateNoteOrLink. AddToolbarIcon(notetb, _("Edit Note (CTRL+e)"), A_EDITNOTE, "note", wxITEM_CHECK); FinishToolbar(notetb, "notetb", _("Note operations")); // The pressed state of these follows the selected cells, see OnUpdateTextAlign and // OnUpdateVertAlign. auto *aligntb = NewToolbar(); AddToolbarIcon(aligntb, _("Align automatically (CTRL+SHIFT+d)"), A_ALIGNAUTO, "alignauto", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Align left (CTRL+SHIFT+l)"), A_ALIGNLEFT, "alignleft", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Center (CTRL+SHIFT+e)"), A_ALIGNCENTER, "aligncenter", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Align right (CTRL+SHIFT+r)"), A_ALIGNRIGHT, "alignright", wxITEM_CHECK); aligntb->AddSeparator(); AddToolbarIcon(aligntb, _("Align vertically automatically"), A_VALIGNAUTO, "valignauto", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Align top (CTRL+SHIFT+y)"), A_ALIGNTOP, "aligntop", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Align middle (CTRL+SHIFT+h)"), A_ALIGNMIDDLE, "alignmiddle", wxITEM_CHECK); AddToolbarIcon(aligntb, _("Align bottom (CTRL+SHIFT+n)"), A_ALIGNBOTTOM, "alignbottom", wxITEM_CHECK); FinishToolbar(aligntb, "aligntb", _("Text alignment operations")); auto *artprovider = aui.GetArtProvider(); artprovider->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0); } using ToolbarLayout = std::map>; ToolbarLayout preferredlayout; // rows as arranged by the user, ignoring window width ToolbarLayout appliedlayout; // what the last reflow produced // wxAuiManager never wraps docked toolbars, those that don't fit in a row are cut off. So // split rows that are too wide ourselves. Rows the user arranged are remembered and restored // once the window is wide enough again. void ReflowToolbars() { std::vector toolbars; ToolbarLayout current; auto &panes = aui.GetAllPanes(); for (size_t i = 0; i < panes.GetCount(); i++) { auto &pane = panes.Item(i); if (pane.IsToolbar() && pane.IsShown() && pane.IsDocked() && pane.dock_direction == wxAUI_DOCK_TOP && pane.window != nullptr) { toolbars.push_back(&pane); current[pane.name] = {pane.dock_row, pane.dock_pos}; } } if (toolbars.empty()) { return; } // If the layout is not what we produced, the user (or a perspective) changed it. if (current != appliedlayout) { preferredlayout = current; } auto preferred = [&](const wxAuiPaneInfo *p) { auto it = preferredlayout.find(p->name); return it != preferredlayout.end() ? it->second : current[p->name]; }; std::stable_sort(toolbars.begin(), toolbars.end(), [&](const wxAuiPaneInfo *a, const wxAuiPaneInfo *b) { return preferred(a) < preferred(b); }); auto maxwidth = GetClientSize().x; auto row = -1; auto pos = 0; auto used = 0; auto prefrow = 0; for (auto *pane : toolbars) { // Includes the toolbar's own gripper, wxAuiManager's is turned off for toolbars. auto width = pane->window->GetBestSize().x; auto pr = preferred(pane).first; if (row < 0 || pr != prefrow || used + width > maxwidth) { row++; pos = 0; used = 0; prefrow = pr; } pane->Row(row).Position(pos++); used += width; } ToolbarLayout wanted; for (auto *pane : toolbars) { wanted[pane->name] = {pane->dock_row, pane->dock_pos}; } if (wanted != current) { aui.Update(); } appliedlayout.clear(); for (auto *pane : toolbars) { appliedlayout[pane->name] = {pane->dock_row, pane->dock_pos}; } } // The perspective to persist: like the current one, but with toolbar rows as arranged by the // user rather than as split up by ReflowToolbars for the current window width. wxString SavePreferredPerspective() { auto &panes = aui.GetAllPanes(); std::vector> restore; ToolbarLayout current; for (size_t i = 0; i < panes.GetCount(); i++) { auto &pane = panes.Item(i); if (pane.IsToolbar() && pane.IsShown() && pane.IsDocked() && pane.dock_direction == wxAUI_DOCK_TOP && pane.window != nullptr) current[pane.name] = {pane.dock_row, pane.dock_pos}; } // Only if the layout is still what the last reflow produced, otherwise the user changed // it since and it is the preferred one. if (current == appliedlayout) { for (size_t i = 0; i < panes.GetCount(); i++) { auto &pane = panes.Item(i); auto it = preferredlayout.find(pane.name); if (it == preferredlayout.end() || !current.count(pane.name)) continue; restore.emplace_back(&pane, pane.dock_row, pane.dock_pos); pane.Row(it->second.first).Position(it->second.second); } } auto perspective = aui.SavePerspective(); for (auto &[pane, row, pos] : restore) pane->Row(row).Position(pos); return perspective; } void OnSize(wxSizeEvent &se) { se.Skip(); ReflowToolbars(); } void AppOnEventLoopEnter() { watcher = new wxFileSystemWatcher(); watcher->SetOwner(this); Connect(wxEVT_FSWATCHER, wxFileSystemWatcherEventHandler(TSFrame::OnFileSystemEvent)); } // event handling functions // Shows whether the selected text has a style in the check state of its menu item, and of // its toolbar button if it has one. void OnUpdateStyle(wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); auto bit = 0; switch (ue.GetId()) { case wxID_BOLD: bit = STYLE_BOLD; break; case wxID_ITALIC: bit = STYLE_ITALIC; break; case A_TT: bit = STYLE_FIXED; break; case wxID_UNDERLINE: bit = STYLE_UNDERLINE; break; case wxID_STRIKETHROUGH: bit = STYLE_STRIKETHRU; break; } ue.Check(canvas != nullptr && bit != 0 && canvas->doc->SelectionHasStyle(bit)); } // Checks the alignment all selected cells have, if they have the same one. void OnUpdateTextAlign(wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && canvas->doc->SelectionHasTextAlign(ue.GetId() - A_ALIGNAUTO + TEXTALIGN_AUTO)); } // Checks the vertical alignment all selected cells have, if they have the same one. void OnUpdateVertAlign(wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && canvas->doc->SelectionHasVertAlign(ue.GetId() - A_VALIGNAUTO + VERTALIGN_AUTO)); } // Checks the border width of the grid the selection is in. void OnUpdateBorder(wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && canvas->doc->selected.grid && canvas->doc->selected.grid->user_grid_outer_spacing == ue.GetId() - A_BORD0 + 1); } // Asks GitHub for the latest release, see OnUpdateCheck(). Without wxWebRequest, opens the // releases page instead. wxString CheckForUpdates() { #if wxUSE_WEBREQUEST if (updaterequest.IsOk() && updaterequest.GetState() == wxWebRequest::State_Active) { return _("Checking for updates..."); } updaterequest = wxWebSession::GetDefault().CreateRequest( this, "https://api.github.com/repos/aardappel/treesheets/releases/latest", A_CHECKUPDATES); updaterequest.SetHeader("Accept", "application/vnd.github+json"); updaterequest.SetHeader("User-Agent", "TreeSheets/" PACKAGE_VERSION); updaterequest.Start(); return _("Checking for updates..."); #else wxLaunchDefaultBrowser(releasesurl); return wxEmptyString; #endif } #if wxUSE_WEBREQUEST // Tells whether the latest release is newer than this version, and offers to open its // page. A version that is not a release, e.g. of a local build, counts as older. void OnUpdateCheck(wxWebRequestEvent &we) { auto state = we.GetState(); if (state != wxWebRequest::State_Completed && state != wxWebRequest::State_Failed) { return; } SetStatus(wxEmptyString); const auto title = _("Check for Updates"); if (state == wxWebRequest::State_Failed) { wxMessageBox(wxString::Format(_("Could not check for updates: %s"), we.GetErrorDescription()), title, wxOK | wxICON_ERROR, this); return; } // The release is a JSON object with one "tag_name": "vX.Y.Z". auto json = we.GetResponse().AsString(); auto key = json.find("\"tag_name\""); auto start = key == wxString::npos ? key : json.find('"', json.find(':', key) + 1); auto end = start == wxString::npos ? start : json.find('"', start + 1); auto tag = end == wxString::npos ? wxString() : json.Mid(start + 1, end - start - 1); wxString available; auto version = [](const wxString &s, std::array &v) { return wxSscanf(s, "%d.%d.%d", &v[0], &v[1], &v[2]) == 3; }; std::array latest {}, current {}; if (!tag.StartsWith("v", &available) || !version(available, latest)) { wxMessageBox(_("Could not check for updates: no release found."), title, wxOK | wxICON_ERROR, this); } else if (version(PACKAGE_VERSION, current) && !(current < latest)) { wxMessageBox(wxString::Format(_("TreeSheets %s is the latest version."), PACKAGE_VERSION), title, wxOK | wxICON_INFORMATION, this); } else if (wxMessageBox(wxString::Format(_("TreeSheets %s is available, you have " "%s.\nDo you want to open its download " "page?"), available, PACKAGE_VERSION), title, wxYES_NO | wxICON_INFORMATION, this) == wxYES) { wxLaunchDefaultBrowser(wxString(releasesurl) + "/tag/" + tag); } } #endif // Shows whether the selected cell has a note, or the selected text a link (see // Document::SelectedLink()), by checking its toolbar button. The menu items can't be checked. void OnUpdateNoteOrLink(wxUpdateUIEvent &ue) { if (wxDynamicCast(ue.GetEventObject(), wxAuiToolBar) == nullptr) { return; } auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && (ue.GetId() == A_EDITNOTE ? canvas->doc->SelectionHasNote() : canvas->doc->SelectionHasLink())); } // Checks the cell type all selected cells have, if they have the same one. void OnUpdateCellType(wxUpdateUIEvent &ue) { auto *canvas = GetCurrentTab(); ue.Check(canvas != nullptr && canvas->doc->SelectionHasCellType(Document::MarkCellType(ue.GetId()))); } void OnMenu(wxCommandEvent &ce) { auto *canvas = GetCurrentTab(); if (canvas == nullptr) { return; } auto *focus = wxWindow::FindFocus(); if (focus != nullptr && (focus == filter || focus == replaces || focus == formulabar)) { auto *tc = static_cast(focus); long from = 0; long to = 0; tc->GetSelection(&from, &to); switch (ce.GetId()) { #if defined(__WXMAC__) // FIXME: have to emulate this behavior on Mac because menu always captures these events (??) // (on Windows this is handled by TSTextCtrl::MSWShouldPreProcessMessage) case A_MLEFT: case A_LEFT: if (from != to) tc->SetInsertionPoint(from); else if (from) tc->SetInsertionPoint(from - 1); return; case A_MRIGHT: case A_RIGHT: if (from != to) tc->SetInsertionPoint(to); else if (to < tc->GetLineLength(0)) tc->SetInsertionPoint(to + 1); return; case A_SHOME: tc->SetSelection(0, to); return; case A_SEND: tc->SetSelection(from, 1000); return; case A_SCLEFT: case A_SLEFT: if (from) tc->SetSelection(from - 1, to); return; case A_SCRIGHT: case A_SRIGHT: if (to < tc->GetLineLength(0)) tc->SetSelection(from, to + 1); return; case A_BACKSPACE: tc->Remove(from - (from == to), to); return; case A_DELETE: tc->Remove(from, to + (from == to)); return; case A_HOME: tc->SetSelection(0, 0); return; case A_END: tc->SetSelection(1000, 1000); return; case wxID_SELECTALL: tc->SetSelection(0, 1000); return; #endif } } // Store a checkbox menu item in a system variable and persist it in the config. auto Toggle = [&](const wxString &cfg, auto &var) { sys->cfg->Write(cfg, var = ce.IsChecked()); }; // Persist a radio menu item group whose ids start at `first`. auto Choose = [&](const wxString &cfg, auto &var, int first) { sys->cfg->Write(cfg, static_cast(var = ce.GetId() - first)); }; switch (ce.GetId()) { case A_NOP: break; case A_ALEFT: canvas->CursorScroll(-g_scrollratecursor, 0); break; case A_ARIGHT: canvas->CursorScroll(g_scrollratecursor, 0); break; case A_AUP: canvas->CursorScroll(0, -g_scrollratecursor); break; case A_ADOWN: canvas->CursorScroll(0, g_scrollratecursor); break; case A_RESETPERSPECTIVE: RefreshToolBar(); sys->showtoolbar = true; aui.Update(); ReflowToolbars(); break; case A_SHOWSBAR: if (!IsFullScreen()) { sys->cfg->Write("showstatusbar", sys->showstatusbar = ce.IsChecked()); auto *wsb = GetStatusBar(); wsb->Show(sys->showstatusbar); SendSizeEvent(); Refresh(); wsb->Refresh(); } break; case A_SHOWTBAR: if (!IsFullScreen()) { sys->cfg->Write("showtoolbar", sys->showtoolbar = ce.IsChecked()); for (const auto &name : GetToolbarPaneNames()) { aui.GetPane(name).Show(sys->showtoolbar); } aui.Update(); } break; case A_COLORS: if (ColorsDialog dlg(this); dlg.ShowModal() == wxID_OK) { dlg.Apply(); Refresh(); } break; #ifdef ENABLE_LOBSTER case A_RUNSCRIPT: { auto filename = ::wxFileSelector( _("Please select the Lobster script to run:"), ScriptDir(), "", "lobster", _("Lobster Files (*.lobster)|*.lobster|All Files (*.*)|*.*"), wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); if (!filename.IsEmpty()) { RunScript(filename); } break; } case A_RUNSCRIPTCODE: { wxDialog dlg(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); wxButton *openfrommenu {nullptr}, *saveadd {nullptr}; // Shows the file the code came from, and what can be done with it. auto update = [&] { dlg.SetTitle(scriptfile.IsEmpty() ? _("Run Lobster code") : _("Run Lobster code") + " - " + scriptfile); openfrommenu->Enable(!sys->scripts.IsEmpty()); saveadd->Enable(sys->scripts.Index(scriptfile) == wxNOT_FOUND); }; auto *sizer = new wxBoxSizer(wxVERTICAL); wxTextCtrl text(&dlg, wxID_ANY, scriptcode, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_DONTWRAP); text.SetFont(wxFont(wxFontInfo().Family(wxFONTFAMILY_TELETYPE))); sizer->Add(&text, 1, wxEXPAND | wxALL, 10); auto openscript = [&](const wxString &filename) { wxString code; if (wxFFile file(filename); !file.IsOpened() || !file.ReadAll(&code)) { wxMessageBox(_("Cannot open file."), filename, wxOK, &dlg); return; } text.SetValue(code); scriptfile = filename; update(); }; // Saves to the file the code came from, or else asks for one. auto savescript = [&](bool addtomenu) { auto filename = scriptfile; if (filename.IsEmpty()) { filename = ::wxFileSelector( _("Choose Lobster file to write"), sys->scripts.IsEmpty() ? wxString() : ScriptDir(), "", "lobster", _("Lobster Files (*.lobster)|*.lobster|All Files (*.*)|*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, &dlg); if (filename.IsEmpty()) return; if (!wxFileName(filename).HasExt()) { filename.Append(".lobster"); } } if (wxFile file; !file.Create(filename, true) || !file.Write(text.GetValue())) { wxMessageBox(_("Error writing to file!"), filename, wxOK, &dlg); return; } scriptfile = filename; if (addtomenu) { AddToList(sys->scripts, filename); UpdateScriptMenu(scriptmenu); } update(); }; auto *buttons = new wxBoxSizer(wxHORIZONTAL); auto addbutton = [&](const wxString &label, auto onclick) { auto *button = new wxButton(&dlg, wxID_ANY, label); button->Bind(wxEVT_BUTTON, [=](wxCommandEvent &) { onclick(); }); buttons->Add(button, 0, wxRIGHT, 5); return button; }; addbutton(_("&Open..."), [&] { auto filename = ::wxFileSelector( _("Please select the Lobster script to open:"), ScriptDir(), "", "lobster", _("Lobster Files (*.lobster)|*.lobster|All Files (*.*)|*.*"), wxFD_OPEN | wxFD_FILE_MUST_EXIST, &dlg); if (!filename.IsEmpty()) { openscript(filename); } }); openfrommenu = addbutton(_("Open from &Menu..."), [&] { wxSingleChoiceDialog choice(&dlg, _("Please select the script to open:"), _("Open from Menu"), sys->scripts); if (choice.ShowModal() == wxID_OK && choice.GetSelection() >= 0) { openscript(sys->scripts[choice.GetSelection()]); } }); addbutton(_("&Save"), [&] { savescript(false); }); saveadd = addbutton(_("Save and &Add to Menu"), [&] { savescript(true); }); update(); buttons->AddStretchSpacer(); buttons->Add(dlg.CreateButtonSizer(wxOK | wxCANCEL)); sizer->Add(buttons, 0, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); dlg.FindWindow(wxID_OK)->SetLabel(_("&Run")); // At least as wide as the buttons, which are wider in some languages. dlg.SetSizerAndFit(sizer); auto size = dlg.GetSize(); size.IncTo(FromDIP(wxSize(760, 480))); dlg.SetSize(size); text.SetFocus(); auto run = dlg.ShowModal() == wxID_OK; scriptcode = text.GetValue(); if (run && !scriptcode.IsEmpty()) { RunScript(scriptfile.IsEmpty() ? wxString("code") : scriptfile, scriptcode.utf8_string()); } break; } case A_ADDSCRIPT: { wxArrayString filenames; GetFilesFromUser(filenames, this, _("Please select Lobster script file(s):"), _("Lobster Files (*.lobster)|*.lobster|All Files (*.*)|*.*"), ScriptDir()); if (!filenames.IsEmpty()) { for (auto &filename : filenames) { AddToList(sys->scripts, filename); } UpdateScriptMenu(scriptmenu); } break; } case A_DETSCRIPT: if (RemoveFromList( sys->scripts, _("Please select the script you want to remove from the list:"), _("Remove script from list..."))) { UpdateScriptMenu(scriptmenu); } break; #endif #ifdef TS_AGENT_SERVER case A_AGENTSERVER: scriptmenu->Check(A_AGENTSERVER, app->ToggleAgentServer()); SetStatus(app->agent_server ? wxString::Format(_("Agent socket: %s"), app->agent_server->endpoint_path) : _("Agent socket closed")); break; #endif case A_OPENTEMPLATE: { wxArrayString filenames; GetFilesFromUser( filenames, this, _("Please select the TreeSheets file(s) to create documents from:"), _("TreeSheets Files (*.cts)|*.cts|All Files (*.*)|*.*"), TemplateDir()); for (auto &filename : filenames) { sys->Open(filename, true); } break; } case A_ADDTEMPLATE: { wxArrayString filenames; GetFilesFromUser(filenames, this, _("Please select the TreeSheets file(s) to add as templates:"), _("TreeSheets Files (*.cts)|*.cts|All Files (*.*)|*.*"), TemplateDir()); for (auto &filename : filenames) { AddToList(sys->templates, filename); } UpdateTemplateMenu(); break; } case A_ADDCURTEMPLATE: // A template is a file, so the document needs one. if (canvas->doc->filename.IsEmpty()) { SetStatus(_("Please save the document first.")); break; } AddToList(sys->templates, canvas->doc->filename); UpdateTemplateMenu(); break; case A_DETTEMPLATE: if (RemoveFromList( sys->templates, _("Please select the template you want to remove from the list:"), _("Remove template from list..."))) { UpdateTemplateMenu(); } break; case A_DEFAULTMAXCOLWIDTH: { int w = wxGetNumberFromUser(_("Please enter the default column width:"), _("Width"), _("Default column width"), sys->defaultmaxcolwidth, 1, 1000, sys->frame); if (w > 0) { sys->cfg->Write("defaultmaxcolwidth", sys->defaultmaxcolwidth = w); } break; } case A_BOTTOMTABS: { Toggle("bottomtabs", sys->bottomtabs); auto style = notebook->GetWindowStyleFlag() & ~(wxAUI_NB_TOP | wxAUI_NB_BOTTOM); notebook->SetWindowStyleFlag(style | GetTabPosition()); notebook->SendSizeEvent(); notebook->Refresh(); break; } case A_SINGLETRAY: Toggle("singletray", sys->singletray); UpdateTaskBarIconEvents(); break; case A_MAKEBAKS: Toggle("makebaks", sys->makebaks); break; case A_TOTRAY: Toggle("totray", sys->totray); break; case A_MINCLOSE: Toggle("minclose", sys->minclose); break; case A_STARTMINIMIZED: Toggle("startminimized", sys->startminimized); break; case A_GLOBALKEY: Toggle("globalkey", sys->globalkey); UpdateGlobalKey(); break; case A_ZOOMSCR: Toggle("zoomscroll", sys->zoomscroll); break; case A_THINSELC: Toggle("thinselc", sys->thinselc); break; case A_HOVERZOOM: Toggle("hoverzoom", sys->hoverzoom); break; case A_HOVERSHADOW: Toggle("hovershadow", sys->hovershadow); if (!sys->hovershadow) { loop(i, notebook->GetPageCount()) { auto *tab = dynamic_cast(notebook->GetPage(i)); tab->doc->SetHoverShade(wxRect()); } } break; case A_AUTOSAVE: Toggle("autosave", sys->autosave); break; case A_SAVEDISMISS: Toggle("savedismiss", sys->savedismiss); break; case A_CENTERED: Toggle("centered", sys->centered); if (notebook != nullptr) { loop(i, notebook->GetPageCount()) { dynamic_cast(notebook->GetPage(i))->doc->ResetAnchor(); } } Refresh(); break; case A_SHRINKTEXT: Toggle("shrinktext", sys->shrinktext); if (notebook != nullptr) { loop(i, notebook->GetPageCount()) { auto *canvas = dynamic_cast(notebook->GetPage(i)); canvas->doc->cursorposcache = {}; } } TabsReset(); break; case A_FSWATCH: Toggle("fswatch", sys->fswatch); sys->UpdateFileSystemWatching(); break; case A_DEFAULTIMAGE_PNG: case A_DEFAULTIMAGE_JPEG: Choose("defaultimageformat", sys->defaultimageformat, A_DEFAULTIMAGE_PNG); break; case A_FASTRENDER: Toggle("fastrender", sys->fastrender); Refresh(); break; case A_INNERBORDERCOLOR: Toggle("innerbordercolor", sys->innerbordercolor); Refresh(); break; case A_INVERTRENDER: Toggle("followdarkmode", sys->followdarkmode); sys->UpdatePens(); Refresh(); break; case A_FULLSCREEN: ShowFullScreen(!IsFullScreen()); if (IsFullScreen()) { SetStatus(_("Press F11 to exit fullscreen mode.")); } break; case wxID_FIND: if (filter != nullptr) { filter->SetFocus(); filter->SetSelection(0, 1000); } else { SetStatus(_("Please enable (Options -> Show Toolbar) to use search.")); } break; case A_RESTRICTVIEW: Toggle("restrictview", sys->restrictview); break; case A_FLATCOPY: Toggle("flatcopy", sys->flatcopy); break; case wxID_REPLACE: if (replaces != nullptr) { replaces->SetFocus(); replaces->SetSelection(0, 1000); } else { SetStatus(_("Please enable (Options -> Show Toolbar) to use replace.")); } break; #ifdef __WXMAC__ case wxID_OSX_HIDE: Iconize(true); break; case wxID_OSX_HIDEOTHERS: SetStatus("NOT IMPLEMENTED"); break; case wxID_OSX_SHOWALL: Iconize(false); break; case wxID_ABOUT: canvas->doc->Action(wxID_ABOUT); break; case wxID_PREFERENCES: canvas->doc->Action(wxID_SELECT_FONT); break; #endif case wxID_EXIT: fromclosebox = false; Close(); break; case wxID_CLOSE: canvas->doc->Action(ce.GetId()); break; // canvas dangling pointer on return default: { auto id = ce.GetId(); #ifdef ENABLE_LOBSTER const int tagsend = A_SCRIPT; #else const int tagsend = A_TEMPLATE; #endif if (id >= wxID_FILE1 && id <= wxID_FILE9) { SetStatus(sys->Open(filehistory.GetHistoryFile(id - wxID_FILE1))); } else if (id >= A_TAGSET && id < tagsend) { SetStatus(canvas->doc->TagSet(id - A_TAGSET)); #ifdef ENABLE_LOBSTER } else if (id >= A_SCRIPT && id < A_TEMPLATE) { RunScript(sys->scripts[id - A_SCRIPT]); #endif } else if (id >= A_TEMPLATE && id < A_MAXACTION) { sys->Open(sys->templates[id - A_TEMPLATE], true); } else { // Shift only counts on toolbar buttons, as it is part of some shortcuts. auto recursive = wxDynamicCast(ce.GetEventObject(), wxAuiToolBar) && wxGetKeyState(WXK_SHIFT); SetStatus(canvas->doc->Action(id, recursive)); } // Actions such as cursor movement or select all change the text selection. if (auto *tab = GetCurrentTab()) { UpdateAmountStatus(tab->doc->selected); } break; } } } // Shows the per document settings of the current document. void OnMenuOpen(wxMenuEvent &me) { if (auto *canvas = GetCurrentTab()) { auto *menubar = GetMenuBar(); menubar->Check(A_AUTOEXPORT_HTML_NONE + canvas->doc->autohtmlexport, true); #ifdef ENABLE_WXPDFDOC menubar->Check(A_AUTOEXPORT_PDF, canvas->doc->autopdfexport); #endif } me.Skip(); } void OnTabChange(wxAuiNotebookEvent &nbe) { nbe.Skip(); // wx 3.3.4 also sends this when the last page was deleted. if (nbe.GetSelection() == wxNOT_FOUND) { return; } ActivateTab(dynamic_cast(notebook->GetPage(nbe.GetSelection()))); } static void LayOutIfStale(Document *doc) { if (!doc->layoutstale) { return; } doc->layoutstale = false; doc->UpdateLayout(); doc->ScrollIfSelectionOutOfView(); } void ActivateTab(TSCanvas *canvas) { LayOutIfStale(canvas->doc.get()); canvas->SetFocus(); canvas->doc->UpdateFileName(); UpdateStatus(canvas->doc->selected, true); } void OnTabClose(wxAuiNotebookEvent &nbe) { auto *canvas = dynamic_cast(notebook->GetPage(nbe.GetSelection())); if (notebook->GetPageCount() <= 1) { nbe.Veto(); Close(); } else if (canvas->doc->CloseDocument()) { nbe.Veto(); } else { nbe.Skip(); } } void OnTabClosed(wxAuiNotebookEvent &nbe) { sys->PurgeUnusedImages(); nbe.Skip(); } void OnSearch(wxCommandEvent &ce) { auto searchstring = ce.GetString(); sys->darkennonmatchingcells = searchstring.Len() != 0; sys->searchstring = sys->casesensitivesearch ? searchstring : searchstring.Lower(); GetCurrentTab()->Refresh(); } void OnCharHook(wxKeyEvent &ke) { auto *canvas = GetCurrentTab(); if (!canvas) return; auto *textctrl = wxDynamicCast(ke.GetEventObject(), wxTextCtrl); if (ke.GetId() == A_FORMULABAR) { // ESCAPE leaves the selected cell unchanged, see OnFormulaBarEnter() for ENTER. if (ke.GetKeyCode() == WXK_ESCAPE) { canvas->SetFocus(); } else { ke.Skip(); } return; } switch (ke.GetKeyCode()) { case WXK_RETURN: { auto issearch = ke.GetId() == A_SEARCH; if (issearch) { if (textctrl && textctrl->IsEmpty()) { canvas->SetFocus(); return; } } if (canvas->doc) { canvas->doc->Action(issearch ? ke.ShiftDown() ? A_SEARCHPREV : A_SEARCHNEXT : A_REPLACEONCEJ); UpdateAmountStatus(canvas->doc->selected); } return; } case WXK_ESCAPE: { if (textctrl) { textctrl->Clear(); } canvas->SetFocus(); return; } default: { ke.Skip(); } } } // ENTER applies the formula bar to the selected cell. It's not handled in OnCharHook(), since // ENTER in the list of suggestions only picks one. void OnFormulaBarEnter() { auto *canvas = GetCurrentTab(); if (canvas == nullptr) { return; } SetStatus(canvas->doc->SetFormulaBarText(formulabar->GetValue())); canvas->SetFocus(); } void OnChangeColor(wxCommandEvent &ce) { GetCurrentTab()->doc->ColorChange(ce.GetId(), ce.GetInt()); ReFocus(); } void OnDDImage(wxCommandEvent &ce) { if (auto *image = GetEmbeddedImage(imagedropdown->filenames[ce.GetInt()])) { GetCurrentTab()->doc->ImageChange(*image, dd_icon_res_scale); } ReFocus(); } void OnActivate(wxActivateEvent &ae) { // This causes warnings in the debug log, but without it keyboard entry upon window select // doesn't work. ReFocus(); } void OnSizing(wxSizeEvent &se) { se.Skip(); } void OnMaximize(wxMaximizeEvent &me) { ReFocus(); me.Skip(); } void OnIconize(wxIconizeEvent &me) { if (me.IsIconized()) { if (sys->savedismiss) { sys->SaveModified(); } #ifndef __WXMAC__ if (sys->totray) { taskbaricon.SetIcon(icon, "TreeSheets"); Show(false); Iconize(); } #endif } else { #ifdef __WXGTK__ if (sys->totray) { Show(true); } #endif if (TSCanvas *canvas = GetCurrentTab()) { canvas->SetFocus(); } } } void OnTBIDBLClick(wxTaskBarIconEvent &e) { DeIconize(); } void UpdateTaskBarIconEvents() { taskbaricon.Unbind(wxEVT_TASKBAR_LEFT_UP, &TSFrame::OnTBIDBLClick, this); taskbaricon.Unbind(wxEVT_TASKBAR_LEFT_DCLICK, &TSFrame::OnTBIDBLClick, this); taskbaricon.Bind(sys->singletray ? wxEVT_TASKBAR_LEFT_UP : wxEVT_TASKBAR_LEFT_DCLICK, &TSFrame::OnTBIDBLClick, this); } void OnClosing(wxCloseEvent &ce) { bool fcb = fromclosebox; fromclosebox = true; if (fcb && sys->minclose) { ce.Veto(); Iconize(); return; } sys->RememberOpenFiles(); #ifdef ENABLE_LOBSTER sys->WriteList("script", sys->scripts); #endif sys->WriteList("template", sys->templates); if (sys->savedismiss) { sys->SaveModified(); } if (ce.CanVeto()) { // ask to save/discard all files before closing any loop(i, notebook->GetPageCount()) { auto *canvas = dynamic_cast(notebook->GetPage(i)); if (canvas->doc->modified) { notebook->SetSelection(i); if (canvas->doc->CheckForChanges()) { ce.Veto(); return; } } } // all files have been saved/discarded while (notebook->GetPageCount() != 0U) { GetCurrentTab()->doc->RemoveTmpFile(); notebook->DeletePage(notebook->GetSelection()); } } sys->every_second_timer.Stop(); filehistory.Save(*sys->cfg); if (!IsIconized()) { sys->cfg->Write("maximized", IsMaximized()); if (!IsMaximized()) { sys->cfg->Write("resx", GetSize().x); sys->cfg->Write("resy", GetSize().y); sys->cfg->Write("posx", GetPosition().x); sys->cfg->Write("posy", GetPosition().y); } } sys->cfg->Write("notesizex", sys->notesizex); sys->cfg->Write("notesizey", sys->notesizey); sys->cfg->Write("perspective", SavePreferredPerspective()); sys->cfg->Write("lastcellcolor", sys->lastcellcolor); sys->cfg->Write("lasttextcolor", sys->lasttextcolor); sys->cfg->Write("lastbordcolor", sys->lastbordcolor); aui.ClearEventHashTable(); aui.UnInit(); DELETEP(editmenupopup); DELETEP(watcher); Destroy(); } void OnFileSystemEvent(wxFileSystemWatcherEvent &event) { // 0xF == create/delete/rename/modify if ((event.GetChangeType() & 0xF) == 0 || watcherwaitingforuser || notebook == nullptr) { return; } const auto &modfile = event.GetPath().GetFullPath(); loop(i, notebook->GetPageCount()) { Document *doc = dynamic_cast(notebook->GetPage(i))->doc.get(); if (modfile == doc->filename) { auto modtime = wxFileName(modfile).GetModificationTime(); // Compare with last modified to trigger multiple times. if (!modtime.IsValid() || !doc->lastmodificationtime.IsValid() || modtime == doc->lastmodificationtime) { return; } if (doc->modified) { // TODO: this dialog is problematic since it may be on an unattended // computer and more of these events may fire. since the occurrence of this // situation is rare, it may be better to just take the most // recently changed version (which is the one that has just been modified // on disk) this potentially throws away local changes, but this can only // happen if the user left changes unsaved, then decided to go edit an older // version on another computer. // for now, we leave this code active, and guard it with // watcherwaitingforuser auto message = wxString::Format( _("%s\nhas been modified on disk by another program / computer:\nWould you like to discard your changes and re-load from disk?"), doc->filename); watcherwaitingforuser = true; int res = wxMessageBox(message, _("File modification conflict!"), wxYES_NO | wxICON_QUESTION, this); watcherwaitingforuser = false; if (res != wxYES) { return; } } auto message = sys->LoadDB(doc->filename, true, i); if (!message.IsEmpty()) { SetStatus(message); } else { notebook->DeletePage(i + 1); sys->PurgeUnusedImages(); ::wxRemoveFile(treesheets::System::TmpName(modfile)); SetStatus( _("File has been re-loaded because of modifications of another program / computer")); } return; } } } void OnDPIChanged(wxDPIChangedEvent &dce) { // block all other events until we finished preparing wxEventBlocker blocker(this); wxBusyCursor wait; for (const auto &image : sys->imagelist) image->ClearBitmap(); RenderFolderIcon(); // Re-layout after child windows have received their new DPI as well. CallAfter([this]() { RefitToolbars(); TabsReset(); }); dce.Skip(); } void OnSysColourChanged(wxSysColourChangedEvent &se) { sys->UpdatePens(); UpdateToolbarIcons(); se.Skip(); } // helper functions void CycleTabs(int offset = 1) const { auto numtabs = static_cast(notebook->GetPageCount()); if (numtabs == 0) { return; } offset = offset >= 0 ? 1 : numtabs - 1; // normalize to non-negative wrt modulo notebook->SetSelection((notebook->GetSelection() + offset) % numtabs); } void ToggleShown() { if (IsActive() && !IsIconized()) { Iconize(); return; } #ifdef __WXMAC__ ActivateMacApp(); #endif if (IsIconized()) { DeIconize(); } else { Raise(); } } void UpdateGlobalKey() { #if wxUSE_HOTKEY if (globalkeyregistered) { UnregisterHotKey(0); } globalkeyregistered = false; if (!sys->globalkey) { return; } wxAcceleratorEntry key; if (!key.FromString(sys->globalkeyname) || !(globalkeyregistered = RegisterHotKey( 0, (key.GetFlags() & wxACCEL_ALT ? wxMOD_ALT : 0) | (key.GetFlags() & wxACCEL_CTRL ? wxMOD_CONTROL : 0) | (key.GetFlags() & wxACCEL_RAW_CTRL ? wxMOD_RAW_CONTROL : 0) | (key.GetFlags() & wxACCEL_SHIFT ? wxMOD_SHIFT : 0), key.GetKeyCode()))) { SetStatus(wxString::Format(_("Could not register the shortcut %s."), sys->globalkeyname)); } #endif } void DeIconize() { if (!IsIconized()) { RequestUserAttention(); return; } Show(true); Iconize(false); taskbaricon.RemoveIcon(); } TSCanvas *GetCurrentTab() const { return notebook != nullptr ? dynamic_cast(notebook->GetCurrentPage()) : nullptr; } TSCanvas *GetTabByFileName(const wxString &filename) const { if (notebook != nullptr) { loop(i, notebook->GetPageCount()) { auto *canvas = dynamic_cast(notebook->GetPage(i)); if (canvas->doc->filename == filename) { notebook->SetSelection(i); return canvas; } } } return nullptr; } void MyAppend(wxMenu *menu, int tag, const wxString &contents, const wxString &help = "", wxItemKind kind = wxITEM_NORMAL) { auto item = contents; wxString key = ""; if (int pos = contents.Find("\t"); pos >= 0) { item = contents.Mid(0, pos); key = contents.Mid(pos + 1); } key = sys->cfg->Read(item, key); auto newcontents = item; if (!key.IsEmpty()) { newcontents += "\t" + key; } menu->Append(tag, newcontents, help, kind); menustrings[item] = key; } TSCanvas *NewTab(unique_ptr doc, bool append = false, int insert_at = -1) { auto *canvas = new TSCanvas(this, notebook); doc->canvas = canvas; canvas->doc = std::move(doc); canvas->SetScrollRate(1, 1); if (insert_at >= 0) { notebook->InsertPage(insert_at, canvas, _(""), true, wxNullBitmap); } else if (append) { notebook->AddPage(canvas, _(""), true, wxNullBitmap); } else { notebook->InsertPage(0, canvas, _(""), true, wxNullBitmap); } canvas->SetDropTarget(new DropTarget(canvas->doc->dndobjc)); canvas->SetFocus(); return canvas; } void ReFocus() const { if (TSCanvas *canvas = GetCurrentTab()) { canvas->SetFocus(); } } void RenderFolderIcon() { foldicon = LoadEmbeddedBitmap("nuvola/fold.png"); ScaleBitmap(foldicon, FromDIP(1.0) / 3.0, foldicon); foldicons.clear(); } // Fold icon scaled relative to the default text size, so it matches the displayed text. wxBitmap *GetFoldIcon(int textsize) { if (textsize == g_deftextsize || !foldicon.IsOk()) { return &foldicon; } auto it = foldicons.find(textsize); if (it == foldicons.end()) { wxBitmap scaled; ScaleBitmap(foldicon, static_cast(textsize) / g_deftextsize, scaled); it = foldicons.emplace(textsize, scaled).first; } return &it->second; } void SetDPIAwareStatusWidths() { int statusbarfieldwidths[] = {-1, FromDIP(300), FromDIP(120), FromDIP(100), FromDIP(150)}; SetStatusWidths(5, statusbarfieldwidths); } void SetFileAssoc(const wxString &exename) { #ifdef WIN32 SetRegistryKey("HKEY_CURRENT_USER\\Software\\Classes\\.cts", "TreeSheets"); SetRegistryKey("HKEY_CURRENT_USER\\Software\\Classes\\TreeSheets", "TreeSheets file"); SetRegistryKey("HKEY_CURRENT_USER\\Software\\Classes\\TreeSheets\\Shell\\Open\\Command", "\"" + exename + "\" \"%1\""); SetRegistryKey("HKEY_CURRENT_USER\\Software\\Classes\\TreeSheets\\DefaultIcon", "\"" + exename + "\",0"); #else // TODO: do something similar for mac/kde/gnome? #endif } void SetPageTitle(const wxString &filename, const wxString &mods, int page = -1) { if (page < 0) { page = notebook->GetSelection(); } if (page < 0) { return; } if (page == notebook->GetSelection()) { SetTitle("TreeSheets - " + wxFileName(filename).GetFullName() + mods); SetRepresentedFilename(filename); } notebook->SetPageText( page, (filename.empty() ? wxString(_("")) : wxFileName(filename).GetName()) + mods); } #ifdef WIN32 void SetRegistryKey(const wxString &key, wxString value) { wxRegKey registrykey(key); registrykey.Create(); registrykey.SetValue("", value); } #endif void SetStatus(const wxString &message) { if (GetStatusBar() != nullptr && !message.IsEmpty()) { SetStatusText(message, 0); } } void TabsReset() const { if (notebook != nullptr) { // Tabs that aren't shown are laid out once they are, see ActivateTab(). auto *current = GetCurrentTab(); loop(i, notebook->GetPageCount()) { auto *doc = dynamic_cast(notebook->GetPage(i))->doc.get(); doc->root->ResetChildren(); doc->layoutstale = true; if (doc->canvas == current) { LayOutIfStale(doc); } } notebook->Refresh(); notebook->Update(); } } // Shows the formula, or else the text, of the selected cell, unless it's being typed in. void UpdateFormulaBar(Document *doc) { if (formulabar == nullptr || wxWindow::FindFocus() == formulabar) { return; } auto *c = doc->selected.GetCell(); auto s = c == nullptr ? wxString() : c->formula && c != doc->editcell ? *c->formula : c->text.t; if (formulabar->GetValue() != s) { formulabar->ChangeValue(s); } } void UpdateStatus(const Selection &s, bool updateamount) { if (GetStatusBar() != nullptr && s.grid != nullptr) { if (!s.Thin()) { // Aggregate over the selection; for a single cell this is just its own values. int minsize = INT_MAX, maxsize = INT_MIN, minwidth = INT_MAX, maxwidth = INT_MIN; wxDateTime lastedit; for (int x = s.x; x < s.x + s.xs; x++) { minwidth = min(minwidth, s.grid->colwidths[x]); maxwidth = max(maxwidth, s.grid->colwidths[x]); for (int y = s.y; y < s.y + s.ys; y++) { const Cell *c = s.grid->C(x, y).get(); minsize = min(minsize, -c->text.relsize); maxsize = max(maxsize, -c->text.relsize); if (!lastedit.IsValid() || c->text.lastedit > lastedit) { lastedit = c->text.lastedit; } } } auto range = [](int lo, int hi) { return lo == hi ? wxString::Format("%d", lo) : wxString::Format("%d-%d", lo, hi); }; SetStatusText(wxString::Format(_("Size %s"), range(minsize, maxsize)), 3); SetStatusText(wxString::Format(_("Width %s"), range(minwidth, maxwidth)), 2); SetStatusText( wxString::Format(_("Edited %s %s"), lastedit.FormatDate(), lastedit.FormatTime()), 1); } else { for (int field : {1, 2, 3}) { SetStatusText("", field); } } if (updateamount) { UpdateAmountStatus(s); } } } // Shows the number of selected characters while text inside a cell is selected, and the // number of selected cells otherwise. void UpdateAmountStatus(const Selection &s) { if (GetStatusBar() == nullptr || s.grid == nullptr) { return; } auto amount = s.TextEdit() && s.cursor != s.cursorend ? wxString::Format(_("%d character(s)"), abs(s.cursorend - s.cursor)) : wxString::Format(_("%d cell(s)"), s.xs * s.ys); // Avoid touching the status bar when nothing changed. if (GetStatusBar()->GetStatusText(4) != amount) { SetStatusText(amount, 4); } } static void AddToList(wxArrayString &list, const wxString &filename) { if (list.Index(filename) == wxNOT_FOUND) { list.Add(filename); } } // Asks which file to remove from list, and returns whether one was. bool RemoveFromList(wxArrayString &list, const wxString &message, const wxString &caption) { wxSingleChoiceDialog dialog(this, message, caption, list); if (dialog.ShowModal() != wxID_OK || dialog.GetSelection() < 0) { return false; } list.RemoveAt(dialog.GetSelection()); return true; } // The folder of the most recently added template. wxString TemplateDir() const { return sys->templates.IsEmpty() ? wxString() : wxFileName(sys->templates.Last()).GetPath(); } void UpdateTemplateMenu() { auto *menu = templatemenu; while (menu->GetMenuItemCount() > 0) { menu->Destroy(menu->FindItemByPosition(0)); } MyAppend(menu, A_OPENTEMPLATE, _("&Open File as Template..."), _("Create a new document from a copy of a TreeSheets file")); MyAppend(menu, A_ADDTEMPLATE, _("&Add Files as Templates..."), _("Add TreeSheets files to this menu as templates")); MyAppend(menu, A_ADDCURTEMPLATE, _("Add &Current Document as Template"), _("Add the file of the current document to this menu as a template")); MyAppend(menu, A_DETTEMPLATE, _("&Remove Template..."), _("Remove a template from this menu")); if (!sys->templates.IsEmpty()) { menu->AppendSeparator(); } loop(i, static_cast(sys->templates.GetCount())) { MyAppend(menu, A_TEMPLATE + i, wxControl::EscapeMnemonics(wxFileName(sys->templates[i]).GetName()), sys->templates[i]); } } #ifdef ENABLE_LOBSTER // If code is non-empty it is run, and filename only labels its errors. void RunScript(const wxString &filename, std::string_view code = {}) { auto message = tssi.ScriptRun(filename.c_str(), code); message.erase(std::remove(message.begin(), message.end(), '\n'), message.end()); SetStatus(wxString(message)); } // The folder of the most recently added script, or else the bundled scripts. wxString ScriptDir() { wxString path; if (!sys->scripts.IsEmpty()) { path = wxFileName(sys->scripts.Last()).GetPath(); } if (path.IsEmpty() || !wxDirExists(path)) { path = app->GetDataPath("scripts/"); if (!wxDirExists(path)) path.Clear(); } return path; } void UpdateScriptMenu(wxMenu *menu) { if (!menu) return; while (menu->GetMenuItemCount() > 0) { menu->Destroy(menu->FindItemByPosition(0)); } MyAppend(menu, A_RUNSCRIPT, _("&Run File..."), _("Run a Lobster script without adding it to the menu")); MyAppend(menu, A_RUNSCRIPTCODE, _("Run &Code..."), _("Paste or type Lobster code and run it")); MyAppend(menu, A_ADDSCRIPT, _("&Add to Menu...") + "\tCTRL+ALT+L", _("Add Lobster scripts to the menu")); MyAppend(menu, A_DETSCRIPT, _("Re&move from Menu...") + "\tCTRL+SHIFT+ALT+L", _("Remove script from list in the menu")); #ifdef TS_AGENT_SERVER MyAppend(menu, A_AGENTSERVER, _("A&gent Socket"), _("Let AI agents run Lobster scripts on the open document through a " "local socket"), wxITEM_CHECK); menu->Check(A_AGENTSERVER, app->agent_server != nullptr); #endif if (!sys->scripts.IsEmpty()) { menu->AppendSeparator(); } for (size_t i = 0; i < sys->scripts.GetCount(); ++i) { MyAppend(menu, A_SCRIPT + static_cast(i), wxString::Format("%s\tCTRL+ALT+%zu", wxFileName(sys->scripts[i]).GetFullName(), i + 1)); } } #endif };