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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  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 BOTH(SDSUPPORT, HAS_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. else {
  380. #if EITHER(HAS_SD_DETECT, USB_FLASH_DRIVE_SUPPORT)
  381. if (marlin_state != MF_INITIALIZING) LCD_ALERTMESSAGE(MSG_MEDIA_INIT_FAIL);
  382. #endif
  383. }
  384. ui.refresh();
  385. }
  386. /**
  387. * Handle SD card events
  388. */
  389. #if MB(FYSETC_CHEETAH, FYSETC_AIO_II)
  390. #include "../module/stepper.h"
  391. #endif
  392. void CardReader::manage_media() {
  393. static uint8_t prev_stat = 2; // At boot we don't know if media is present or not
  394. uint8_t stat = uint8_t(IS_SD_INSERTED());
  395. if (stat == prev_stat) return; // Already checked and still no change?
  396. DEBUG_SECTION(cmm, "CardReader::manage_media()", true);
  397. DEBUG_ECHOLNPGM("Media present: ", prev_stat, " -> ", stat);
  398. if (!ui.detected()) {
  399. DEBUG_ECHOLNPGM("SD: No UI Detected.");
  400. return;
  401. }
  402. flag.workDirIsRoot = true; // Return to root on mount/release/init
  403. const uint8_t old_stat = prev_stat;
  404. prev_stat = stat; // Change now to prevent re-entry in safe_delay
  405. if (stat) { // Media Inserted
  406. safe_delay(500); // Some boards need a delay to get settled
  407. // Try to mount the media (only later with SD_IGNORE_AT_STARTUP)
  408. if (TERN1(SD_IGNORE_AT_STARTUP, old_stat != 2)) mount();
  409. if (!isMounted()) stat = 0; // Not mounted?
  410. TERN_(RESET_STEPPERS_ON_MEDIA_INSERT, reset_stepper_drivers()); // Workaround for Cheetah bug
  411. }
  412. else {
  413. TERN_(HAS_SD_DETECT, release()); // Card is released
  414. }
  415. ui.media_changed(old_stat, stat); // Update the UI or flag an error
  416. if (!stat) return; // Exit if no media is present
  417. if (old_stat != 2) return; // First mount?
  418. DEBUG_ECHOLNPGM("First mount.");
  419. // Load settings the first time media is inserted (not just during init)
  420. TERN_(SDCARD_EEPROM_EMULATION, settings.first_load());
  421. bool do_auto = true; UNUSED(do_auto);
  422. // Check for PLR file.
  423. TERN_(POWER_LOSS_RECOVERY, if (recovery.check()) do_auto = false);
  424. // Look for auto0.g on the next idle()
  425. IF_DISABLED(NO_SD_AUTOSTART, if (do_auto) autofile_begin());
  426. }
  427. /**
  428. * "Release" the media by clearing the 'mounted' flag.
  429. * Used by M22, "Release Media", manage_media.
  430. */
  431. void CardReader::release() {
  432. // Card removed while printing? Abort!
  433. if (IS_SD_PRINTING())
  434. abortFilePrintSoon();
  435. else
  436. endFilePrintNow();
  437. flag.mounted = false;
  438. flag.workDirIsRoot = true;
  439. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  440. nrFiles = 0;
  441. #endif
  442. }
  443. /**
  444. * Open a G-code file and set Marlin to start processing it.
  445. * Enqueues M23 and M24 commands to initiate a media print.
  446. */
  447. void CardReader::openAndPrintFile(const char *name) {
  448. char cmd[4 + strlen(name) + 1 + 3 + 1]; // Room for "M23 ", filename, "\n", "M24", and null
  449. sprintf_P(cmd, M23_STR, name);
  450. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  451. strcat_P(cmd, PSTR("\nM24"));
  452. queue.inject(cmd);
  453. }
  454. /**
  455. * Start or resume a media print by setting the sdprinting flag.
  456. * The file browser pre-sort is also purged to free up memory,
  457. * since you cannot browse files during active printing.
  458. * Used by M24 and anywhere Start / Resume applies.
  459. */
  460. void CardReader::startOrResumeFilePrinting() {
  461. if (isMounted()) {
  462. flag.sdprinting = true;
  463. flag.sdprintdone = false;
  464. TERN_(SD_RESORT, flush_presort());
  465. }
  466. }
  467. //
  468. // Run tasks upon finishing or aborting a file print.
  469. //
  470. void CardReader::endFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  471. TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0);
  472. TERN_(HAS_DWIN_E3V2_BASIC, HMI_flag.print_finish = flag.sdprinting);
  473. flag.abort_sd_printing = false;
  474. if (isFileOpen()) file.close();
  475. TERN_(SD_RESORT, if (re_sort) presort());
  476. }
  477. void CardReader::abortFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  478. flag.sdprinting = flag.sdprintdone = false;
  479. endFilePrintNow(TERN_(SD_RESORT, re_sort));
  480. }
  481. void CardReader::openLogFile(const char * const path) {
  482. flag.logging = DISABLED(SDCARD_READONLY);
  483. IF_DISABLED(SDCARD_READONLY, openFileWrite(path));
  484. }
  485. //
  486. // Get the root-relative DOS path of the selected file
  487. //
  488. void CardReader::getAbsFilenameInCWD(char *dst) {
  489. *dst++ = '/';
  490. uint8_t cnt = 1;
  491. auto appendAtom = [&](SdFile &file) {
  492. file.getDosName(dst);
  493. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  494. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  495. };
  496. LOOP_L_N(i, workDirDepth) // Loop down to current work dir
  497. appendAtom(workDirParents[i]);
  498. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  499. appendAtom(file);
  500. --dst;
  501. }
  502. *dst = '\0';
  503. }
  504. void openFailed(const char * const fname) {
  505. SERIAL_ECHOLNPGM(STR_SD_OPEN_FILE_FAIL, fname, ".");
  506. }
  507. void announceOpen(const uint8_t doing, const char * const path) {
  508. if (doing) {
  509. PORT_REDIRECT(SerialMask::All);
  510. SERIAL_ECHO_START();
  511. SERIAL_ECHOPGM("Now ");
  512. SERIAL_ECHOF(doing == 1 ? F("doing") : F("fresh"));
  513. SERIAL_ECHOLNPGM(" file: ", path);
  514. }
  515. }
  516. //
  517. // Open a file by DOS path for read
  518. // The 'subcall_type' flag indicates...
  519. // - 0 : Standard open from host or user interface.
  520. // - 1 : (file open) Opening a new sub-procedure.
  521. // - 1 : (no file open) Opening a macro (M98).
  522. // - 2 : Resuming from a sub-procedure
  523. //
  524. void CardReader::openFileRead(const char * const path, const uint8_t subcall_type/*=0*/) {
  525. if (!isMounted()) return;
  526. switch (subcall_type) {
  527. case 0: // Starting a new print. "Now fresh file: ..."
  528. announceOpen(2, path);
  529. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  530. break;
  531. #if HAS_MEDIA_SUBCALLS
  532. case 1: // Starting a sub-procedure
  533. // With no file is open it's a simple macro. "Now doing file: ..."
  534. if (!isFileOpen()) { announceOpen(1, path); break; }
  535. // Too deep? The firmware has to bail.
  536. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  537. SERIAL_ERROR_MSG("Exceeded max SUBROUTINE depth:", SD_PROCEDURE_DEPTH);
  538. kill(GET_TEXT_F(MSG_KILL_SUBCALL_OVERFLOW));
  539. return;
  540. }
  541. // Store current filename (based on workDirParents) and position
  542. getAbsFilenameInCWD(proc_filenames[file_subcall_ctr]);
  543. filespos[file_subcall_ctr] = sdpos;
  544. // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345'
  545. SERIAL_ECHO_MSG("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  546. file_subcall_ctr++;
  547. break;
  548. case 2: // Resuming previous file after sub-procedure
  549. SERIAL_ECHO_MSG("END SUBROUTINE");
  550. break;
  551. #endif
  552. }
  553. abortFilePrintNow();
  554. SdFile *diveDir;
  555. const char * const fname = diveToFile(true, diveDir, path);
  556. if (!fname) return;
  557. if (file.open(diveDir, fname, O_READ)) {
  558. filesize = file.fileSize();
  559. sdpos = 0;
  560. { // Don't remove this block, as the PORT_REDIRECT is a RAII
  561. PORT_REDIRECT(SerialMask::All);
  562. SERIAL_ECHOLNPGM(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize);
  563. SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED);
  564. }
  565. selectFileByName(fname);
  566. ui.set_status(longFilename[0] ? longFilename : fname);
  567. }
  568. else
  569. openFailed(fname);
  570. }
  571. inline void echo_write_to_file(const char * const fname) {
  572. SERIAL_ECHOLNPGM(STR_SD_WRITE_TO_FILE, fname);
  573. }
  574. //
  575. // Open a file by DOS path for write
  576. //
  577. void CardReader::openFileWrite(const char * const path) {
  578. if (!isMounted()) return;
  579. announceOpen(2, path);
  580. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  581. abortFilePrintNow();
  582. SdFile *diveDir;
  583. const char * const fname = diveToFile(false, diveDir, path);
  584. if (!fname) return;
  585. #if ENABLED(SDCARD_READONLY)
  586. openFailed(fname);
  587. #else
  588. if (file.open(diveDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  589. flag.saving = true;
  590. selectFileByName(fname);
  591. TERN_(EMERGENCY_PARSER, emergency_parser.disable());
  592. echo_write_to_file(fname);
  593. ui.set_status(fname);
  594. }
  595. else
  596. openFailed(fname);
  597. #endif
  598. }
  599. //
  600. // Check if a file exists by absolute or workDir-relative path
  601. // If the file exists, the long name can also be fetched.
  602. //
  603. bool CardReader::fileExists(const char * const path) {
  604. if (!isMounted()) return false;
  605. DEBUG_ECHOLNPGM("fileExists: ", path);
  606. // Dive to the file's directory and get the base name
  607. SdFile *diveDir = nullptr;
  608. const char * const fname = diveToFile(false, diveDir, path);
  609. if (!fname) return false;
  610. // Get the longname of the checked file
  611. //diveDir->rewind();
  612. //selectByName(*diveDir, fname);
  613. //diveDir->close();
  614. // Try to open the file and return the result
  615. SdFile tmpFile;
  616. const bool success = tmpFile.open(diveDir, fname, O_READ);
  617. if (success) tmpFile.close();
  618. return success;
  619. }
  620. //
  621. // Delete a file by name in the working directory
  622. //
  623. void CardReader::removeFile(const char * const name) {
  624. if (!isMounted()) return;
  625. //abortFilePrintNow();
  626. SdFile *itsDirPtr;
  627. const char * const fname = diveToFile(false, itsDirPtr, name);
  628. if (!fname) return;
  629. #if ENABLED(SDCARD_READONLY)
  630. SERIAL_ECHOLNPGM("Deletion failed (read-only), File: ", fname, ".");
  631. #else
  632. if (file.remove(itsDirPtr, fname)) {
  633. SERIAL_ECHOLNPGM("File deleted:", fname);
  634. sdpos = 0;
  635. TERN_(SDCARD_SORT_ALPHA, presort());
  636. }
  637. else
  638. SERIAL_ECHOLNPGM("Deletion failed, File: ", fname, ".");
  639. #endif
  640. }
  641. void CardReader::report_status() {
  642. if (isPrinting()) {
  643. SERIAL_ECHOPGM(STR_SD_PRINTING_BYTE, sdpos);
  644. SERIAL_CHAR('/');
  645. SERIAL_ECHOLN(filesize);
  646. }
  647. else
  648. SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING);
  649. }
  650. void CardReader::write_command(char * const buf) {
  651. char *begin = buf,
  652. *npos = nullptr,
  653. *end = buf + strlen(buf) - 1;
  654. file.writeError = false;
  655. if ((npos = strchr(buf, 'N'))) {
  656. begin = strchr(npos, ' ') + 1;
  657. end = strchr(npos, '*') - 1;
  658. }
  659. end[1] = '\r';
  660. end[2] = '\n';
  661. end[3] = '\0';
  662. file.write(begin);
  663. if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE);
  664. }
  665. #if DISABLED(NO_SD_AUTOSTART)
  666. /**
  667. * Run all the auto#.g files. Called:
  668. * - On boot after successful card init.
  669. * - From the LCD command to Run Auto Files
  670. */
  671. void CardReader::autofile_begin() {
  672. autofile_index = 1;
  673. (void)autofile_check();
  674. }
  675. /**
  676. * Run the next auto#.g file. Called:
  677. * - On boot after successful card init
  678. * - After finishing the previous auto#.g file
  679. * - From the LCD command to begin the auto#.g files
  680. *
  681. * Return 'true' if an auto file was started
  682. */
  683. bool CardReader::autofile_check() {
  684. if (!autofile_index) return false;
  685. if (!isMounted())
  686. mount();
  687. else if (ENABLED(SDCARD_EEPROM_EMULATION))
  688. settings.first_load();
  689. // Don't run auto#.g when a PLR file exists
  690. if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) {
  691. char autoname[10];
  692. sprintf_P(autoname, PSTR("/auto%c.g"), '0' + autofile_index - 1);
  693. if (fileExists(autoname)) {
  694. cdroot();
  695. openAndPrintFile(autoname);
  696. autofile_index++;
  697. return true;
  698. }
  699. }
  700. autofile_cancel();
  701. return false;
  702. }
  703. #endif
  704. void CardReader::closefile(const bool store_location/*=false*/) {
  705. file.sync();
  706. file.close();
  707. flag.saving = flag.logging = false;
  708. sdpos = 0;
  709. TERN_(EMERGENCY_PARSER, emergency_parser.enable());
  710. if (store_location) {
  711. //future: store printer state, filename and position for continuing a stopped print
  712. // so one can unplug the printer and continue printing the next day.
  713. }
  714. }
  715. //
  716. // Get info for a file in the working directory by index
  717. //
  718. void CardReader::selectFileByIndex(const uint16_t nr) {
  719. #if ENABLED(SDSORT_CACHE_NAMES)
  720. if (nr < sort_count) {
  721. strcpy(filename, sortshort[nr]);
  722. strcpy(longFilename, sortnames[nr]);
  723. flag.filenameIsDir = IS_DIR(nr);
  724. setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0);
  725. return;
  726. }
  727. #endif
  728. workDir.rewind();
  729. selectByIndex(workDir, nr);
  730. }
  731. //
  732. // Get info for a file in the working directory by DOS name
  733. //
  734. void CardReader::selectFileByName(const char * const match) {
  735. #if ENABLED(SDSORT_CACHE_NAMES)
  736. for (uint16_t nr = 0; nr < sort_count; nr++)
  737. if (strcasecmp(match, sortshort[nr]) == 0) {
  738. strcpy(filename, sortshort[nr]);
  739. strcpy(longFilename, sortnames[nr]);
  740. flag.filenameIsDir = IS_DIR(nr);
  741. setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0);
  742. return;
  743. }
  744. #endif
  745. workDir.rewind();
  746. selectByName(workDir, match);
  747. }
  748. uint16_t CardReader::countFilesInWorkDir() {
  749. workDir.rewind();
  750. return countItems(workDir);
  751. }
  752. /**
  753. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  754. *
  755. * On entry:
  756. * - The workDir points to the last-set navigation target by cd, cdup, cdroot, or diveToFile(true, ...)
  757. *
  758. * On exit:
  759. * - Your curDir pointer contains an SdFile reference to the file's directory.
  760. * - If update_cwd was 'true' the workDir now points to the file's directory.
  761. *
  762. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  763. * On exit, inDirPtr contains an SdFile reference to the file's directory.
  764. *
  765. * A nullptr result indicates an unrecoverable error.
  766. *
  767. * NOTE: End the path with a slash to dive to a folder. In this case the
  768. * returned filename will be blank (points to the end of the path).
  769. */
  770. const char* CardReader::diveToFile(const bool update_cwd, SdFile* &inDirPtr, const char * const path, const bool echo/*=false*/) {
  771. DEBUG_SECTION(est, "diveToFile", true);
  772. // Track both parent and subfolder
  773. static SdFile newDir1, newDir2;
  774. SdFile *sub = &newDir1, *startDirPtr;
  775. // Parsing the path string
  776. const char *atom_ptr = path;
  777. DEBUG_ECHOLNPGM(" path = '", path, "'");
  778. if (path[0] == '/') { // Starting at the root directory?
  779. inDirPtr = &root;
  780. atom_ptr++;
  781. DEBUG_ECHOLNPGM(" CWD to root: ", hex_address((void*)inDirPtr));
  782. if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs
  783. }
  784. else
  785. inDirPtr = &workDir; // Dive from workDir (as set by the UI)
  786. startDirPtr = inDirPtr;
  787. DEBUG_ECHOLNPGM(" startDirPtr = ", hex_address((void*)startDirPtr));
  788. while (atom_ptr) {
  789. // Find next subdirectory delimiter
  790. const char * const name_end = strchr(atom_ptr, '/');
  791. // Last atom in the path? Item found.
  792. if (name_end <= atom_ptr) break;
  793. // Isolate the next subitem name
  794. const uint8_t len = name_end - atom_ptr;
  795. char dosSubdirname[len + 1];
  796. strncpy(dosSubdirname, atom_ptr, len);
  797. dosSubdirname[len] = 0;
  798. if (echo) SERIAL_ECHOLN(dosSubdirname);
  799. DEBUG_ECHOLNPGM(" sub = ", hex_address((void*)sub));
  800. // Open inDirPtr (closing first)
  801. sub->close();
  802. if (!sub->open(inDirPtr, dosSubdirname, O_READ)) {
  803. openFailed(dosSubdirname);
  804. atom_ptr = nullptr;
  805. break;
  806. }
  807. // Close inDirPtr if not at starting-point
  808. if (inDirPtr != startDirPtr) {
  809. DEBUG_ECHOLNPGM(" closing inDirPtr: ", hex_address((void*)inDirPtr));
  810. inDirPtr->close();
  811. }
  812. // inDirPtr now subDir
  813. inDirPtr = sub;
  814. DEBUG_ECHOLNPGM(" inDirPtr = sub: ", hex_address((void*)inDirPtr));
  815. // Update workDirParents and workDirDepth
  816. if (update_cwd) {
  817. DEBUG_ECHOLNPGM(" update_cwd");
  818. if (workDirDepth < MAX_DIR_DEPTH)
  819. workDirParents[workDirDepth++] = *inDirPtr;
  820. }
  821. // Point sub at the other scratch object
  822. sub = (inDirPtr != &newDir1) ? &newDir1 : &newDir2;
  823. DEBUG_ECHOLNPGM(" swapping sub = ", hex_address((void*)sub));
  824. // Next path atom address
  825. atom_ptr = name_end + 1;
  826. }
  827. if (update_cwd) {
  828. workDir = *inDirPtr;
  829. DEBUG_ECHOLNPGM(" final workDir = ", hex_address((void*)inDirPtr));
  830. flag.workDirIsRoot = (workDirDepth == 0);
  831. TERN_(SDCARD_SORT_ALPHA, presort());
  832. }
  833. DEBUG_ECHOLNPGM(" returning string ", atom_ptr ?: "nullptr");
  834. return atom_ptr;
  835. }
  836. void CardReader::cd(const char * relpath) {
  837. SdFile newDir, *parent = &getWorkDir();
  838. if (newDir.open(parent, relpath, O_READ)) {
  839. workDir = newDir;
  840. flag.workDirIsRoot = false;
  841. if (workDirDepth < MAX_DIR_DEPTH)
  842. workDirParents[workDirDepth++] = workDir;
  843. TERN_(SDCARD_SORT_ALPHA, presort());
  844. }
  845. else
  846. SERIAL_ECHO_MSG(STR_SD_CANT_ENTER_SUBDIR, relpath);
  847. }
  848. int8_t CardReader::cdup() {
  849. if (workDirDepth > 0) { // At least 1 dir has been saved
  850. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  851. TERN_(SDCARD_SORT_ALPHA, presort());
  852. }
  853. if (!workDirDepth) flag.workDirIsRoot = true;
  854. return workDirDepth;
  855. }
  856. void CardReader::cdroot() {
  857. workDir = root;
  858. flag.workDirIsRoot = true;
  859. workDirDepth = 0;
  860. TERN_(SDCARD_SORT_ALPHA, presort());
  861. }
  862. #if ENABLED(SDCARD_SORT_ALPHA)
  863. /**
  864. * Get the name of a file in the working directory by sort-index
  865. */
  866. void CardReader::getfilename_sorted(const uint16_t nr) {
  867. selectFileByIndex(TERN1(SDSORT_GCODE, sort_alpha) && (nr < sort_count)
  868. ? sort_order[nr] : nr);
  869. }
  870. #if ENABLED(SDSORT_USES_RAM)
  871. #if ENABLED(SDSORT_DYNAMIC_RAM)
  872. // Use dynamic method to copy long filename
  873. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  874. #if ENABLED(SDSORT_CACHE_NAMES)
  875. // When caching also store the short name, since
  876. // we're replacing the selectFileByIndex() behavior.
  877. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  878. #else
  879. #define SET_SORTSHORT(I) NOOP
  880. #endif
  881. #else
  882. // Copy filenames into the static array
  883. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  884. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  885. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  886. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  887. #else
  888. // Copy multiple name blocks. Add a nul for the longest case.
  889. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  890. #endif
  891. #if ENABLED(SDSORT_CACHE_NAMES)
  892. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  893. #else
  894. #define SET_SORTSHORT(I) NOOP
  895. #endif
  896. #endif
  897. #endif
  898. /**
  899. * Read all the files and produce a sort key
  900. *
  901. * We can do this in 3 ways...
  902. * - Minimal RAM: Read two filenames at a time sorting along...
  903. * - Some RAM: Buffer the directory just for this sort
  904. * - Most RAM: Buffer the directory and return filenames from RAM
  905. */
  906. void CardReader::presort() {
  907. // Throw away old sort index
  908. flush_presort();
  909. // Sorting may be turned off
  910. if (TERN0(SDSORT_GCODE, !sort_alpha)) return;
  911. // If there are files, sort up to the limit
  912. uint16_t fileCnt = countFilesInWorkDir();
  913. if (fileCnt > 0) {
  914. // Never sort more than the max allowed
  915. // If you use folders to organize, 20 may be enough
  916. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  917. // Sort order is always needed. May be static or dynamic.
  918. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]);
  919. // Use RAM to store the entire directory during pre-sort.
  920. // SDSORT_LIMIT should be set to prevent over-allocation.
  921. #if ENABLED(SDSORT_USES_RAM)
  922. // If using dynamic ram for names, allocate on the heap.
  923. #if ENABLED(SDSORT_CACHE_NAMES)
  924. #if ENABLED(SDSORT_DYNAMIC_RAM)
  925. sortshort = new char*[fileCnt];
  926. sortnames = new char*[fileCnt];
  927. #endif
  928. #elif ENABLED(SDSORT_USES_STACK)
  929. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  930. #endif
  931. // Folder sorting needs 1 bit per entry for flags.
  932. #if HAS_FOLDER_SORTING
  933. #if ENABLED(SDSORT_DYNAMIC_RAM)
  934. isDir = new uint8_t[(fileCnt + 7) >> 3];
  935. #elif ENABLED(SDSORT_USES_STACK)
  936. uint8_t isDir[(fileCnt + 7) >> 3];
  937. #endif
  938. #endif
  939. #else // !SDSORT_USES_RAM
  940. // By default re-read the names from SD for every compare
  941. // retaining only two filenames at a time. This is very
  942. // slow but is safest and uses minimal RAM.
  943. char name1[LONG_FILENAME_LENGTH];
  944. #endif
  945. if (fileCnt > 1) {
  946. // Init sort order.
  947. for (uint16_t i = 0; i < fileCnt; i++) {
  948. sort_order[i] = i;
  949. // If using RAM then read all filenames now.
  950. #if ENABLED(SDSORT_USES_RAM)
  951. selectFileByIndex(i);
  952. SET_SORTNAME(i);
  953. SET_SORTSHORT(i);
  954. //char out[30];
  955. //sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  956. //SERIAL_ECHOLN(out);
  957. #if HAS_FOLDER_SORTING
  958. const uint16_t bit = i & 0x07, ind = i >> 3;
  959. if (bit == 0) isDir[ind] = 0x00;
  960. if (flag.filenameIsDir) SBI(isDir[ind], bit);
  961. #endif
  962. #endif
  963. }
  964. // Bubble Sort
  965. for (uint16_t i = fileCnt; --i;) {
  966. bool didSwap = false;
  967. uint8_t o1 = sort_order[0];
  968. #if DISABLED(SDSORT_USES_RAM)
  969. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  970. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  971. #if HAS_FOLDER_SORTING
  972. bool dir1 = flag.filenameIsDir;
  973. #endif
  974. #endif
  975. for (uint16_t j = 0; j < i; ++j) {
  976. const uint16_t o2 = sort_order[j + 1];
  977. // Compare names from the array or just the two buffered names
  978. #if ENABLED(SDSORT_USES_RAM)
  979. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  980. #else
  981. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  982. #endif
  983. #if HAS_FOLDER_SORTING
  984. #if ENABLED(SDSORT_USES_RAM)
  985. // Folder sorting needs an index and bit to test for folder-ness.
  986. #define _SORT_CMP_DIR(fs) (IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2))
  987. #else
  988. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  989. #endif
  990. #endif
  991. // The most economical method reads names as-needed
  992. // throughout the loop. Slow if there are many.
  993. #if DISABLED(SDSORT_USES_RAM)
  994. selectFileByIndex(o2);
  995. const bool dir2 = flag.filenameIsDir;
  996. char * const name2 = longest_filename(); // use the string in-place
  997. #endif // !SDSORT_USES_RAM
  998. // Sort the current pair according to settings.
  999. if (
  1000. #if HAS_FOLDER_SORTING
  1001. #if ENABLED(SDSORT_GCODE)
  1002. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  1003. #else
  1004. _SORT_CMP_DIR(FOLDER_SORTING)
  1005. #endif
  1006. #else
  1007. _SORT_CMP_NODIR()
  1008. #endif
  1009. ) {
  1010. // Reorder the index, indicate that sorting happened
  1011. // Note that the next o1 will be the current o1. No new fetch needed.
  1012. sort_order[j] = o2;
  1013. sort_order[j + 1] = o1;
  1014. didSwap = true;
  1015. }
  1016. else {
  1017. // The next o1 is the current o2. No new fetch needed.
  1018. o1 = o2;
  1019. #if DISABLED(SDSORT_USES_RAM)
  1020. TERN_(HAS_FOLDER_SORTING, dir1 = dir2);
  1021. strcpy(name1, name2);
  1022. #endif
  1023. }
  1024. }
  1025. if (!didSwap) break;
  1026. }
  1027. // Using RAM but not keeping names around
  1028. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  1029. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1030. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  1031. TERN_(HAS_FOLDER_SORTING, delete [] isDir);
  1032. #endif
  1033. #endif
  1034. }
  1035. else {
  1036. sort_order[0] = 0;
  1037. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1038. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1039. sortnames = new char*[1];
  1040. sortshort = new char*[1];
  1041. isDir = new uint8_t[1];
  1042. #endif
  1043. selectFileByIndex(0);
  1044. SET_SORTNAME(0);
  1045. SET_SORTSHORT(0);
  1046. isDir[0] = flag.filenameIsDir;
  1047. #endif
  1048. }
  1049. sort_count = fileCnt;
  1050. }
  1051. }
  1052. void CardReader::flush_presort() {
  1053. if (sort_count > 0) {
  1054. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1055. delete [] sort_order;
  1056. #if ENABLED(SDSORT_CACHE_NAMES)
  1057. LOOP_L_N(i, sort_count) {
  1058. free(sortshort[i]); // strdup
  1059. free(sortnames[i]); // strdup
  1060. }
  1061. delete [] sortshort;
  1062. delete [] sortnames;
  1063. #endif
  1064. #endif
  1065. sort_count = 0;
  1066. }
  1067. }
  1068. #endif // SDCARD_SORT_ALPHA
  1069. uint16_t CardReader::get_num_Files() {
  1070. if (!isMounted()) return 0;
  1071. return (
  1072. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1073. nrFiles // no need to access the SD card for filenames
  1074. #else
  1075. countFilesInWorkDir()
  1076. #endif
  1077. );
  1078. }
  1079. //
  1080. // Return from procedure or close out the Print Job
  1081. //
  1082. void CardReader::fileHasFinished() {
  1083. file.close();
  1084. #if HAS_MEDIA_SUBCALLS
  1085. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  1086. file_subcall_ctr--;
  1087. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  1088. setIndex(filespos[file_subcall_ctr]);
  1089. startOrResumeFilePrinting();
  1090. return;
  1091. }
  1092. #endif
  1093. endFilePrintNow(TERN_(SD_RESORT, true));
  1094. flag.sdprintdone = true; // Stop getting bytes from the SD card
  1095. marlin_state = MF_SD_COMPLETE; // Tell Marlin to enqueue M1001 soon
  1096. }
  1097. #if ENABLED(AUTO_REPORT_SD_STATUS)
  1098. AutoReporter<CardReader::AutoReportSD> CardReader::auto_reporter;
  1099. #endif
  1100. #if ENABLED(POWER_LOSS_RECOVERY)
  1101. bool CardReader::jobRecoverFileExists() {
  1102. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  1103. if (exists) recovery.file.close();
  1104. return exists;
  1105. }
  1106. void CardReader::openJobRecoveryFile(const bool read) {
  1107. if (!isMounted()) return;
  1108. if (recovery.file.isOpen()) return;
  1109. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  1110. openFailed(recovery.filename);
  1111. else if (!read)
  1112. echo_write_to_file(recovery.filename);
  1113. }
  1114. // Removing the job recovery file currently requires closing
  1115. // the file being printed, so during SD printing the file should
  1116. // be zeroed and written instead of deleted.
  1117. void CardReader::removeJobRecoveryFile() {
  1118. if (jobRecoverFileExists()) {
  1119. recovery.init();
  1120. removeFile(recovery.filename);
  1121. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  1122. SERIAL_ECHOPGM("Power-loss file delete");
  1123. SERIAL_ECHOF(jobRecoverFileExists() ? F(" failed.\n") : F("d.\n"));
  1124. #endif
  1125. }
  1126. }
  1127. #endif // POWER_LOSS_RECOVERY
  1128. #endif // SDSUPPORT