My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cardreader.cpp 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../inc/MarlinConfig.h"
  23. #if ENABLED(SDSUPPORT)
  24. //#define DEBUG_CARDREADER
  25. #include "cardreader.h"
  26. #include "../MarlinCore.h"
  27. #include "../lcd/marlinui.h"
  28. #if ENABLED(DWIN_CREALITY_LCD)
  29. #include "../lcd/e3v2/creality/dwin.h"
  30. #elif ENABLED(DWIN_LCD_PROUI)
  31. #include "../lcd/e3v2/proui/dwin.h"
  32. #endif
  33. #include "../module/planner.h" // for synchronize
  34. #include "../module/printcounter.h"
  35. #include "../gcode/queue.h"
  36. #include "../module/settings.h"
  37. #include "../module/stepper/indirection.h"
  38. #if ENABLED(EMERGENCY_PARSER)
  39. #include "../feature/e_parser.h"
  40. #endif
  41. #if ENABLED(POWER_LOSS_RECOVERY)
  42. #include "../feature/powerloss.h"
  43. #endif
  44. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  45. #include "../feature/pause.h"
  46. #endif
  47. #define DEBUG_OUT EITHER(DEBUG_CARDREADER, MARLIN_DEV_MODE)
  48. #include "../core/debug_out.h"
  49. #include "../libs/hex_print.h"
  50. // extern
  51. PGMSTR(M21_STR, "M21");
  52. PGMSTR(M23_STR, "M23 %s");
  53. PGMSTR(M24_STR, "M24");
  54. // public:
  55. card_flags_t CardReader::flag;
  56. char CardReader::filename[FILENAME_LENGTH], CardReader::longFilename[LONG_FILENAME_LENGTH];
  57. IF_DISABLED(NO_SD_AUTOSTART, uint8_t CardReader::autofile_index); // = 0
  58. #if ENABLED(BINARY_FILE_TRANSFER)
  59. serial_index_t IF_DISABLED(HAS_MULTI_SERIAL, constexpr) CardReader::transfer_port_index;
  60. #endif
  61. // private:
  62. SdFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH];
  63. uint8_t CardReader::workDirDepth;
  64. #if ENABLED(SDCARD_SORT_ALPHA)
  65. uint16_t CardReader::sort_count;
  66. #if ENABLED(SDSORT_GCODE)
  67. bool CardReader::sort_alpha;
  68. int CardReader::sort_folders;
  69. //bool CardReader::sort_reverse;
  70. #endif
  71. #if ENABLED(SDSORT_DYNAMIC_RAM)
  72. uint8_t *CardReader::sort_order;
  73. #else
  74. uint8_t CardReader::sort_order[SDSORT_LIMIT];
  75. #endif
  76. #if ENABLED(SDSORT_USES_RAM)
  77. #if ENABLED(SDSORT_CACHE_NAMES)
  78. uint16_t CardReader::nrFiles; // Cached total file count
  79. #if ENABLED(SDSORT_DYNAMIC_RAM)
  80. char **CardReader::sortshort, **CardReader::sortnames;
  81. #else
  82. char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH];
  83. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  84. #endif
  85. #elif DISABLED(SDSORT_USES_STACK)
  86. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  87. #endif
  88. #if HAS_FOLDER_SORTING
  89. #if ENABLED(SDSORT_DYNAMIC_RAM)
  90. uint8_t *CardReader::isDir;
  91. #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK)
  92. uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3];
  93. #endif
  94. #define IS_DIR(n) TEST(isDir[(n) >> 3], (n) & 0x07)
  95. #endif
  96. #endif // SDSORT_USES_RAM
  97. #endif // SDCARD_SORT_ALPHA
  98. #if HAS_USB_FLASH_DRIVE
  99. DiskIODriver_USBFlash CardReader::media_driver_usbFlash;
  100. #endif
  101. #if NEED_SD2CARD_SDIO || NEED_SD2CARD_SPI
  102. CardReader::sdcard_driver_t CardReader::media_driver_sdcard;
  103. #endif
  104. DiskIODriver* CardReader::driver = nullptr;
  105. SdVolume CardReader::volume;
  106. SdFile CardReader::file;
  107. #if HAS_MEDIA_SUBCALLS
  108. uint8_t CardReader::file_subcall_ctr;
  109. uint32_t CardReader::filespos[SD_PROCEDURE_DEPTH];
  110. char CardReader::proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
  111. #endif
  112. uint32_t CardReader::filesize, CardReader::sdpos;
  113. CardReader::CardReader() {
  114. changeMedia(&
  115. #if HAS_USB_FLASH_DRIVE && !SHARED_VOLUME_IS(SD_ONBOARD)
  116. media_driver_usbFlash
  117. #else
  118. media_driver_sdcard
  119. #endif
  120. );
  121. #if ENABLED(SDCARD_SORT_ALPHA)
  122. sort_count = 0;
  123. #if ENABLED(SDSORT_GCODE)
  124. sort_alpha = true;
  125. sort_folders = FOLDER_SORTING;
  126. //sort_reverse = false;
  127. #endif
  128. #endif
  129. flag.sdprinting = flag.sdprintdone = flag.mounted = flag.saving = flag.logging = false;
  130. filesize = sdpos = 0;
  131. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  132. IF_DISABLED(NO_SD_AUTOSTART, autofile_cancel());
  133. workDirDepth = 0;
  134. ZERO(workDirParents);
  135. #if ENABLED(SDSUPPORT) && PIN_EXISTS(SD_DETECT)
  136. SET_INPUT_PULLUP(SD_DETECT_PIN);
  137. #endif
  138. #if PIN_EXISTS(SDPOWER)
  139. OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader
  140. #endif
  141. }
  142. //
  143. // Get a DOS 8.3 filename in its useful form
  144. //
  145. char *createFilename(char * const buffer, const dir_t &p) {
  146. char *pos = buffer;
  147. LOOP_L_N(i, 11) {
  148. if (p.name[i] == ' ') continue;
  149. if (i == 8) *pos++ = '.';
  150. *pos++ = p.name[i];
  151. }
  152. *pos++ = 0;
  153. return buffer;
  154. }
  155. //
  156. // Return 'true' if the item is a folder, G-code file or Binary file
  157. //
  158. bool CardReader::is_visible_entity(const dir_t &p OPTARG(CUSTOM_FIRMWARE_UPLOAD, bool onlyBin/*=false*/)) {
  159. //uint8_t pn0 = p.name[0];
  160. #if DISABLED(CUSTOM_FIRMWARE_UPLOAD)
  161. constexpr bool onlyBin = false;
  162. #endif
  163. if ( (p.attributes & DIR_ATT_HIDDEN) // Hidden by attribute
  164. // When readDir() > 0 these must be false:
  165. //|| pn0 == DIR_NAME_FREE || pn0 == DIR_NAME_DELETED // Clear or Deleted entry
  166. //|| pn0 == '.' || longFilename[0] == '.' // Hidden file
  167. //|| !DIR_IS_FILE_OR_SUBDIR(&p) // Not a File or Directory
  168. ) return false;
  169. flag.filenameIsDir = DIR_IS_SUBDIR(&p); // We know it's a File or Folder
  170. setBinFlag(p.name[8] == 'B' && // List .bin files (a firmware file for flashing)
  171. p.name[9] == 'I' &&
  172. p.name[10]== 'N');
  173. return (
  174. flag.filenameIsDir // All Directories are ok
  175. || fileIsBinary() // BIN files are accepted
  176. || (!onlyBin && p.name[8] == 'G'
  177. && p.name[9] != '~') // Non-backup *.G* files are accepted
  178. );
  179. }
  180. //
  181. // Get the number of (compliant) items in the folder
  182. //
  183. int CardReader::countItems(SdFile dir) {
  184. dir_t p;
  185. int c = 0;
  186. while (dir.readDir(&p, longFilename) > 0)
  187. c += is_visible_entity(p);
  188. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  189. nrFiles = c;
  190. #endif
  191. return c;
  192. }
  193. //
  194. // Get file/folder info for an item by index
  195. //
  196. void CardReader::selectByIndex(SdFile dir, const uint8_t index) {
  197. dir_t p;
  198. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0;) {
  199. if (is_visible_entity(p)) {
  200. if (cnt == index) {
  201. createFilename(filename, p);
  202. return; // 0 based index
  203. }
  204. cnt++;
  205. }
  206. }
  207. }
  208. //
  209. // Get file/folder info for an item by name
  210. //
  211. void CardReader::selectByName(SdFile dir, const char * const match) {
  212. dir_t p;
  213. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0; cnt++) {
  214. if (is_visible_entity(p)) {
  215. createFilename(filename, p);
  216. if (strcasecmp(match, filename) == 0) return;
  217. }
  218. }
  219. }
  220. /**
  221. * Recursive method to print all files within a folder in flat
  222. * DOS 8.3 format. This style of listing is the most compatible
  223. * with legacy hosts.
  224. *
  225. * This method recurses to unlimited depth and lists all G-code
  226. * files within the given parent. If the hierarchy is very deep
  227. * this can blow up the stack, so a 'depth' parameter would be a
  228. * good addition.
  229. */
  230. void CardReader::printListing(
  231. SdFile parent, const char * const prepend
  232. OPTARG(CUSTOM_FIRMWARE_UPLOAD, bool onlyBin/*=false*/)
  233. OPTARG(LONG_FILENAME_HOST_SUPPORT, const bool includeLongNames/*=false*/)
  234. OPTARG(LONG_FILENAME_HOST_SUPPORT, const char * const prependLong/*=nullptr*/)
  235. ) {
  236. dir_t p;
  237. while (parent.readDir(&p, longFilename) > 0) {
  238. if (DIR_IS_SUBDIR(&p)) {
  239. size_t lenPrepend = prepend ? strlen(prepend) + 1 : 0;
  240. // Allocate enough stack space for the full path including / separator
  241. char path[lenPrepend + FILENAME_LENGTH];
  242. if (prepend) { strcpy(path, prepend); path[lenPrepend - 1] = '/'; }
  243. char* dosFilename = path + lenPrepend;
  244. createFilename(dosFilename, p);
  245. // Get a new directory object using the full path
  246. // and dive recursively into it.
  247. SdFile child; // child.close() in destructor
  248. if (child.open(&parent, dosFilename, O_READ)) {
  249. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  250. if (includeLongNames) {
  251. size_t lenPrependLong = prependLong ? strlen(prependLong) + 1 : 0;
  252. // Allocate enough stack space for the full long path including / separator
  253. char pathLong[lenPrependLong + strlen(longFilename) + 1];
  254. if (prependLong) { strcpy(pathLong, prependLong); pathLong[lenPrependLong - 1] = '/'; }
  255. strcpy(pathLong + lenPrependLong, longFilename);
  256. printListing(child, path OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin), true, pathLong);
  257. }
  258. else
  259. printListing(child, path OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin));
  260. #else
  261. printListing(child, path OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin));
  262. #endif
  263. }
  264. else {
  265. SERIAL_ECHO_MSG(STR_SD_CANT_OPEN_SUBDIR, dosFilename);
  266. return;
  267. }
  268. }
  269. else if (is_visible_entity(p OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin))) {
  270. if (prepend) { SERIAL_ECHO(prepend); SERIAL_CHAR('/'); }
  271. SERIAL_ECHO(createFilename(filename, p));
  272. SERIAL_CHAR(' ');
  273. SERIAL_ECHO(p.fileSize);
  274. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  275. if (includeLongNames) {
  276. SERIAL_CHAR(' ');
  277. if (prependLong) { SERIAL_ECHO(prependLong); SERIAL_CHAR('/'); }
  278. SERIAL_ECHO(longFilename[0] ? longFilename : filename);
  279. }
  280. #endif
  281. SERIAL_EOL();
  282. }
  283. }
  284. }
  285. //
  286. // List all files on the SD card
  287. //
  288. void CardReader::ls(
  289. TERN_(CUSTOM_FIRMWARE_UPLOAD, const bool onlyBin/*=false*/)
  290. #if BOTH(CUSTOM_FIRMWARE_UPLOAD, LONG_FILENAME_HOST_SUPPORT)
  291. ,
  292. #endif
  293. TERN_(LONG_FILENAME_HOST_SUPPORT, const bool includeLongNames/*=false*/)
  294. ) {
  295. if (flag.mounted) {
  296. root.rewind();
  297. printListing(root, nullptr OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin) OPTARG(LONG_FILENAME_HOST_SUPPORT, includeLongNames));
  298. }
  299. }
  300. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  301. //
  302. // Get a long pretty path based on a DOS 8.3 path
  303. //
  304. void CardReader::printLongPath(char * const path) {
  305. int i, pathLen = path ? strlen(path) : 0;
  306. // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);
  307. // Zero out slashes to make segments
  308. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  309. SdFile diveDir = root; // start from the root for segment 1
  310. for (i = 0; i < pathLen;) {
  311. if (path[i] == '\0') i++; // move past a single nul
  312. char *segment = &path[i]; // The segment after most slashes
  313. // If a segment is empty (extra-slash) then exit
  314. if (!*segment) break;
  315. // Go to the next segment
  316. while (path[++i]) { }
  317. //SERIAL_ECHOLNPGM("Looking for segment: ", segment);
  318. // Find the item, setting the long filename
  319. diveDir.rewind();
  320. selectByName(diveDir, segment);
  321. // Print /LongNamePart to serial output or the short name if not available
  322. SERIAL_CHAR('/');
  323. SERIAL_ECHO(longFilename[0] ? longFilename : filename);
  324. // If the filename was printed then that's it
  325. if (!flag.filenameIsDir) break;
  326. // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);
  327. // Open the sub-item as the new dive parent
  328. SdFile dir;
  329. if (!dir.open(&diveDir, segment, O_READ)) {
  330. SERIAL_EOL();
  331. SERIAL_ECHO_START();
  332. SERIAL_ECHOPGM(STR_SD_CANT_OPEN_SUBDIR, segment);
  333. break;
  334. }
  335. diveDir.close();
  336. diveDir = dir;
  337. } // while i<pathLen
  338. SERIAL_EOL();
  339. }
  340. #endif // LONG_FILENAME_HOST_SUPPORT
  341. //
  342. // Echo the DOS 8.3 filename (and long filename, if any)
  343. //
  344. void CardReader::printSelectedFilename() {
  345. if (file.isOpen()) {
  346. char dosFilename[FILENAME_LENGTH];
  347. file.getDosName(dosFilename);
  348. SERIAL_ECHO(dosFilename);
  349. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  350. selectFileByName(dosFilename);
  351. if (longFilename[0]) {
  352. SERIAL_CHAR(' ');
  353. SERIAL_ECHO(longFilename);
  354. }
  355. #endif
  356. }
  357. else
  358. SERIAL_ECHOPGM("(no file)");
  359. SERIAL_EOL();
  360. }
  361. void CardReader::mount() {
  362. flag.mounted = false;
  363. if (root.isOpen()) root.close();
  364. if (!driver->init(SD_SPI_SPEED, SDSS)
  365. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  366. && !driver->init(SD_SPI_SPEED, LCD_SDSS)
  367. #endif
  368. ) SERIAL_ECHO_MSG(STR_SD_INIT_FAIL);
  369. else if (!volume.init(driver))
  370. SERIAL_ERROR_MSG(STR_SD_VOL_INIT_FAIL);
  371. else if (!root.openRoot(&volume))
  372. SERIAL_ERROR_MSG(STR_SD_OPENROOT_FAIL);
  373. else {
  374. flag.mounted = true;
  375. SERIAL_ECHO_MSG(STR_SD_CARD_OK);
  376. }
  377. if (flag.mounted)
  378. cdroot();
  379. #if ENABLED(USB_FLASH_DRIVE_SUPPORT) || PIN_EXISTS(SD_DETECT)
  380. else if (marlin_state != MF_INITIALIZING)
  381. LCD_ALERTMESSAGE(MSG_MEDIA_INIT_FAIL);
  382. #endif
  383. ui.refresh();
  384. }
  385. /**
  386. * Handle SD card events
  387. */
  388. #if MB(FYSETC_CHEETAH, FYSETC_AIO_II)
  389. #include "../module/stepper.h"
  390. #endif
  391. void CardReader::manage_media() {
  392. static uint8_t prev_stat = 2; // First call, no prior state
  393. uint8_t stat = uint8_t(IS_SD_INSERTED());
  394. if (stat == prev_stat) return;
  395. DEBUG_ECHOLNPGM("SD: Status changed from ", prev_stat, " to ", stat);
  396. flag.workDirIsRoot = true; // Return to root on mount/release
  397. if (ui.detected()) {
  398. uint8_t old_stat = prev_stat;
  399. prev_stat = stat; // Change now to prevent re-entry
  400. if (stat) { // Media Inserted
  401. safe_delay(500); // Some boards need a delay to get settled
  402. if (TERN1(SD_IGNORE_AT_STARTUP, old_stat != 2))
  403. mount(); // Try to mount the media
  404. #if MB(FYSETC_CHEETAH, FYSETC_CHEETAH_V12, FYSETC_AIO_II)
  405. reset_stepper_drivers(); // Workaround for Cheetah bug
  406. #endif
  407. if (!isMounted()) stat = 0; // Not mounted?
  408. }
  409. else {
  410. #if PIN_EXISTS(SD_DETECT)
  411. release(); // Card is released
  412. #endif
  413. }
  414. ui.media_changed(old_stat, stat); // Update the UI
  415. if (stat) {
  416. TERN_(SDCARD_EEPROM_EMULATION, settings.first_load());
  417. if (old_stat == 2) { // First mount?
  418. DEBUG_ECHOLNPGM("First mount.");
  419. #if ENABLED(POWER_LOSS_RECOVERY)
  420. recovery.check(); // Check for PLR file. (If not there then call autofile_begin)
  421. #elif DISABLED(NO_SD_AUTOSTART)
  422. autofile_begin(); // Look for auto0.g on the next loop
  423. #endif
  424. }
  425. }
  426. }
  427. else
  428. DEBUG_ECHOLNPGM("SD: No UI Detected.");
  429. }
  430. /**
  431. * "Release" the media by clearing the 'mounted' flag.
  432. * Used by M22, "Release Media", manage_media.
  433. */
  434. void CardReader::release() {
  435. // Card removed while printing? Abort!
  436. if (IS_SD_PRINTING())
  437. abortFilePrintSoon();
  438. else
  439. endFilePrintNow();
  440. flag.mounted = false;
  441. flag.workDirIsRoot = true;
  442. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  443. nrFiles = 0;
  444. #endif
  445. }
  446. /**
  447. * Open a G-code file and set Marlin to start processing it.
  448. * Enqueues M23 and M24 commands to initiate a media print.
  449. */
  450. void CardReader::openAndPrintFile(const char *name) {
  451. char cmd[4 + strlen(name) + 1 + 3 + 1]; // Room for "M23 ", filename, "\n", "M24", and null
  452. sprintf_P(cmd, M23_STR, name);
  453. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  454. strcat_P(cmd, PSTR("\nM24"));
  455. queue.inject(cmd);
  456. }
  457. /**
  458. * Start or resume a media print by setting the sdprinting flag.
  459. * The file browser pre-sort is also purged to free up memory,
  460. * since you cannot browse files during active printing.
  461. * Used by M24 and anywhere Start / Resume applies.
  462. */
  463. void CardReader::startOrResumeFilePrinting() {
  464. if (isMounted()) {
  465. flag.sdprinting = true;
  466. flag.sdprintdone = false;
  467. TERN_(SD_RESORT, flush_presort());
  468. }
  469. }
  470. //
  471. // Run tasks upon finishing or aborting a file print.
  472. //
  473. void CardReader::endFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  474. TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0);
  475. TERN_(HAS_DWIN_E3V2_BASIC, HMI_flag.print_finish = flag.sdprinting);
  476. flag.abort_sd_printing = false;
  477. if (isFileOpen()) file.close();
  478. TERN_(SD_RESORT, if (re_sort) presort());
  479. }
  480. void CardReader::abortFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  481. flag.sdprinting = flag.sdprintdone = false;
  482. endFilePrintNow(TERN_(SD_RESORT, re_sort));
  483. }
  484. void CardReader::openLogFile(const char * const path) {
  485. flag.logging = DISABLED(SDCARD_READONLY);
  486. IF_DISABLED(SDCARD_READONLY, openFileWrite(path));
  487. }
  488. //
  489. // Get the root-relative DOS path of the selected file
  490. //
  491. void CardReader::getAbsFilenameInCWD(char *dst) {
  492. *dst++ = '/';
  493. uint8_t cnt = 1;
  494. auto appendAtom = [&](SdFile &file) {
  495. file.getDosName(dst);
  496. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  497. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  498. };
  499. LOOP_L_N(i, workDirDepth) // Loop down to current work dir
  500. appendAtom(workDirParents[i]);
  501. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  502. appendAtom(file);
  503. --dst;
  504. }
  505. *dst = '\0';
  506. }
  507. void openFailed(const char * const fname) {
  508. SERIAL_ECHOLNPGM(STR_SD_OPEN_FILE_FAIL, fname, ".");
  509. }
  510. void announceOpen(const uint8_t doing, const char * const path) {
  511. if (doing) {
  512. PORT_REDIRECT(SerialMask::All);
  513. SERIAL_ECHO_START();
  514. SERIAL_ECHOPGM("Now ");
  515. SERIAL_ECHOF(doing == 1 ? F("doing") : F("fresh"));
  516. SERIAL_ECHOLNPGM(" file: ", path);
  517. }
  518. }
  519. //
  520. // Open a file by DOS path for read
  521. // The 'subcall_type' flag indicates...
  522. // - 0 : Standard open from host or user interface.
  523. // - 1 : (file open) Opening a new sub-procedure.
  524. // - 1 : (no file open) Opening a macro (M98).
  525. // - 2 : Resuming from a sub-procedure
  526. //
  527. void CardReader::openFileRead(const char * const path, const uint8_t subcall_type/*=0*/) {
  528. if (!isMounted()) return;
  529. switch (subcall_type) {
  530. case 0: // Starting a new print. "Now fresh file: ..."
  531. announceOpen(2, path);
  532. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  533. break;
  534. #if HAS_MEDIA_SUBCALLS
  535. case 1: // Starting a sub-procedure
  536. // With no file is open it's a simple macro. "Now doing file: ..."
  537. if (!isFileOpen()) { announceOpen(1, path); break; }
  538. // Too deep? The firmware has to bail.
  539. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  540. SERIAL_ERROR_MSG("Exceeded max SUBROUTINE depth:", SD_PROCEDURE_DEPTH);
  541. kill(GET_TEXT_F(MSG_KILL_SUBCALL_OVERFLOW));
  542. return;
  543. }
  544. // Store current filename (based on workDirParents) and position
  545. getAbsFilenameInCWD(proc_filenames[file_subcall_ctr]);
  546. filespos[file_subcall_ctr] = sdpos;
  547. // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345'
  548. SERIAL_ECHO_MSG("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  549. file_subcall_ctr++;
  550. break;
  551. case 2: // Resuming previous file after sub-procedure
  552. SERIAL_ECHO_MSG("END SUBROUTINE");
  553. break;
  554. #endif
  555. }
  556. abortFilePrintNow();
  557. SdFile *diveDir;
  558. const char * const fname = diveToFile(true, diveDir, path);
  559. if (!fname) return;
  560. if (file.open(diveDir, fname, O_READ)) {
  561. filesize = file.fileSize();
  562. sdpos = 0;
  563. { // Don't remove this block, as the PORT_REDIRECT is a RAII
  564. PORT_REDIRECT(SerialMask::All);
  565. SERIAL_ECHOLNPGM(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize);
  566. SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED);
  567. }
  568. selectFileByName(fname);
  569. ui.set_status(longFilename[0] ? longFilename : fname);
  570. }
  571. else
  572. openFailed(fname);
  573. }
  574. inline void echo_write_to_file(const char * const fname) {
  575. SERIAL_ECHOLNPGM(STR_SD_WRITE_TO_FILE, fname);
  576. }
  577. //
  578. // Open a file by DOS path for write
  579. //
  580. void CardReader::openFileWrite(const char * const path) {
  581. if (!isMounted()) return;
  582. announceOpen(2, path);
  583. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  584. abortFilePrintNow();
  585. SdFile *diveDir;
  586. const char * const fname = diveToFile(false, diveDir, path);
  587. if (!fname) return;
  588. #if ENABLED(SDCARD_READONLY)
  589. openFailed(fname);
  590. #else
  591. if (file.open(diveDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  592. flag.saving = true;
  593. selectFileByName(fname);
  594. TERN_(EMERGENCY_PARSER, emergency_parser.disable());
  595. echo_write_to_file(fname);
  596. ui.set_status(fname);
  597. }
  598. else
  599. openFailed(fname);
  600. #endif
  601. }
  602. //
  603. // Check if a file exists by absolute or workDir-relative path
  604. // If the file exists, the long name can also be fetched.
  605. //
  606. bool CardReader::fileExists(const char * const path) {
  607. if (!isMounted()) return false;
  608. DEBUG_ECHOLNPGM("fileExists: ", path);
  609. // Dive to the file's directory and get the base name
  610. SdFile *diveDir = nullptr;
  611. const char * const fname = diveToFile(false, diveDir, path);
  612. if (!fname) return false;
  613. // Get the longname of the checked file
  614. //diveDir->rewind();
  615. //selectByName(*diveDir, fname);
  616. //diveDir->close();
  617. // Try to open the file and return the result
  618. SdFile tmpFile;
  619. const bool success = tmpFile.open(diveDir, fname, O_READ);
  620. if (success) tmpFile.close();
  621. return success;
  622. }
  623. //
  624. // Delete a file by name in the working directory
  625. //
  626. void CardReader::removeFile(const char * const name) {
  627. if (!isMounted()) return;
  628. //abortFilePrintNow();
  629. SdFile *itsDirPtr;
  630. const char * const fname = diveToFile(false, itsDirPtr, name);
  631. if (!fname) return;
  632. #if ENABLED(SDCARD_READONLY)
  633. SERIAL_ECHOLNPGM("Deletion failed (read-only), File: ", fname, ".");
  634. #else
  635. if (file.remove(itsDirPtr, fname)) {
  636. SERIAL_ECHOLNPGM("File deleted:", fname);
  637. sdpos = 0;
  638. TERN_(SDCARD_SORT_ALPHA, presort());
  639. }
  640. else
  641. SERIAL_ECHOLNPGM("Deletion failed, File: ", fname, ".");
  642. #endif
  643. }
  644. void CardReader::report_status() {
  645. if (isPrinting()) {
  646. SERIAL_ECHOPGM(STR_SD_PRINTING_BYTE, sdpos);
  647. SERIAL_CHAR('/');
  648. SERIAL_ECHOLN(filesize);
  649. }
  650. else
  651. SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING);
  652. }
  653. void CardReader::write_command(char * const buf) {
  654. char *begin = buf,
  655. *npos = nullptr,
  656. *end = buf + strlen(buf) - 1;
  657. file.writeError = false;
  658. if ((npos = strchr(buf, 'N'))) {
  659. begin = strchr(npos, ' ') + 1;
  660. end = strchr(npos, '*') - 1;
  661. }
  662. end[1] = '\r';
  663. end[2] = '\n';
  664. end[3] = '\0';
  665. file.write(begin);
  666. if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE);
  667. }
  668. #if DISABLED(NO_SD_AUTOSTART)
  669. /**
  670. * Run all the auto#.g files. Called:
  671. * - On boot after successful card init.
  672. * - From the LCD command to Run Auto Files
  673. */
  674. void CardReader::autofile_begin() {
  675. autofile_index = 1;
  676. (void)autofile_check();
  677. }
  678. /**
  679. * Run the next auto#.g file. Called:
  680. * - On boot after successful card init
  681. * - After finishing the previous auto#.g file
  682. * - From the LCD command to begin the auto#.g files
  683. *
  684. * Return 'true' if an auto file was started
  685. */
  686. bool CardReader::autofile_check() {
  687. if (!autofile_index) return false;
  688. if (!isMounted())
  689. mount();
  690. else if (ENABLED(SDCARD_EEPROM_EMULATION))
  691. settings.first_load();
  692. // Don't run auto#.g when a PLR file exists
  693. if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) {
  694. char autoname[10];
  695. sprintf_P(autoname, PSTR("/auto%c.g"), '0' + autofile_index - 1);
  696. if (fileExists(autoname)) {
  697. cdroot();
  698. openAndPrintFile(autoname);
  699. autofile_index++;
  700. return true;
  701. }
  702. }
  703. autofile_cancel();
  704. return false;
  705. }
  706. #endif
  707. void CardReader::closefile(const bool store_location/*=false*/) {
  708. file.sync();
  709. file.close();
  710. flag.saving = flag.logging = false;
  711. sdpos = 0;
  712. TERN_(EMERGENCY_PARSER, emergency_parser.enable());
  713. if (store_location) {
  714. //future: store printer state, filename and position for continuing a stopped print
  715. // so one can unplug the printer and continue printing the next day.
  716. }
  717. }
  718. //
  719. // Get info for a file in the working directory by index
  720. //
  721. void CardReader::selectFileByIndex(const uint16_t nr) {
  722. #if ENABLED(SDSORT_CACHE_NAMES)
  723. if (nr < sort_count) {
  724. strcpy(filename, sortshort[nr]);
  725. strcpy(longFilename, sortnames[nr]);
  726. flag.filenameIsDir = IS_DIR(nr);
  727. setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0);
  728. return;
  729. }
  730. #endif
  731. workDir.rewind();
  732. selectByIndex(workDir, nr);
  733. }
  734. //
  735. // Get info for a file in the working directory by DOS name
  736. //
  737. void CardReader::selectFileByName(const char * const match) {
  738. #if ENABLED(SDSORT_CACHE_NAMES)
  739. for (uint16_t nr = 0; nr < sort_count; nr++)
  740. if (strcasecmp(match, sortshort[nr]) == 0) {
  741. strcpy(filename, sortshort[nr]);
  742. strcpy(longFilename, sortnames[nr]);
  743. flag.filenameIsDir = IS_DIR(nr);
  744. setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0);
  745. return;
  746. }
  747. #endif
  748. workDir.rewind();
  749. selectByName(workDir, match);
  750. }
  751. uint16_t CardReader::countFilesInWorkDir() {
  752. workDir.rewind();
  753. return countItems(workDir);
  754. }
  755. /**
  756. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  757. *
  758. * On entry:
  759. * - The workDir points to the last-set navigation target by cd, cdup, cdroot, or diveToFile(true, ...)
  760. *
  761. * On exit:
  762. * - Your curDir pointer contains an SdFile reference to the file's directory.
  763. * - If update_cwd was 'true' the workDir now points to the file's directory.
  764. *
  765. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  766. * On exit, inDirPtr contains an SdFile reference to the file's directory.
  767. *
  768. * A nullptr result indicates an unrecoverable error.
  769. *
  770. * NOTE: End the path with a slash to dive to a folder. In this case the
  771. * returned filename will be blank (points to the end of the path).
  772. */
  773. const char* CardReader::diveToFile(const bool update_cwd, SdFile* &inDirPtr, const char * const path, const bool echo/*=false*/) {
  774. DEBUG_SECTION(est, "diveToFile", true);
  775. // Track both parent and subfolder
  776. static SdFile newDir1, newDir2;
  777. SdFile *sub = &newDir1, *startDirPtr;
  778. // Parsing the path string
  779. const char *atom_ptr = path;
  780. DEBUG_ECHOLNPGM(" path = '", path, "'");
  781. if (path[0] == '/') { // Starting at the root directory?
  782. inDirPtr = &root;
  783. atom_ptr++;
  784. DEBUG_ECHOLNPGM(" CWD to root: ", hex_address((void*)inDirPtr));
  785. if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs
  786. }
  787. else
  788. inDirPtr = &workDir; // Dive from workDir (as set by the UI)
  789. startDirPtr = inDirPtr;
  790. DEBUG_ECHOLNPGM(" startDirPtr = ", hex_address((void*)startDirPtr));
  791. while (atom_ptr) {
  792. // Find next subdirectory delimiter
  793. const char * const name_end = strchr(atom_ptr, '/');
  794. // Last atom in the path? Item found.
  795. if (name_end <= atom_ptr) break;
  796. // Isolate the next subitem name
  797. const uint8_t len = name_end - atom_ptr;
  798. char dosSubdirname[len + 1];
  799. strncpy(dosSubdirname, atom_ptr, len);
  800. dosSubdirname[len] = 0;
  801. if (echo) SERIAL_ECHOLN(dosSubdirname);
  802. DEBUG_ECHOLNPGM(" sub = ", hex_address((void*)sub));
  803. // Open inDirPtr (closing first)
  804. sub->close();
  805. if (!sub->open(inDirPtr, dosSubdirname, O_READ)) {
  806. openFailed(dosSubdirname);
  807. atom_ptr = nullptr;
  808. break;
  809. }
  810. // Close inDirPtr if not at starting-point
  811. if (inDirPtr != startDirPtr) {
  812. DEBUG_ECHOLNPGM(" closing inDirPtr: ", hex_address((void*)inDirPtr));
  813. inDirPtr->close();
  814. }
  815. // inDirPtr now subDir
  816. inDirPtr = sub;
  817. DEBUG_ECHOLNPGM(" inDirPtr = sub: ", hex_address((void*)inDirPtr));
  818. // Update workDirParents and workDirDepth
  819. if (update_cwd) {
  820. DEBUG_ECHOLNPGM(" update_cwd");
  821. if (workDirDepth < MAX_DIR_DEPTH)
  822. workDirParents[workDirDepth++] = *inDirPtr;
  823. }
  824. // Point sub at the other scratch object
  825. sub = (inDirPtr != &newDir1) ? &newDir1 : &newDir2;
  826. DEBUG_ECHOLNPGM(" swapping sub = ", hex_address((void*)sub));
  827. // Next path atom address
  828. atom_ptr = name_end + 1;
  829. }
  830. if (update_cwd) {
  831. workDir = *inDirPtr;
  832. DEBUG_ECHOLNPGM(" final workDir = ", hex_address((void*)inDirPtr));
  833. flag.workDirIsRoot = (workDirDepth == 0);
  834. TERN_(SDCARD_SORT_ALPHA, presort());
  835. }
  836. DEBUG_ECHOLNPGM(" returning string ", atom_ptr ?: "nullptr");
  837. return atom_ptr;
  838. }
  839. void CardReader::cd(const char * relpath) {
  840. SdFile newDir, *parent = &getWorkDir();
  841. if (newDir.open(parent, relpath, O_READ)) {
  842. workDir = newDir;
  843. flag.workDirIsRoot = false;
  844. if (workDirDepth < MAX_DIR_DEPTH)
  845. workDirParents[workDirDepth++] = workDir;
  846. TERN_(SDCARD_SORT_ALPHA, presort());
  847. }
  848. else
  849. SERIAL_ECHO_MSG(STR_SD_CANT_ENTER_SUBDIR, relpath);
  850. }
  851. int8_t CardReader::cdup() {
  852. if (workDirDepth > 0) { // At least 1 dir has been saved
  853. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  854. TERN_(SDCARD_SORT_ALPHA, presort());
  855. }
  856. if (!workDirDepth) flag.workDirIsRoot = true;
  857. return workDirDepth;
  858. }
  859. void CardReader::cdroot() {
  860. workDir = root;
  861. flag.workDirIsRoot = true;
  862. workDirDepth = 0;
  863. TERN_(SDCARD_SORT_ALPHA, presort());
  864. }
  865. #if ENABLED(SDCARD_SORT_ALPHA)
  866. /**
  867. * Get the name of a file in the working directory by sort-index
  868. */
  869. void CardReader::getfilename_sorted(const uint16_t nr) {
  870. selectFileByIndex(TERN1(SDSORT_GCODE, sort_alpha) && (nr < sort_count)
  871. ? sort_order[nr] : nr);
  872. }
  873. #if ENABLED(SDSORT_USES_RAM)
  874. #if ENABLED(SDSORT_DYNAMIC_RAM)
  875. // Use dynamic method to copy long filename
  876. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  877. #if ENABLED(SDSORT_CACHE_NAMES)
  878. // When caching also store the short name, since
  879. // we're replacing the selectFileByIndex() behavior.
  880. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  881. #else
  882. #define SET_SORTSHORT(I) NOOP
  883. #endif
  884. #else
  885. // Copy filenames into the static array
  886. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  887. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  888. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  889. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  890. #else
  891. // Copy multiple name blocks. Add a nul for the longest case.
  892. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  893. #endif
  894. #if ENABLED(SDSORT_CACHE_NAMES)
  895. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  896. #else
  897. #define SET_SORTSHORT(I) NOOP
  898. #endif
  899. #endif
  900. #endif
  901. /**
  902. * Read all the files and produce a sort key
  903. *
  904. * We can do this in 3 ways...
  905. * - Minimal RAM: Read two filenames at a time sorting along...
  906. * - Some RAM: Buffer the directory just for this sort
  907. * - Most RAM: Buffer the directory and return filenames from RAM
  908. */
  909. void CardReader::presort() {
  910. // Throw away old sort index
  911. flush_presort();
  912. // Sorting may be turned off
  913. if (TERN0(SDSORT_GCODE, !sort_alpha)) return;
  914. // If there are files, sort up to the limit
  915. uint16_t fileCnt = countFilesInWorkDir();
  916. if (fileCnt > 0) {
  917. // Never sort more than the max allowed
  918. // If you use folders to organize, 20 may be enough
  919. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  920. // Sort order is always needed. May be static or dynamic.
  921. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]);
  922. // Use RAM to store the entire directory during pre-sort.
  923. // SDSORT_LIMIT should be set to prevent over-allocation.
  924. #if ENABLED(SDSORT_USES_RAM)
  925. // If using dynamic ram for names, allocate on the heap.
  926. #if ENABLED(SDSORT_CACHE_NAMES)
  927. #if ENABLED(SDSORT_DYNAMIC_RAM)
  928. sortshort = new char*[fileCnt];
  929. sortnames = new char*[fileCnt];
  930. #endif
  931. #elif ENABLED(SDSORT_USES_STACK)
  932. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  933. #endif
  934. // Folder sorting needs 1 bit per entry for flags.
  935. #if HAS_FOLDER_SORTING
  936. #if ENABLED(SDSORT_DYNAMIC_RAM)
  937. isDir = new uint8_t[(fileCnt + 7) >> 3];
  938. #elif ENABLED(SDSORT_USES_STACK)
  939. uint8_t isDir[(fileCnt + 7) >> 3];
  940. #endif
  941. #endif
  942. #else // !SDSORT_USES_RAM
  943. // By default re-read the names from SD for every compare
  944. // retaining only two filenames at a time. This is very
  945. // slow but is safest and uses minimal RAM.
  946. char name1[LONG_FILENAME_LENGTH];
  947. #endif
  948. if (fileCnt > 1) {
  949. // Init sort order.
  950. for (uint16_t i = 0; i < fileCnt; i++) {
  951. sort_order[i] = i;
  952. // If using RAM then read all filenames now.
  953. #if ENABLED(SDSORT_USES_RAM)
  954. selectFileByIndex(i);
  955. SET_SORTNAME(i);
  956. SET_SORTSHORT(i);
  957. //char out[30];
  958. //sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  959. //SERIAL_ECHOLN(out);
  960. #if HAS_FOLDER_SORTING
  961. const uint16_t bit = i & 0x07, ind = i >> 3;
  962. if (bit == 0) isDir[ind] = 0x00;
  963. if (flag.filenameIsDir) SBI(isDir[ind], bit);
  964. #endif
  965. #endif
  966. }
  967. // Bubble Sort
  968. for (uint16_t i = fileCnt; --i;) {
  969. bool didSwap = false;
  970. uint8_t o1 = sort_order[0];
  971. #if DISABLED(SDSORT_USES_RAM)
  972. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  973. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  974. #if HAS_FOLDER_SORTING
  975. bool dir1 = flag.filenameIsDir;
  976. #endif
  977. #endif
  978. for (uint16_t j = 0; j < i; ++j) {
  979. const uint16_t o2 = sort_order[j + 1];
  980. // Compare names from the array or just the two buffered names
  981. #if ENABLED(SDSORT_USES_RAM)
  982. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  983. #else
  984. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  985. #endif
  986. #if HAS_FOLDER_SORTING
  987. #if ENABLED(SDSORT_USES_RAM)
  988. // Folder sorting needs an index and bit to test for folder-ness.
  989. #define _SORT_CMP_DIR(fs) (IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2))
  990. #else
  991. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  992. #endif
  993. #endif
  994. // The most economical method reads names as-needed
  995. // throughout the loop. Slow if there are many.
  996. #if DISABLED(SDSORT_USES_RAM)
  997. selectFileByIndex(o2);
  998. const bool dir2 = flag.filenameIsDir;
  999. char * const name2 = longest_filename(); // use the string in-place
  1000. #endif // !SDSORT_USES_RAM
  1001. // Sort the current pair according to settings.
  1002. if (
  1003. #if HAS_FOLDER_SORTING
  1004. #if ENABLED(SDSORT_GCODE)
  1005. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  1006. #else
  1007. _SORT_CMP_DIR(FOLDER_SORTING)
  1008. #endif
  1009. #else
  1010. _SORT_CMP_NODIR()
  1011. #endif
  1012. ) {
  1013. // Reorder the index, indicate that sorting happened
  1014. // Note that the next o1 will be the current o1. No new fetch needed.
  1015. sort_order[j] = o2;
  1016. sort_order[j + 1] = o1;
  1017. didSwap = true;
  1018. }
  1019. else {
  1020. // The next o1 is the current o2. No new fetch needed.
  1021. o1 = o2;
  1022. #if DISABLED(SDSORT_USES_RAM)
  1023. TERN_(HAS_FOLDER_SORTING, dir1 = dir2);
  1024. strcpy(name1, name2);
  1025. #endif
  1026. }
  1027. }
  1028. if (!didSwap) break;
  1029. }
  1030. // Using RAM but not keeping names around
  1031. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  1032. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1033. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  1034. TERN_(HAS_FOLDER_SORTING, delete [] isDir);
  1035. #endif
  1036. #endif
  1037. }
  1038. else {
  1039. sort_order[0] = 0;
  1040. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1041. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1042. sortnames = new char*[1];
  1043. sortshort = new char*[1];
  1044. isDir = new uint8_t[1];
  1045. #endif
  1046. selectFileByIndex(0);
  1047. SET_SORTNAME(0);
  1048. SET_SORTSHORT(0);
  1049. isDir[0] = flag.filenameIsDir;
  1050. #endif
  1051. }
  1052. sort_count = fileCnt;
  1053. }
  1054. }
  1055. void CardReader::flush_presort() {
  1056. if (sort_count > 0) {
  1057. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1058. delete [] sort_order;
  1059. #if ENABLED(SDSORT_CACHE_NAMES)
  1060. LOOP_L_N(i, sort_count) {
  1061. free(sortshort[i]); // strdup
  1062. free(sortnames[i]); // strdup
  1063. }
  1064. delete [] sortshort;
  1065. delete [] sortnames;
  1066. #endif
  1067. #endif
  1068. sort_count = 0;
  1069. }
  1070. }
  1071. #endif // SDCARD_SORT_ALPHA
  1072. uint16_t CardReader::get_num_Files() {
  1073. if (!isMounted()) return 0;
  1074. return (
  1075. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1076. nrFiles // no need to access the SD card for filenames
  1077. #else
  1078. countFilesInWorkDir()
  1079. #endif
  1080. );
  1081. }
  1082. //
  1083. // Return from procedure or close out the Print Job
  1084. //
  1085. void CardReader::fileHasFinished() {
  1086. file.close();
  1087. #if HAS_MEDIA_SUBCALLS
  1088. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  1089. file_subcall_ctr--;
  1090. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  1091. setIndex(filespos[file_subcall_ctr]);
  1092. startOrResumeFilePrinting();
  1093. return;
  1094. }
  1095. #endif
  1096. endFilePrintNow(TERN_(SD_RESORT, true));
  1097. flag.sdprintdone = true; // Stop getting bytes from the SD card
  1098. marlin_state = MF_SD_COMPLETE; // Tell Marlin to enqueue M1001 soon
  1099. }
  1100. #if ENABLED(AUTO_REPORT_SD_STATUS)
  1101. AutoReporter<CardReader::AutoReportSD> CardReader::auto_reporter;
  1102. #endif
  1103. #if ENABLED(POWER_LOSS_RECOVERY)
  1104. bool CardReader::jobRecoverFileExists() {
  1105. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  1106. if (exists) recovery.file.close();
  1107. return exists;
  1108. }
  1109. void CardReader::openJobRecoveryFile(const bool read) {
  1110. if (!isMounted()) return;
  1111. if (recovery.file.isOpen()) return;
  1112. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  1113. openFailed(recovery.filename);
  1114. else if (!read)
  1115. echo_write_to_file(recovery.filename);
  1116. }
  1117. // Removing the job recovery file currently requires closing
  1118. // the file being printed, so during SD printing the file should
  1119. // be zeroed and written instead of deleted.
  1120. void CardReader::removeJobRecoveryFile() {
  1121. if (jobRecoverFileExists()) {
  1122. recovery.init();
  1123. removeFile(recovery.filename);
  1124. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  1125. SERIAL_ECHOPGM("Power-loss file delete");
  1126. SERIAL_ECHOF(jobRecoverFileExists() ? F(" failed.\n") : F("d.\n"));
  1127. #endif
  1128. }
  1129. }
  1130. #endif // POWER_LOSS_RECOVERY
  1131. #endif // SDSUPPORT