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 40KB

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