| {"repo_name": "freewrite", "file_name": "/freewrite/freewrite/ContentView.swift", "inference_info": {"prefix_code": "// Swift 5.0\n//\n// ContentView.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\nimport AppKit\nimport UniformTypeIdentifiers\nimport PDFKit\n\nstruct HumanEntry: Identifiable {\n let id: UUID\n let date: String\n let filename: String\n var previewText: String\n \n static func createNew() -> HumanEntry {\n let id = UUID()\n let now = Date()\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n let dateString = dateFormatter.string(from: now)\n \n // For display\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: now)\n \n return HumanEntry(\n id: id,\n date: displayDate,\n filename: \"[\\(id)]-[\\(dateString)].md\",\n previewText: \"\"\n )\n }\n}\n\nstruct HeartEmoji: Identifiable {\n let id = UUID()\n var position: CGPoint\n var offset: CGFloat = 0\n}\n\nstruct ContentView: View {\n private let headerString = \"\\n\\n\"\n @State private var entries: [HumanEntry] = []\n @State private var text: String = \"\" // Remove initial welcome text since we'll handle it in createNewEntry\n \n @State private var isFullscreen = false\n @State private var selectedFont: String = \"Lato-Regular\"\n @State private var currentRandomFont: String = \"\"\n @State private var timeRemaining: Int = 900 // Changed to 900 seconds (15 minutes)\n @State private var timerIsRunning = false\n @State private var isHoveringTimer = false\n @State private var isHoveringFullscreen = false\n @State private var hoveredFont: String? = nil\n @State private var isHoveringSize = false\n @State private var fontSize: CGFloat = 18\n @State private var blinkCount = 0\n @State private var isBlinking = false\n @State private var opacity: Double = 1.0\n @State private var shouldShowGray = true // New state to control color\n @State private var lastClickTime: Date? = nil\n @State private var bottomNavOpacity: Double = 1.0\n @State private var isHoveringBottomNav = false\n @State private var selectedEntryIndex: Int = 0\n @State private var scrollOffset: CGFloat = 0\n @State private var selectedEntryId: UUID? = nil\n @State private var hoveredEntryId: UUID? = nil\n @State private var isHoveringChat = false // Add this state variable\n @State private var showingChatMenu = false\n @State private var chatMenuAnchor: CGPoint = .zero\n @State private var showingSidebar = false // Add this state variable\n @State private var hoveredTrashId: UUID? = nil\n @State private var hoveredExportId: UUID? = nil\n @State private var placeholderText: String = \"\" // Add this line\n @State private var isHoveringNewEntry = false\n @State private var isHoveringClock = false\n @State private var isHoveringHistory = false\n @State private var isHoveringHistoryText = false\n @State private var isHoveringHistoryPath = false\n @State private var isHoveringHistoryArrow = false\n @State private var colorScheme: ColorScheme = .light // Add state for color scheme\n @State private var isHoveringThemeToggle = false // Add state for theme toggle hover\n @State private var didCopyPrompt: Bool = false // Add state for copy prompt feedback\n let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()\n let entryHeight: CGFloat = 40\n \n let availableFonts = NSFontManager.shared.availableFontFamilies\n let standardFonts = [\"Lato-Regular\", \"Arial\", \".AppleSystemUIFont\", \"Times New Roman\"]\n let fontSizes: [CGFloat] = [16, 18, 20, 22, 24, 26]\n let placeholderOptions = [\n \"\\n\\nBegin writing\",\n \"\\n\\nPick a thought and go\",\n \"\\n\\nStart typing\",\n \"\\n\\nWhat's on your mind\",\n \"\\n\\nJust start\",\n \"\\n\\nType your first thought\",\n \"\\n\\nStart with one sentence\",\n \"\\n\\nJust say it\"\n ]\n \n // Add file manager and save timer\n private let fileManager = FileManager.default\n private let saveTimer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()\n \n // Add cached documents directory\n private let documentsDirectory: URL = {\n let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(\"Freewrite\")\n \n // Create Freewrite directory if it doesn't exist\n if !FileManager.default.fileExists(atPath: directory.path) {\n do {\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n print(\"Successfully created Freewrite directory\")\n } catch {\n print(\"Error creating directory: \\(error)\")\n }\n }\n \n return directory\n }()\n \n // Add shared prompt constant\n private let aiChatPrompt = \"\"\"\n below is my journal entry. wyt? talk through it with me like a friend. don't therpaize me and give me a whole breakdown, don't repeat my thoughts with headings. really take all of this, and tell me back stuff truly as if you're an old homie.\n \n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n\n do not just go through every single thing i say, and say it back to me. you need to proccess everythikng is say, make connections i don't see it, and deliver it all back to me as a story that makes me feel what you think i wanna feel. thats what the best therapists do.\n\n ideally, you're style/tone should sound like the user themselves. it's as if the user is hearing their own tone but it should still feel different, because you have different things to say and don't just repeat back they say.\n\n else, start by saying, \"hey, thanks for showing me this. my thoughts:\"\n \n my entry:\n \"\"\"\n \n private let claudePrompt = \"\"\"\n Take a look at my journal entry below. I'd like you to analyze it and respond with deep insight that feels personal, not clinical.\n Imagine you're not just a friend, but a mentor who truly gets both my tech background and my psychological patterns. I want you to uncover the deeper meaning and emotional undercurrents behind my scattered thoughts.\n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n Use vivid metaphors and powerful imagery to help me see what I'm really building. Organize your thoughts with meaningful headings that create a narrative journey through my ideas.\n Don't just validate my thoughts - reframe them in a way that shows me what I'm really seeking beneath the surface. Go beyond the product concepts to the emotional core of what I'm trying to solve.\n Be willing to be profound and philosophical without sounding like you're giving therapy. I want someone who can see the patterns I can't see myself and articulate them in a way that feels like an epiphany.\n Start with 'hey, thanks for showing me this. my thoughts:' and then use markdown headings to structure your response.\n\n Here's my journal entry:\n \"\"\"\n \n // Initialize with saved theme preference if available\n init() {\n // Load saved color scheme preference\n let savedScheme = UserDefaults.standard.string(forKey: \"colorScheme\") ?? \"light\"\n _colorScheme = State(initialValue: savedScheme == \"dark\" ? .dark : .light)\n }\n \n // Modify getDocumentsDirectory to use cached value\n private func getDocumentsDirectory() -> URL {\n return documentsDirectory\n }\n \n // Add function to save text\n private func saveText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n print(\"Attempting to save file to: \\(fileURL.path)\")\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved file\")\n } catch {\n print(\"Error saving file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }\n \n // Add function to load text\n ", "suffix_code": "\n \n // Add function to load existing entries\n private func loadExistingEntries() {\n let documentsDirectory = getDocumentsDirectory()\n print(\"Looking for entries in: \\(documentsDirectory.path)\")\n \n do {\n let fileURLs = try fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)\n let mdFiles = fileURLs.filter { $0.pathExtension == \"md\" }\n \n print(\"Found \\(mdFiles.count) .md files\")\n \n // Process each file\n let entriesWithDates = mdFiles.compactMap { fileURL -> (entry: HumanEntry, date: Date, content: String)? in\n let filename = fileURL.lastPathComponent\n print(\"Processing: \\(filename)\")\n \n // Extract UUID and date from filename - pattern [uuid]-[yyyy-MM-dd-HH-mm-ss].md\n guard let uuidMatch = filename.range(of: \"\\\\[(.*?)\\\\]\", options: .regularExpression),\n let dateMatch = filename.range(of: \"\\\\[(\\\\d{4}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2})\\\\]\", options: .regularExpression),\n let uuid = UUID(uuidString: String(filename[uuidMatch].dropFirst().dropLast())) else {\n print(\"Failed to extract UUID or date from filename: \\(filename)\")\n return nil\n }\n \n // Parse the date string\n let dateString = String(filename[dateMatch].dropFirst().dropLast())\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n \n guard let fileDate = dateFormatter.date(from: dateString) else {\n print(\"Failed to parse date from filename: \\(filename)\")\n return nil\n }\n \n // Read file contents for preview\n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Format display date\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: fileDate)\n \n return (\n entry: HumanEntry(\n id: uuid,\n date: displayDate,\n filename: filename,\n previewText: truncated\n ),\n date: fileDate,\n content: content // Store the full content to check for welcome message\n )\n } catch {\n print(\"Error reading file: \\(error)\")\n return nil\n }\n }\n \n // Sort and extract entries\n entries = entriesWithDates\n .sorted { $0.date > $1.date } // Sort by actual date from filename\n .map { $0.entry }\n \n print(\"Successfully loaded and sorted \\(entries.count) entries\")\n \n // Check if we need to create a new entry\n let calendar = Calendar.current\n let today = Date()\n let todayStart = calendar.startOfDay(for: today)\n \n // Check if there's an empty entry from today\n let hasEmptyEntryToday = entries.contains { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }\n \n // Check if we have only one entry and it's the welcome message\n let hasOnlyWelcomeEntry = entries.count == 1 && entriesWithDates.first?.content.contains(\"Welcome to Freewrite.\") == true\n \n if entries.isEmpty {\n // First time user - create entry with welcome message\n print(\"First time user, creating welcome entry\")\n createNewEntry()\n } else if !hasEmptyEntryToday && !hasOnlyWelcomeEntry {\n // No empty entry for today and not just the welcome entry - create new entry\n print(\"No empty entry for today, creating new entry\")\n createNewEntry()\n } else {\n // Select the most recent empty entry from today or the welcome entry\n if let todayEntry = entries.first(where: { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }) {\n selectedEntryId = todayEntry.id\n loadEntry(entry: todayEntry)\n } else if hasOnlyWelcomeEntry {\n // If we only have the welcome entry, select it\n selectedEntryId = entries[0].id\n loadEntry(entry: entries[0])\n }\n }\n \n } catch {\n print(\"Error loading directory contents: \\(error)\")\n print(\"Creating default entry after error\")\n createNewEntry()\n }\n }\n \n var randomButtonTitle: String {\n return currentRandomFont.isEmpty ? \"Random\" : \"Random [\\(currentRandomFont)]\"\n }\n \n var timerButtonTitle: String {\n if !timerIsRunning && timeRemaining == 900 {\n return \"15:00\"\n }\n let minutes = timeRemaining / 60\n let seconds = timeRemaining % 60\n return String(format: \"%d:%02d\", minutes, seconds)\n }\n \n var timerColor: Color {\n if timerIsRunning {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : .gray.opacity(0.8)\n } else {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : (colorScheme == .light ? .gray : .gray.opacity(0.8))\n }\n }\n \n var lineHeight: CGFloat {\n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let defaultLineHeight = getLineHeight(font: font)\n return (fontSize * 1.5) - defaultLineHeight\n }\n \n var fontSizeButtonTitle: String {\n return \"\\(Int(fontSize))px\"\n }\n \n var placeholderOffset: CGFloat {\n // Instead of using calculated line height, use a simple offset\n return fontSize / 2\n }\n \n // Add a color utility computed property\n var popoverBackgroundColor: Color {\n return colorScheme == .light ? Color(NSColor.controlBackgroundColor) : Color(NSColor.darkGray)\n }\n \n var popoverTextColor: Color {\n return colorScheme == .light ? Color.primary : Color.white\n }\n \n @State private var viewHeight: CGFloat = 0\n \n var body: some View {\n let buttonBackground = colorScheme == .light ? Color.white : Color.black\n let navHeight: CGFloat = 68\n let textColor = colorScheme == .light ? Color.gray : Color.gray.opacity(0.8)\n let textHoverColor = colorScheme == .light ? Color.black : Color.white\n \n HStack(spacing: 0) {\n // Main content\n ZStack {\n Color(colorScheme == .light ? .white : .black)\n .ignoresSafeArea()\n \n \n TextEditor(text: Binding(\n get: { text },\n set: { newValue in\n // Ensure the text always starts with two newlines\n if !newValue.hasPrefix(\"\\n\\n\") {\n text = \"\\n\\n\" + newValue.trimmingCharacters(in: .newlines)\n } else {\n text = newValue\n }\n }\n ))\n .background(Color(colorScheme == .light ? .white : .black))\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? Color(red: 0.20, green: 0.20, blue: 0.20) : Color(red: 0.9, green: 0.9, blue: 0.9))\n .scrollContentBackground(.hidden)\n .scrollIndicators(.never)\n .lineSpacing(lineHeight)\n .frame(maxWidth: 650)\n \n \n .id(\"\\(selectedFont)-\\(fontSize)-\\(colorScheme)\")\n .padding(.bottom, bottomNavOpacity > 0 ? navHeight : 0)\n .ignoresSafeArea()\n .colorScheme(colorScheme)\n .onAppear {\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Removed findSubview code which was causing errors\n }\n .overlay(\n ZStack(alignment: .topLeading) {\n if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n Text(placeholderText)\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? .gray.opacity(0.5) : .gray.opacity(0.6))\n // .padding(.top, 8)\n // .padding(.leading, 8)\n .allowsHitTesting(false)\n .offset(x: 5, y: placeholderOffset)\n }\n }, alignment: .topLeading\n )\n .onGeometryChange(for: CGFloat.self) { proxy in\n proxy.size.height\n } action: { height in\n viewHeight = height\n }\n .contentMargins(.bottom, viewHeight / 4)\n \n \n VStack {\n Spacer()\n HStack {\n // Font buttons (moved to left)\n HStack(spacing: 8) {\n Button(fontSizeButtonTitle) {\n if let currentIndex = fontSizes.firstIndex(of: fontSize) {\n let nextIndex = (currentIndex + 1) % fontSizes.count\n fontSize = fontSizes[nextIndex]\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringSize ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringSize = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Lato\") {\n selectedFont = \"Lato-Regular\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Lato\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Lato\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Arial\") {\n selectedFont = \"Arial\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Arial\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Arial\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"System\") {\n selectedFont = \".AppleSystemUIFont\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"System\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"System\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Serif\") {\n selectedFont = \"Times New Roman\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Serif\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Serif\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(randomButtonTitle) {\n if let randomFont = availableFonts.randomElement() {\n selectedFont = randomFont\n currentRandomFont = randomFont\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Random\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Random\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n \n Spacer()\n \n // Utility buttons (moved to right)\n HStack(spacing: 8) {\n Button(timerButtonTitle) {\n let now = Date()\n if let lastClick = lastClickTime,\n now.timeIntervalSince(lastClick) < 0.3 {\n timeRemaining = 900\n timerIsRunning = false\n lastClickTime = nil\n } else {\n timerIsRunning.toggle()\n lastClickTime = now\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(timerColor)\n .onHover { hovering in\n isHoveringTimer = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .onAppear {\n NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in\n if isHoveringTimer {\n let scrollBuffer = event.deltaY * 0.25\n \n if abs(scrollBuffer) >= 0.1 {\n let currentMinutes = timeRemaining / 60\n NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now)\n let direction = -scrollBuffer > 0 ? 5 : -5\n let newMinutes = currentMinutes + direction\n let roundedMinutes = (newMinutes / 5) * 5\n let newTime = roundedMinutes * 60\n timeRemaining = min(max(newTime, 0), 2700)\n }\n }\n return event\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Chat\") {\n showingChatMenu = true\n // Ensure didCopyPrompt is reset when opening the menu\n didCopyPrompt = false\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringChat ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringChat = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .popover(isPresented: $showingChatMenu, attachmentAnchor: .point(UnitPoint(x: 0.5, y: 0)), arrowEdge: .top) {\n VStack(spacing: 0) { // Wrap everything in a VStack for consistent styling and onChange\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Calculate potential URL lengths\n let gptFullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n let claudeFullText = claudePrompt + \"\\n\\n\" + trimmedText\n let encodedGptText = gptFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n let encodedClaudeText = claudeFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n \n let gptUrlLength = \"https://chat.openai.com/?m=\".count + encodedGptText.count\n let claudeUrlLength = \"https://claude.ai/new?q=\".count + encodedClaudeText.count\n let isUrlTooLong = gptUrlLength > 6000 || claudeUrlLength > 6000\n \n if isUrlTooLong {\n // View for long text (URL too long)\n Text(\"Hey, your entry is long. It'll break the URL. Instead, copy prompt by clicking below and paste into AI of your choice!\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .lineLimit(nil)\n .multilineTextAlignment(.leading)\n .frame(width: 200, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n \n Divider()\n \n Button(action: {\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n } else if text.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix(\"hi. my name is farza.\") {\n Text(\"Yo. Sorry, you can't chat with the guide lol. Please write your own entry.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else if text.count < 350 {\n Text(\"Please free write for at minimum 5 minutes first. Then click this. Trust.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else {\n // View for normal text length\n Button(action: {\n showingChatMenu = false\n openChatGPT()\n }) {\n Text(\"ChatGPT\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n showingChatMenu = false\n openClaude()\n }) {\n Text(\"Claude\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n // Don't dismiss menu, just copy and update state\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n .frame(minWidth: 120, maxWidth: 250) // Allow width to adjust\n .background(popoverBackgroundColor)\n .cornerRadius(8)\n .shadow(color: Color.black.opacity(0.1), radius: 4, y: 2)\n // Reset copied state when popover dismisses\n .onChange(of: showingChatMenu) { newValue in\n if !newValue {\n didCopyPrompt = false\n }\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(isFullscreen ? \"Minimize\" : \"Fullscreen\") {\n if let window = NSApplication.shared.windows.first {\n window.toggleFullScreen(nil)\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringFullscreen ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringFullscreen = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(action: {\n createNewEntry()\n }) {\n Text(\"New Entry\")\n .font(.system(size: 13))\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringNewEntry ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringNewEntry = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n // Theme toggle button\n Button(action: {\n colorScheme = colorScheme == .light ? .dark : .light\n // Save preference\n UserDefaults.standard.set(colorScheme == .light ? \"light\" : \"dark\", forKey: \"colorScheme\")\n }) {\n Image(systemName: colorScheme == .light ? \"moon.fill\" : \"sun.max.fill\")\n .foregroundColor(isHoveringThemeToggle ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringThemeToggle = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n\n Text(\"•\")\n .foregroundColor(.gray)\n \n // Version history button\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showingSidebar.toggle()\n }\n }) {\n Image(systemName: \"clock.arrow.circlepath\")\n .foregroundColor(isHoveringClock ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringClock = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n }\n .padding()\n .background(Color(colorScheme == .light ? .white : .black))\n .opacity(bottomNavOpacity)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n if hovering {\n withAnimation(.easeOut(duration: 0.2)) {\n bottomNavOpacity = 1.0\n }\n } else if timerIsRunning {\n withAnimation(.easeIn(duration: 1.0)) {\n bottomNavOpacity = 0.0\n }\n }\n }\n }\n }\n \n // Right sidebar\n if showingSidebar {\n Divider()\n \n VStack(spacing: 0) {\n // Header\n Button(action: {\n NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: getDocumentsDirectory().path)\n }) {\n HStack {\n VStack(alignment: .leading, spacing: 4) {\n HStack(spacing: 4) {\n Text(\"History\")\n .font(.system(size: 13))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n Image(systemName: \"arrow.up.right\")\n .font(.system(size: 10))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n }\n Text(getDocumentsDirectory().path)\n .font(.system(size: 10))\n .foregroundColor(.secondary)\n .lineLimit(1)\n }\n Spacer()\n }\n }\n .buttonStyle(.plain)\n .padding(.horizontal, 16)\n .padding(.vertical, 12)\n .onHover { hovering in\n isHoveringHistory = hovering\n }\n \n Divider()\n \n // Entries List\n ScrollView {\n LazyVStack(spacing: 0) {\n ForEach(entries) { entry in\n Button(action: {\n if selectedEntryId != entry.id {\n // Save current entry before switching\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n \n selectedEntryId = entry.id\n loadEntry(entry: entry)\n }\n }) {\n HStack(alignment: .top) {\n VStack(alignment: .leading, spacing: 4) {\n HStack {\n Text(entry.previewText)\n .font(.system(size: 13))\n .lineLimit(1)\n .foregroundColor(.primary)\n \n Spacer()\n \n // Export/Trash icons that appear on hover\n if hoveredEntryId == entry.id {\n HStack(spacing: 8) {\n // Export PDF button\n Button(action: {\n exportEntryAsPDF(entry: entry)\n }) {\n Image(systemName: \"arrow.down.circle\")\n .font(.system(size: 11))\n .foregroundColor(hoveredExportId == entry.id ? \n (colorScheme == .light ? .black : .white) : \n (colorScheme == .light ? .gray : .gray.opacity(0.8)))\n }\n .buttonStyle(.plain)\n .help(\"Export entry as PDF\")\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredExportId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n // Trash icon\n Button(action: {\n deleteEntry(entry: entry)\n }) {\n Image(systemName: \"trash\")\n .font(.system(size: 11))\n .foregroundColor(hoveredTrashId == entry.id ? .red : .gray)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredTrashId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n }\n \n Text(entry.date)\n .font(.system(size: 12))\n .foregroundColor(.secondary)\n }\n }\n .frame(maxWidth: .infinity)\n .padding(.horizontal, 16)\n .padding(.vertical, 8)\n .background(\n RoundedRectangle(cornerRadius: 4)\n .fill(backgroundColor(for: entry))\n )\n }\n .buttonStyle(PlainButtonStyle())\n .contentShape(Rectangle())\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredEntryId = hovering ? entry.id : nil\n }\n }\n .onAppear {\n NSCursor.pop() // Reset cursor when button appears\n }\n .help(\"Click to select this entry\") // Add tooltip\n \n if entry.id != entries.last?.id {\n Divider()\n }\n }\n }\n }\n .scrollIndicators(.never)\n }\n .frame(width: 200)\n .background(Color(colorScheme == .light ? .white : NSColor.black))\n }\n }\n .frame(minWidth: 1100, minHeight: 600)\n .animation(.easeInOut(duration: 0.2), value: showingSidebar)\n .preferredColorScheme(colorScheme)\n .onAppear {\n showingSidebar = false // Hide sidebar by default\n loadExistingEntries()\n }\n .onChange(of: text) { _ in\n // Save current entry when text changes\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n }\n .onReceive(timer) { _ in\n if timerIsRunning && timeRemaining > 0 {\n timeRemaining -= 1\n } else if timeRemaining == 0 {\n timerIsRunning = false\n if !isHoveringBottomNav {\n withAnimation(.easeOut(duration: 1.0)) {\n bottomNavOpacity = 1.0\n }\n }\n }\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willEnterFullScreenNotification)) { _ in\n isFullscreen = true\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willExitFullScreenNotification)) { _ in\n isFullscreen = false\n }\n }\n \n private func backgroundColor(for entry: HumanEntry) -> Color {\n if entry.id == selectedEntryId {\n return Color.gray.opacity(0.1) // More subtle selection highlight\n } else if entry.id == hoveredEntryId {\n return Color.gray.opacity(0.05) // Even more subtle hover state\n } else {\n return Color.clear\n }\n }\n \n private func updatePreviewText(for entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Find and update the entry in the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries[index].previewText = truncated\n }\n } catch {\n print(\"Error updating preview text: \\(error)\")\n }\n }\n \n private func saveEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved entry: \\(entry.filename)\")\n updatePreviewText(for: entry) // Update preview after saving\n } catch {\n print(\"Error saving entry: \\(error)\")\n }\n }\n \n private func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded entry: \\(entry.filename)\")\n }\n } catch {\n print(\"Error loading entry: \\(error)\")\n }\n }\n \n private func createNewEntry() {\n let newEntry = HumanEntry.createNew()\n entries.insert(newEntry, at: 0) // Add to the beginning\n selectedEntryId = newEntry.id\n \n // If this is the first entry (entries was empty before adding this one)\n if entries.count == 1 {\n // Read welcome message from default.md\n if let defaultMessageURL = Bundle.main.url(forResource: \"default\", withExtension: \"md\"),\n let defaultMessage = try? String(contentsOf: defaultMessageURL, encoding: .utf8) {\n text = \"\\n\\n\" + defaultMessage\n }\n // Save the welcome message immediately\n saveEntry(entry: newEntry)\n // Update the preview text\n updatePreviewText(for: newEntry)\n } else {\n // Regular new entry starts with newlines\n text = \"\\n\\n\"\n // Randomize placeholder text for new entry\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Save the empty entry\n saveEntry(entry: newEntry)\n }\n }\n \n private func openChatGPT() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://chat.openai.com/?m=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n \n private func openClaude() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = claudePrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://claude.ai/new?q=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n\n private func copyPromptToClipboard() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n\n let pasteboard = NSPasteboard.general\n pasteboard.clearContents()\n pasteboard.setString(fullText, forType: .string)\n print(\"Prompt copied to clipboard\")\n }\n \n private func deleteEntry(entry: HumanEntry) {\n // Delete the file from the filesystem\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try fileManager.removeItem(at: fileURL)\n print(\"Successfully deleted file: \\(entry.filename)\")\n \n // Remove the entry from the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries.remove(at: index)\n \n // If the deleted entry was selected, select the first entry or create a new one\n if selectedEntryId == entry.id {\n if let firstEntry = entries.first {\n selectedEntryId = firstEntry.id\n loadEntry(entry: firstEntry)\n } else {\n createNewEntry()\n }\n }\n }\n } catch {\n print(\"Error deleting file: \\(error)\")\n }\n }\n \n // Extract a title from entry content for PDF export\n private func extractTitleFromContent(_ content: String, date: String) -> String {\n // Clean up content by removing leading/trailing whitespace and newlines\n let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // If content is empty, just use the date\n if trimmedContent.isEmpty {\n return \"Entry \\(date)\"\n }\n \n // Split content into words, ignoring newlines and removing punctuation\n let words = trimmedContent\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .components(separatedBy: .whitespaces)\n .filter { !$0.isEmpty }\n .map { word in\n word.trimmingCharacters(in: CharacterSet(charactersIn: \".,!?;:\\\"'()[]{}<>\"))\n .lowercased()\n }\n .filter { !$0.isEmpty }\n \n // If we have at least 4 words, use them\n if words.count >= 4 {\n return \"\\(words[0])-\\(words[1])-\\(words[2])-\\(words[3])\"\n }\n \n // If we have fewer than 4 words, use what we have\n if !words.isEmpty {\n return words.joined(separator: \"-\")\n }\n \n // Fallback to date if no words found\n return \"Entry \\(date)\"\n }\n \n private func exportEntryAsPDF(entry: HumanEntry) {\n // First make sure the current entry is saved\n if selectedEntryId == entry.id {\n saveEntry(entry: entry)\n }\n \n // Get entry content\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n // Read the content of the entry\n let entryContent = try String(contentsOf: fileURL, encoding: .utf8)\n \n // Extract a title from the entry content and add .pdf extension\n let suggestedFilename = extractTitleFromContent(entryContent, date: entry.date) + \".pdf\"\n \n // Create save panel\n let savePanel = NSSavePanel()\n savePanel.allowedContentTypes = [UTType.pdf]\n savePanel.nameFieldStringValue = suggestedFilename\n savePanel.isExtensionHidden = false // Make sure extension is visible\n \n // Show save dialog\n if savePanel.runModal() == .OK, let url = savePanel.url {\n // Create PDF data\n if let pdfData = createPDFFromText(text: entryContent) {\n try pdfData.write(to: url)\n print(\"Successfully exported PDF to: \\(url.path)\")\n }\n }\n } catch {\n print(\"Error in PDF export: \\(error)\")\n }\n }\n \n private func createPDFFromText(text: String) -> Data? {\n // Letter size page dimensions\n let pageWidth: CGFloat = 612.0 // 8.5 x 72\n let pageHeight: CGFloat = 792.0 // 11 x 72\n let margin: CGFloat = 72.0 // 1-inch margins\n \n // Calculate content area\n let contentRect = CGRect(\n x: margin,\n y: margin,\n width: pageWidth - (margin * 2),\n height: pageHeight - (margin * 2)\n )\n \n // Create PDF data container\n let pdfData = NSMutableData()\n \n // Configure text formatting attributes\n let paragraphStyle = NSMutableParagraphStyle()\n paragraphStyle.lineSpacing = lineHeight\n \n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let textAttributes: [NSAttributedString.Key: Any] = [\n .font: font,\n .foregroundColor: NSColor(red: 0.20, green: 0.20, blue: 0.20, alpha: 1.0),\n .paragraphStyle: paragraphStyle\n ]\n \n // Trim the initial newlines before creating the PDF\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Create the attributed string with formatting\n let attributedString = NSAttributedString(string: trimmedText, attributes: textAttributes)\n \n // Create a Core Text framesetter for text layout\n let framesetter = CTFramesetterCreateWithAttributedString(attributedString)\n \n // Create a PDF context with the data consumer\n guard let pdfContext = CGContext(consumer: CGDataConsumer(data: pdfData as CFMutableData)!, mediaBox: nil, nil) else {\n print(\"Failed to create PDF context\")\n return nil\n }\n \n // Track position within text\n var currentRange = CFRange(location: 0, length: 0)\n var pageIndex = 0\n \n // Create a path for the text frame\n let framePath = CGMutablePath()\n framePath.addRect(contentRect)\n \n // Continue creating pages until all text is processed\n while currentRange.location < attributedString.length {\n // Begin a new PDF page\n pdfContext.beginPage(mediaBox: nil)\n \n // Fill the page with white background\n pdfContext.setFillColor(NSColor.white.cgColor)\n pdfContext.fill(CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight))\n \n // Create a frame for this page's text\n let frame = CTFramesetterCreateFrame(\n framesetter, \n currentRange, \n framePath, \n nil\n )\n \n // Draw the text frame\n CTFrameDraw(frame, pdfContext)\n \n // Get the range of text that was actually displayed in this frame\n let visibleRange = CTFrameGetVisibleStringRange(frame)\n \n // Move to the next block of text for the next page\n currentRange.location += visibleRange.length\n \n // Finish the page\n pdfContext.endPage()\n pageIndex += 1\n \n // Safety check - don't allow infinite loops\n if pageIndex > 1000 {\n print(\"Safety limit reached - stopping PDF generation\")\n break\n }\n }\n \n // Finalize the PDF document\n pdfContext.closePDF()\n \n return pdfData as Data\n }\n}\n\n// Helper function to calculate line height\nfunc getLineHeight(font: NSFont) -> CGFloat {\n return font.ascender - font.descender + font.leading\n}\n\n// Add helper extension to find NSTextView\nextension NSView {\n func findTextView() -> NSView? {\n if self is NSTextView {\n return self\n }\n for subview in subviews {\n if let textView = subview.findTextView() {\n return textView\n }\n }\n return nil\n }\n}\n\n// Add helper extension for finding subviews of a specific type\nextension NSView {\n func findSubview<T: NSView>(ofType type: T.Type) -> T? {\n if let typedSelf = self as? T {\n return typedSelf\n }\n for subview in subviews {\n if let found = subview.findSubview(ofType: type) {\n return found\n }\n }\n return nil\n }\n}\n\n#Preview {\n ContentView()\n}\n", "middle_code": "private func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n print(\"Attempting to load file from: \\(fileURL.path)\")\n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded file\")\n } else {\n print(\"File does not exist yet\")\n }\n } catch {\n print(\"Error loading file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/freewrite/freewrite/freewriteApp.swift", "//\n// freewriteApp.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\n\n@main\nstruct freewriteApp: App {\n @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n @AppStorage(\"colorScheme\") private var colorSchemeString: String = \"light\"\n \n init() {\n // Register Lato font\n if let fontURL = Bundle.main.url(forResource: \"Lato-Regular\", withExtension: \"ttf\") {\n CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, nil)\n }\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .toolbar(.hidden, for: .windowToolbar)\n .preferredColorScheme(colorSchemeString == \"dark\" ? .dark : .light)\n }\n .windowStyle(.hiddenTitleBar)\n .defaultSize(width: 1100, height: 600)\n .windowToolbarStyle(.unifiedCompact)\n .windowResizability(.contentSize)\n }\n}\n\n// Add AppDelegate to handle window configuration\nclass AppDelegate: NSObject, NSApplicationDelegate {\n func applicationDidFinishLaunching(_ notification: Notification) {\n if let window = NSApplication.shared.windows.first {\n // Ensure window starts in windowed mode\n if window.styleMask.contains(.fullScreen) {\n window.toggleFullScreen(nil)\n }\n \n // Center the window on the screen\n window.center()\n }\n }\n} \n"]], "task_instance_info": {"created_time": "2025-08-21 03:24:27", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func loadText ( ) { }", "code_description": "This code segment functions to: Retrieve stored text content from a designated file location and assign it to the application's main text storage component while handling potential file access errors."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n do {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded text from: \\(fileURL.path)\")\n } catch {\n print(\"Error loading text: \\(error)\")\n // Initialize with empty text if file doesn't exist\n text = \"\\n\\n\"\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-24-45"}, "editdistance_info": {"edit_distance": 48.0315, "calculate_time": "2025-08-21 03:24:45", "true_code_clean": "private func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n print(\"Attempting to load file from: \\(fileURL.path)\")\n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded file\")\n } else {\n print(\"File does not exist yet\")\n }\n } catch {\n print(\"Error loading file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }", "predict_code_clean": "private func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n do {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded text from: \\(fileURL.path)\")\n } catch {\n print(\"Error loading text: \\(error)\")\n text = \"\\n\\n\"\n }\n}"}} | |
| {"repo_name": "freewrite", "file_name": "/freewrite/freewrite/ContentView.swift", "inference_info": {"prefix_code": "// Swift 5.0\n//\n// ContentView.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\nimport AppKit\nimport UniformTypeIdentifiers\nimport PDFKit\n\nstruct HumanEntry: Identifiable {\n let id: UUID\n let date: String\n let filename: String\n var previewText: String\n \n static func createNew() -> HumanEntry {\n let id = UUID()\n let now = Date()\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n let dateString = dateFormatter.string(from: now)\n \n // For display\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: now)\n \n return HumanEntry(\n id: id,\n date: displayDate,\n filename: \"[\\(id)]-[\\(dateString)].md\",\n previewText: \"\"\n )\n }\n}\n\nstruct HeartEmoji: Identifiable {\n let id = UUID()\n var position: CGPoint\n var offset: CGFloat = 0\n}\n\nstruct ContentView: View {\n private let headerString = \"\\n\\n\"\n @State private var entries: [HumanEntry] = []\n @State private var text: String = \"\" // Remove initial welcome text since we'll handle it in createNewEntry\n \n @State private var isFullscreen = false\n @State private var selectedFont: String = \"Lato-Regular\"\n @State private var currentRandomFont: String = \"\"\n @State private var timeRemaining: Int = 900 // Changed to 900 seconds (15 minutes)\n @State private var timerIsRunning = false\n @State private var isHoveringTimer = false\n @State private var isHoveringFullscreen = false\n @State private var hoveredFont: String? = nil\n @State private var isHoveringSize = false\n @State private var fontSize: CGFloat = 18\n @State private var blinkCount = 0\n @State private var isBlinking = false\n @State private var opacity: Double = 1.0\n @State private var shouldShowGray = true // New state to control color\n @State private var lastClickTime: Date? = nil\n @State private var bottomNavOpacity: Double = 1.0\n @State private var isHoveringBottomNav = false\n @State private var selectedEntryIndex: Int = 0\n @State private var scrollOffset: CGFloat = 0\n @State private var selectedEntryId: UUID? = nil\n @State private var hoveredEntryId: UUID? = nil\n @State private var isHoveringChat = false // Add this state variable\n @State private var showingChatMenu = false\n @State private var chatMenuAnchor: CGPoint = .zero\n @State private var showingSidebar = false // Add this state variable\n @State private var hoveredTrashId: UUID? = nil\n @State private var hoveredExportId: UUID? = nil\n @State private var placeholderText: String = \"\" // Add this line\n @State private var isHoveringNewEntry = false\n @State private var isHoveringClock = false\n @State private var isHoveringHistory = false\n @State private var isHoveringHistoryText = false\n @State private var isHoveringHistoryPath = false\n @State private var isHoveringHistoryArrow = false\n @State private var colorScheme: ColorScheme = .light // Add state for color scheme\n @State private var isHoveringThemeToggle = false // Add state for theme toggle hover\n @State private var didCopyPrompt: Bool = false // Add state for copy prompt feedback\n let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()\n let entryHeight: CGFloat = 40\n \n let availableFonts = NSFontManager.shared.availableFontFamilies\n let standardFonts = [\"Lato-Regular\", \"Arial\", \".AppleSystemUIFont\", \"Times New Roman\"]\n let fontSizes: [CGFloat] = [16, 18, 20, 22, 24, 26]\n let placeholderOptions = [\n \"\\n\\nBegin writing\",\n \"\\n\\nPick a thought and go\",\n \"\\n\\nStart typing\",\n \"\\n\\nWhat's on your mind\",\n \"\\n\\nJust start\",\n \"\\n\\nType your first thought\",\n \"\\n\\nStart with one sentence\",\n \"\\n\\nJust say it\"\n ]\n \n // Add file manager and save timer\n private let fileManager = FileManager.default\n private let saveTimer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()\n \n // Add cached documents directory\n private let documentsDirectory: URL = {\n let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(\"Freewrite\")\n \n // Create Freewrite directory if it doesn't exist\n if !FileManager.default.fileExists(atPath: directory.path) {\n do {\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n print(\"Successfully created Freewrite directory\")\n } catch {\n print(\"Error creating directory: \\(error)\")\n }\n }\n \n return directory\n }()\n \n // Add shared prompt constant\n private let aiChatPrompt = \"\"\"\n below is my journal entry. wyt? talk through it with me like a friend. don't therpaize me and give me a whole breakdown, don't repeat my thoughts with headings. really take all of this, and tell me back stuff truly as if you're an old homie.\n \n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n\n do not just go through every single thing i say, and say it back to me. you need to proccess everythikng is say, make connections i don't see it, and deliver it all back to me as a story that makes me feel what you think i wanna feel. thats what the best therapists do.\n\n ideally, you're style/tone should sound like the user themselves. it's as if the user is hearing their own tone but it should still feel different, because you have different things to say and don't just repeat back they say.\n\n else, start by saying, \"hey, thanks for showing me this. my thoughts:\"\n \n my entry:\n \"\"\"\n \n private let claudePrompt = \"\"\"\n Take a look at my journal entry below. I'd like you to analyze it and respond with deep insight that feels personal, not clinical.\n Imagine you're not just a friend, but a mentor who truly gets both my tech background and my psychological patterns. I want you to uncover the deeper meaning and emotional undercurrents behind my scattered thoughts.\n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n Use vivid metaphors and powerful imagery to help me see what I'm really building. Organize your thoughts with meaningful headings that create a narrative journey through my ideas.\n Don't just validate my thoughts - reframe them in a way that shows me what I'm really seeking beneath the surface. Go beyond the product concepts to the emotional core of what I'm trying to solve.\n Be willing to be profound and philosophical without sounding like you're giving therapy. I want someone who can see the patterns I can't see myself and articulate them in a way that feels like an epiphany.\n Start with 'hey, thanks for showing me this. my thoughts:' and then use markdown headings to structure your response.\n\n Here's my journal entry:\n \"\"\"\n \n // Initialize with saved theme preference if available\n init() {\n // Load saved color scheme preference\n let savedScheme = UserDefaults.standard.string(forKey: \"colorScheme\") ?? \"light\"\n _colorScheme = State(initialValue: savedScheme == \"dark\" ? .dark : .light)\n }\n \n // Modify getDocumentsDirectory to use cached value\n private func getDocumentsDirectory() -> URL {\n return documentsDirectory\n }\n \n // Add function to save text\n private func saveText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n print(\"Attempting to save file to: \\(fileURL.path)\")\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved file\")\n } catch {\n print(\"Error saving file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }\n \n // Add function to load text\n private func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n print(\"Attempting to load file from: \\(fileURL.path)\")\n \n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded file\")\n } else {\n print(\"File does not exist yet\")\n }\n } catch {\n print(\"Error loading file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }\n \n // Add function to load existing entries\n private func loadExistingEntries() {\n let documentsDirectory = getDocumentsDirectory()\n print(\"Looking for entries in: \\(documentsDirectory.path)\")\n \n do {\n let fileURLs = try fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)\n let mdFiles = fileURLs.filter { $0.pathExtension == \"md\" }\n \n print(\"Found \\(mdFiles.count) .md files\")\n \n // Process each file\n let entriesWithDates = mdFiles.compactMap { fileURL -> (entry: HumanEntry, date: Date, content: String)? in\n let filename = fileURL.lastPathComponent\n print(\"Processing: \\(filename)\")\n \n // Extract UUID and date from filename - pattern [uuid]-[yyyy-MM-dd-HH-mm-ss].md\n guard let uuidMatch = filename.range(of: \"\\\\[(.*?)\\\\]\", options: .regularExpression),\n let dateMatch = filename.range(of: \"\\\\[(\\\\d{4}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2})\\\\]\", options: .regularExpression),\n let uuid = UUID(uuidString: String(filename[uuidMatch].dropFirst().dropLast())) else {\n print(\"Failed to extract UUID or date from filename: \\(filename)\")\n return nil\n }\n \n // Parse the date string\n let dateString = String(filename[dateMatch].dropFirst().dropLast())\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n \n guard let fileDate = dateFormatter.date(from: dateString) else {\n print(\"Failed to parse date from filename: \\(filename)\")\n return nil\n }\n \n // Read file contents for preview\n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Format display date\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: fileDate)\n \n return (\n entry: HumanEntry(\n id: uuid,\n date: displayDate,\n filename: filename,\n previewText: truncated\n ),\n date: fileDate,\n content: content // Store the full content to check for welcome message\n )\n } catch {\n print(\"Error reading file: \\(error)\")\n return nil\n }\n }\n \n // Sort and extract entries\n entries = entriesWithDates\n .sorted { $0.date > $1.date } // Sort by actual date from filename\n .map { $0.entry }\n \n print(\"Successfully loaded and sorted \\(entries.count) entries\")\n \n // Check if we need to create a new entry\n let calendar = Calendar.current\n let today = Date()\n let todayStart = calendar.startOfDay(for: today)\n \n // Check if there's an empty entry from today\n let hasEmptyEntryToday = entries.contains { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }\n \n // Check if we have only one entry and it's the welcome message\n let hasOnlyWelcomeEntry = entries.count == 1 && entriesWithDates.first?.content.contains(\"Welcome to Freewrite.\") == true\n \n if entries.isEmpty {\n // First time user - create entry with welcome message\n print(\"First time user, creating welcome entry\")\n createNewEntry()\n } else if !hasEmptyEntryToday && !hasOnlyWelcomeEntry {\n // No empty entry for today and not just the welcome entry - create new entry\n print(\"No empty entry for today, creating new entry\")\n createNewEntry()\n } else {\n // Select the most recent empty entry from today or the welcome entry\n if let todayEntry = entries.first(where: { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }) {\n selectedEntryId = todayEntry.id\n loadEntry(entry: todayEntry)\n } else if hasOnlyWelcomeEntry {\n // If we only have the welcome entry, select it\n selectedEntryId = entries[0].id\n loadEntry(entry: entries[0])\n }\n }\n \n } catch {\n print(\"Error loading directory contents: \\(error)\")\n print(\"Creating default entry after error\")\n createNewEntry()\n }\n }\n \n var randomButtonTitle: String {\n return currentRandomFont.isEmpty ? \"Random\" : \"Random [\\(currentRandomFont)]\"\n }\n \n var timerButtonTitle: String {\n if !timerIsRunning && timeRemaining == 900 {\n return \"15:00\"\n }\n let minutes = timeRemaining / 60\n let seconds = timeRemaining % 60\n return String(format: \"%d:%02d\", minutes, seconds)\n }\n \n var timerColor: Color {\n if timerIsRunning {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : .gray.opacity(0.8)\n } else {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : (colorScheme == .light ? .gray : .gray.opacity(0.8))\n }\n }\n \n var lineHeight: CGFloat {\n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let defaultLineHeight = getLineHeight(font: font)\n return (fontSize * 1.5) - defaultLineHeight\n }\n \n var fontSizeButtonTitle: String {\n return \"\\(Int(fontSize))px\"\n }\n \n var placeholderOffset: CGFloat {\n // Instead of using calculated line height, use a simple offset\n return fontSize / 2\n }\n \n // Add a color utility computed property\n var popoverBackgroundColor: Color {\n return colorScheme == .light ? Color(NSColor.controlBackgroundColor) : Color(NSColor.darkGray)\n }\n \n var popoverTextColor: Color {\n return colorScheme == .light ? Color.primary : Color.white\n }\n \n @State private var viewHeight: CGFloat = 0\n \n var body: some View {\n let buttonBackground = colorScheme == .light ? Color.white : Color.black\n let navHeight: CGFloat = 68\n let textColor = colorScheme == .light ? Color.gray : Color.gray.opacity(0.8)\n let textHoverColor = colorScheme == .light ? Color.black : Color.white\n \n HStack(spacing: 0) {\n // Main content\n ZStack {\n Color(colorScheme == .light ? .white : .black)\n .ignoresSafeArea()\n \n \n TextEditor(text: Binding(\n get: { text },\n set: { newValue in\n // Ensure the text always starts with two newlines\n if !newValue.hasPrefix(\"\\n\\n\") {\n text = \"\\n\\n\" + newValue.trimmingCharacters(in: .newlines)\n } else {\n text = newValue\n }\n }\n ))\n .background(Color(colorScheme == .light ? .white : .black))\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? Color(red: 0.20, green: 0.20, blue: 0.20) : Color(red: 0.9, green: 0.9, blue: 0.9))\n .scrollContentBackground(.hidden)\n .scrollIndicators(.never)\n .lineSpacing(lineHeight)\n .frame(maxWidth: 650)\n \n \n .id(\"\\(selectedFont)-\\(fontSize)-\\(colorScheme)\")\n .padding(.bottom, bottomNavOpacity > 0 ? navHeight : 0)\n .ignoresSafeArea()\n .colorScheme(colorScheme)\n .onAppear {\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Removed findSubview code which was causing errors\n }\n .overlay(\n ZStack(alignment: .topLeading) {\n if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n Text(placeholderText)\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? .gray.opacity(0.5) : .gray.opacity(0.6))\n // .padding(.top, 8)\n // .padding(.leading, 8)\n .allowsHitTesting(false)\n .offset(x: 5, y: placeholderOffset)\n }\n }, alignment: .topLeading\n )\n .onGeometryChange(for: CGFloat.self) { proxy in\n proxy.size.height\n } action: { height in\n viewHeight = height\n }\n .contentMargins(.bottom, viewHeight / 4)\n \n \n VStack {\n Spacer()\n HStack {\n // Font buttons (moved to left)\n HStack(spacing: 8) {\n Button(fontSizeButtonTitle) {\n if let currentIndex = fontSizes.firstIndex(of: fontSize) {\n let nextIndex = (currentIndex + 1) % fontSizes.count\n fontSize = fontSizes[nextIndex]\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringSize ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringSize = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Lato\") {\n selectedFont = \"Lato-Regular\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Lato\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Lato\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Arial\") {\n selectedFont = \"Arial\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Arial\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Arial\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"System\") {\n selectedFont = \".AppleSystemUIFont\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"System\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"System\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Serif\") {\n selectedFont = \"Times New Roman\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Serif\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Serif\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(randomButtonTitle) {\n if let randomFont = availableFonts.randomElement() {\n selectedFont = randomFont\n currentRandomFont = randomFont\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Random\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Random\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n \n Spacer()\n \n // Utility buttons (moved to right)\n HStack(spacing: 8) {\n Button(timerButtonTitle) {\n let now = Date()\n if let lastClick = lastClickTime,\n now.timeIntervalSince(lastClick) < 0.3 {\n timeRemaining = 900\n timerIsRunning = false\n lastClickTime = nil\n } else {\n timerIsRunning.toggle()\n lastClickTime = now\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(timerColor)\n .onHover { hovering in\n isHoveringTimer = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .onAppear {\n NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in\n if isHoveringTimer {\n let scrollBuffer = event.deltaY * 0.25\n \n if abs(scrollBuffer) >= 0.1 {\n let currentMinutes = timeRemaining / 60\n NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now)\n let direction = -scrollBuffer > 0 ? 5 : -5\n let newMinutes = currentMinutes + direction\n let roundedMinutes = (newMinutes / 5) * 5\n let newTime = roundedMinutes * 60\n timeRemaining = min(max(newTime, 0), 2700)\n }\n }\n return event\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Chat\") {\n showingChatMenu = true\n // Ensure didCopyPrompt is reset when opening the menu\n didCopyPrompt = false\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringChat ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringChat = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .popover(isPresented: $showingChatMenu, attachmentAnchor: .point(UnitPoint(x: 0.5, y: 0)), arrowEdge: .top) {\n VStack(spacing: 0) { // Wrap everything in a VStack for consistent styling and onChange\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Calculate potential URL lengths\n let gptFullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n let claudeFullText = claudePrompt + \"\\n\\n\" + trimmedText\n let encodedGptText = gptFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n let encodedClaudeText = claudeFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n \n let gptUrlLength = \"https://chat.openai.com/?m=\".count + encodedGptText.count\n let claudeUrlLength = \"https://claude.ai/new?q=\".count + encodedClaudeText.count\n let isUrlTooLong = gptUrlLength > 6000 || claudeUrlLength > 6000\n \n if isUrlTooLong {\n // View for long text (URL too long)\n Text(\"Hey, your entry is long. It'll break the URL. Instead, copy prompt by clicking below and paste into AI of your choice!\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .lineLimit(nil)\n .multilineTextAlignment(.leading)\n .frame(width: 200, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n \n Divider()\n \n Button(action: {\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n } else if text.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix(\"hi. my name is farza.\") {\n Text(\"Yo. Sorry, you can't chat with the guide lol. Please write your own entry.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else if text.count < 350 {\n Text(\"Please free write for at minimum 5 minutes first. Then click this. Trust.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else {\n // View for normal text length\n Button(action: {\n showingChatMenu = false\n openChatGPT()\n }) {\n Text(\"ChatGPT\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n showingChatMenu = false\n openClaude()\n }) {\n Text(\"Claude\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n // Don't dismiss menu, just copy and update state\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n .frame(minWidth: 120, maxWidth: 250) // Allow width to adjust\n .background(popoverBackgroundColor)\n .cornerRadius(8)\n .shadow(color: Color.black.opacity(0.1), radius: 4, y: 2)\n // Reset copied state when popover dismisses\n .onChange(of: showingChatMenu) { newValue in\n if !newValue {\n didCopyPrompt = false\n }\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(isFullscreen ? \"Minimize\" : \"Fullscreen\") {\n if let window = NSApplication.shared.windows.first {\n window.toggleFullScreen(nil)\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringFullscreen ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringFullscreen = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(action: {\n createNewEntry()\n }) {\n Text(\"New Entry\")\n .font(.system(size: 13))\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringNewEntry ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringNewEntry = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n // Theme toggle button\n Button(action: {\n colorScheme = colorScheme == .light ? .dark : .light\n // Save preference\n UserDefaults.standard.set(colorScheme == .light ? \"light\" : \"dark\", forKey: \"colorScheme\")\n }) {\n Image(systemName: colorScheme == .light ? \"moon.fill\" : \"sun.max.fill\")\n .foregroundColor(isHoveringThemeToggle ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringThemeToggle = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n\n Text(\"•\")\n .foregroundColor(.gray)\n \n // Version history button\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showingSidebar.toggle()\n }\n }) {\n Image(systemName: \"clock.arrow.circlepath\")\n .foregroundColor(isHoveringClock ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringClock = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n }\n .padding()\n .background(Color(colorScheme == .light ? .white : .black))\n .opacity(bottomNavOpacity)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n if hovering {\n withAnimation(.easeOut(duration: 0.2)) {\n bottomNavOpacity = 1.0\n }\n } else if timerIsRunning {\n withAnimation(.easeIn(duration: 1.0)) {\n bottomNavOpacity = 0.0\n }\n }\n }\n }\n }\n \n // Right sidebar\n if showingSidebar {\n Divider()\n \n VStack(spacing: 0) {\n // Header\n Button(action: {\n NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: getDocumentsDirectory().path)\n }) {\n HStack {\n VStack(alignment: .leading, spacing: 4) {\n HStack(spacing: 4) {\n Text(\"History\")\n .font(.system(size: 13))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n Image(systemName: \"arrow.up.right\")\n .font(.system(size: 10))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n }\n Text(getDocumentsDirectory().path)\n .font(.system(size: 10))\n .foregroundColor(.secondary)\n .lineLimit(1)\n }\n Spacer()\n }\n }\n .buttonStyle(.plain)\n .padding(.horizontal, 16)\n .padding(.vertical, 12)\n .onHover { hovering in\n isHoveringHistory = hovering\n }\n \n Divider()\n \n // Entries List\n ScrollView {\n LazyVStack(spacing: 0) {\n ForEach(entries) { entry in\n Button(action: {\n if selectedEntryId != entry.id {\n // Save current entry before switching\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n \n selectedEntryId = entry.id\n loadEntry(entry: entry)\n }\n }) {\n HStack(alignment: .top) {\n VStack(alignment: .leading, spacing: 4) {\n HStack {\n Text(entry.previewText)\n .font(.system(size: 13))\n .lineLimit(1)\n .foregroundColor(.primary)\n \n Spacer()\n \n // Export/Trash icons that appear on hover\n if hoveredEntryId == entry.id {\n HStack(spacing: 8) {\n // Export PDF button\n Button(action: {\n exportEntryAsPDF(entry: entry)\n }) {\n Image(systemName: \"arrow.down.circle\")\n .font(.system(size: 11))\n .foregroundColor(hoveredExportId == entry.id ? \n (colorScheme == .light ? .black : .white) : \n (colorScheme == .light ? .gray : .gray.opacity(0.8)))\n }\n .buttonStyle(.plain)\n .help(\"Export entry as PDF\")\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredExportId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n // Trash icon\n Button(action: {\n deleteEntry(entry: entry)\n }) {\n Image(systemName: \"trash\")\n .font(.system(size: 11))\n .foregroundColor(hoveredTrashId == entry.id ? .red : .gray)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredTrashId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n }\n \n Text(entry.date)\n .font(.system(size: 12))\n .foregroundColor(.secondary)\n }\n }\n .frame(maxWidth: .infinity)\n .padding(.horizontal, 16)\n .padding(.vertical, 8)\n .background(\n RoundedRectangle(cornerRadius: 4)\n .fill(backgroundColor(for: entry))\n )\n }\n .buttonStyle(PlainButtonStyle())\n .contentShape(Rectangle())\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredEntryId = hovering ? entry.id : nil\n }\n }\n .onAppear {\n NSCursor.pop() // Reset cursor when button appears\n }\n .help(\"Click to select this entry\") // Add tooltip\n \n if entry.id != entries.last?.id {\n Divider()\n }\n }\n }\n }\n .scrollIndicators(.never)\n }\n .frame(width: 200)\n .background(Color(colorScheme == .light ? .white : NSColor.black))\n }\n }\n .frame(minWidth: 1100, minHeight: 600)\n .animation(.easeInOut(duration: 0.2), value: showingSidebar)\n .preferredColorScheme(colorScheme)\n .onAppear {\n showingSidebar = false // Hide sidebar by default\n loadExistingEntries()\n }\n .onChange(of: text) { _ in\n // Save current entry when text changes\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n }\n .onReceive(timer) { _ in\n if timerIsRunning && timeRemaining > 0 {\n timeRemaining -= 1\n } else if timeRemaining == 0 {\n timerIsRunning = false\n if !isHoveringBottomNav {\n withAnimation(.easeOut(duration: 1.0)) {\n bottomNavOpacity = 1.0\n }\n }\n }\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willEnterFullScreenNotification)) { _ in\n isFullscreen = true\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willExitFullScreenNotification)) { _ in\n isFullscreen = false\n }\n }\n \n private func backgroundColor(for entry: HumanEntry) -> Color {\n if entry.id == selectedEntryId {\n return Color.gray.opacity(0.1) // More subtle selection highlight\n } else if entry.id == hoveredEntryId {\n return Color.gray.opacity(0.05) // Even more subtle hover state\n } else {\n return Color.clear\n }\n }\n \n private func updatePreviewText(for entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Find and update the entry in the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries[index].previewText = truncated\n }\n } catch {\n print(\"Error updating preview text: \\(error)\")\n }\n }\n \n private func saveEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved entry: \\(entry.filename)\")\n updatePreviewText(for: entry) // Update preview after saving\n } catch {\n print(\"Error saving entry: \\(error)\")\n }\n }\n \n ", "suffix_code": "\n \n private func createNewEntry() {\n let newEntry = HumanEntry.createNew()\n entries.insert(newEntry, at: 0) // Add to the beginning\n selectedEntryId = newEntry.id\n \n // If this is the first entry (entries was empty before adding this one)\n if entries.count == 1 {\n // Read welcome message from default.md\n if let defaultMessageURL = Bundle.main.url(forResource: \"default\", withExtension: \"md\"),\n let defaultMessage = try? String(contentsOf: defaultMessageURL, encoding: .utf8) {\n text = \"\\n\\n\" + defaultMessage\n }\n // Save the welcome message immediately\n saveEntry(entry: newEntry)\n // Update the preview text\n updatePreviewText(for: newEntry)\n } else {\n // Regular new entry starts with newlines\n text = \"\\n\\n\"\n // Randomize placeholder text for new entry\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Save the empty entry\n saveEntry(entry: newEntry)\n }\n }\n \n private func openChatGPT() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://chat.openai.com/?m=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n \n private func openClaude() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = claudePrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://claude.ai/new?q=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n\n private func copyPromptToClipboard() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n\n let pasteboard = NSPasteboard.general\n pasteboard.clearContents()\n pasteboard.setString(fullText, forType: .string)\n print(\"Prompt copied to clipboard\")\n }\n \n private func deleteEntry(entry: HumanEntry) {\n // Delete the file from the filesystem\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try fileManager.removeItem(at: fileURL)\n print(\"Successfully deleted file: \\(entry.filename)\")\n \n // Remove the entry from the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries.remove(at: index)\n \n // If the deleted entry was selected, select the first entry or create a new one\n if selectedEntryId == entry.id {\n if let firstEntry = entries.first {\n selectedEntryId = firstEntry.id\n loadEntry(entry: firstEntry)\n } else {\n createNewEntry()\n }\n }\n }\n } catch {\n print(\"Error deleting file: \\(error)\")\n }\n }\n \n // Extract a title from entry content for PDF export\n private func extractTitleFromContent(_ content: String, date: String) -> String {\n // Clean up content by removing leading/trailing whitespace and newlines\n let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // If content is empty, just use the date\n if trimmedContent.isEmpty {\n return \"Entry \\(date)\"\n }\n \n // Split content into words, ignoring newlines and removing punctuation\n let words = trimmedContent\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .components(separatedBy: .whitespaces)\n .filter { !$0.isEmpty }\n .map { word in\n word.trimmingCharacters(in: CharacterSet(charactersIn: \".,!?;:\\\"'()[]{}<>\"))\n .lowercased()\n }\n .filter { !$0.isEmpty }\n \n // If we have at least 4 words, use them\n if words.count >= 4 {\n return \"\\(words[0])-\\(words[1])-\\(words[2])-\\(words[3])\"\n }\n \n // If we have fewer than 4 words, use what we have\n if !words.isEmpty {\n return words.joined(separator: \"-\")\n }\n \n // Fallback to date if no words found\n return \"Entry \\(date)\"\n }\n \n private func exportEntryAsPDF(entry: HumanEntry) {\n // First make sure the current entry is saved\n if selectedEntryId == entry.id {\n saveEntry(entry: entry)\n }\n \n // Get entry content\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n // Read the content of the entry\n let entryContent = try String(contentsOf: fileURL, encoding: .utf8)\n \n // Extract a title from the entry content and add .pdf extension\n let suggestedFilename = extractTitleFromContent(entryContent, date: entry.date) + \".pdf\"\n \n // Create save panel\n let savePanel = NSSavePanel()\n savePanel.allowedContentTypes = [UTType.pdf]\n savePanel.nameFieldStringValue = suggestedFilename\n savePanel.isExtensionHidden = false // Make sure extension is visible\n \n // Show save dialog\n if savePanel.runModal() == .OK, let url = savePanel.url {\n // Create PDF data\n if let pdfData = createPDFFromText(text: entryContent) {\n try pdfData.write(to: url)\n print(\"Successfully exported PDF to: \\(url.path)\")\n }\n }\n } catch {\n print(\"Error in PDF export: \\(error)\")\n }\n }\n \n private func createPDFFromText(text: String) -> Data? {\n // Letter size page dimensions\n let pageWidth: CGFloat = 612.0 // 8.5 x 72\n let pageHeight: CGFloat = 792.0 // 11 x 72\n let margin: CGFloat = 72.0 // 1-inch margins\n \n // Calculate content area\n let contentRect = CGRect(\n x: margin,\n y: margin,\n width: pageWidth - (margin * 2),\n height: pageHeight - (margin * 2)\n )\n \n // Create PDF data container\n let pdfData = NSMutableData()\n \n // Configure text formatting attributes\n let paragraphStyle = NSMutableParagraphStyle()\n paragraphStyle.lineSpacing = lineHeight\n \n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let textAttributes: [NSAttributedString.Key: Any] = [\n .font: font,\n .foregroundColor: NSColor(red: 0.20, green: 0.20, blue: 0.20, alpha: 1.0),\n .paragraphStyle: paragraphStyle\n ]\n \n // Trim the initial newlines before creating the PDF\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Create the attributed string with formatting\n let attributedString = NSAttributedString(string: trimmedText, attributes: textAttributes)\n \n // Create a Core Text framesetter for text layout\n let framesetter = CTFramesetterCreateWithAttributedString(attributedString)\n \n // Create a PDF context with the data consumer\n guard let pdfContext = CGContext(consumer: CGDataConsumer(data: pdfData as CFMutableData)!, mediaBox: nil, nil) else {\n print(\"Failed to create PDF context\")\n return nil\n }\n \n // Track position within text\n var currentRange = CFRange(location: 0, length: 0)\n var pageIndex = 0\n \n // Create a path for the text frame\n let framePath = CGMutablePath()\n framePath.addRect(contentRect)\n \n // Continue creating pages until all text is processed\n while currentRange.location < attributedString.length {\n // Begin a new PDF page\n pdfContext.beginPage(mediaBox: nil)\n \n // Fill the page with white background\n pdfContext.setFillColor(NSColor.white.cgColor)\n pdfContext.fill(CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight))\n \n // Create a frame for this page's text\n let frame = CTFramesetterCreateFrame(\n framesetter, \n currentRange, \n framePath, \n nil\n )\n \n // Draw the text frame\n CTFrameDraw(frame, pdfContext)\n \n // Get the range of text that was actually displayed in this frame\n let visibleRange = CTFrameGetVisibleStringRange(frame)\n \n // Move to the next block of text for the next page\n currentRange.location += visibleRange.length\n \n // Finish the page\n pdfContext.endPage()\n pageIndex += 1\n \n // Safety check - don't allow infinite loops\n if pageIndex > 1000 {\n print(\"Safety limit reached - stopping PDF generation\")\n break\n }\n }\n \n // Finalize the PDF document\n pdfContext.closePDF()\n \n return pdfData as Data\n }\n}\n\n// Helper function to calculate line height\nfunc getLineHeight(font: NSFont) -> CGFloat {\n return font.ascender - font.descender + font.leading\n}\n\n// Add helper extension to find NSTextView\nextension NSView {\n func findTextView() -> NSView? {\n if self is NSTextView {\n return self\n }\n for subview in subviews {\n if let textView = subview.findTextView() {\n return textView\n }\n }\n return nil\n }\n}\n\n// Add helper extension for finding subviews of a specific type\nextension NSView {\n func findSubview<T: NSView>(ofType type: T.Type) -> T? {\n if let typedSelf = self as? T {\n return typedSelf\n }\n for subview in subviews {\n if let found = subview.findSubview(ofType: type) {\n return found\n }\n }\n return nil\n }\n}\n\n#Preview {\n ContentView()\n}\n", "middle_code": "private func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded entry: \\(entry.filename)\")\n }\n } catch {\n print(\"Error loading entry: \\(error)\")\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/freewrite/freewrite/freewriteApp.swift", "//\n// freewriteApp.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\n\n@main\nstruct freewriteApp: App {\n @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n @AppStorage(\"colorScheme\") private var colorSchemeString: String = \"light\"\n \n init() {\n // Register Lato font\n if let fontURL = Bundle.main.url(forResource: \"Lato-Regular\", withExtension: \"ttf\") {\n CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, nil)\n }\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .toolbar(.hidden, for: .windowToolbar)\n .preferredColorScheme(colorSchemeString == \"dark\" ? .dark : .light)\n }\n .windowStyle(.hiddenTitleBar)\n .defaultSize(width: 1100, height: 600)\n .windowToolbarStyle(.unifiedCompact)\n .windowResizability(.contentSize)\n }\n}\n\n// Add AppDelegate to handle window configuration\nclass AppDelegate: NSObject, NSApplicationDelegate {\n func applicationDidFinishLaunching(_ notification: Notification) {\n if let window = NSApplication.shared.windows.first {\n // Ensure window starts in windowed mode\n if window.styleMask.contains(.fullScreen) {\n window.toggleFullScreen(nil)\n }\n \n // Center the window on the screen\n window.center()\n }\n }\n} \n"]], "task_instance_info": {"created_time": "2025-08-21 03:24:27", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func loadEntry ( entry: HumanEntry ) { }", "code_description": "This code segment functions to: Retrieve stored textual content from persistent storage based on a provided record identifier and populate the application's primary text buffer for user interaction."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n text = content\n print(\"Successfully loaded entry: \\(entry.filename)\")\n } catch {\n print(\"Error loading entry: \\(error)\")\n text = \"\\n\\n\" // Fallback to empty text with required newlines\n }\n \n // Update preview text in entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n let preview = text\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n entries[index].previewText = truncated\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-24-53"}, "editdistance_info": {"edit_distance": 30.0, "calculate_time": "2025-08-21 03:24:53", "true_code_clean": "private func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded entry: \\(entry.filename)\")\n }\n } catch {\n print(\"Error loading entry: \\(error)\")\n }\n }", "predict_code_clean": "private func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n text = content\n print(\"Successfully loaded entry: \\(entry.filename)\")\n } catch {\n print(\"Error loading entry: \\(error)\")\n text = \"\\n\\n\" \n }\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n let preview = text\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n entries[index].previewText = truncated\n }\n}"}} | |
| {"repo_name": "freewrite", "file_name": "/freewrite/freewrite/ContentView.swift", "inference_info": {"prefix_code": "// Swift 5.0\n//\n// ContentView.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\nimport AppKit\nimport UniformTypeIdentifiers\nimport PDFKit\n\nstruct HumanEntry: Identifiable {\n let id: UUID\n let date: String\n let filename: String\n var previewText: String\n \n static func createNew() -> HumanEntry {\n let id = UUID()\n let now = Date()\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n let dateString = dateFormatter.string(from: now)\n \n // For display\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: now)\n \n return HumanEntry(\n id: id,\n date: displayDate,\n filename: \"[\\(id)]-[\\(dateString)].md\",\n previewText: \"\"\n )\n }\n}\n\nstruct HeartEmoji: Identifiable {\n let id = UUID()\n var position: CGPoint\n var offset: CGFloat = 0\n}\n\nstruct ContentView: View {\n private let headerString = \"\\n\\n\"\n @State private var entries: [HumanEntry] = []\n @State private var text: String = \"\" // Remove initial welcome text since we'll handle it in createNewEntry\n \n @State private var isFullscreen = false\n @State private var selectedFont: String = \"Lato-Regular\"\n @State private var currentRandomFont: String = \"\"\n @State private var timeRemaining: Int = 900 // Changed to 900 seconds (15 minutes)\n @State private var timerIsRunning = false\n @State private var isHoveringTimer = false\n @State private var isHoveringFullscreen = false\n @State private var hoveredFont: String? = nil\n @State private var isHoveringSize = false\n @State private var fontSize: CGFloat = 18\n @State private var blinkCount = 0\n @State private var isBlinking = false\n @State private var opacity: Double = 1.0\n @State private var shouldShowGray = true // New state to control color\n @State private var lastClickTime: Date? = nil\n @State private var bottomNavOpacity: Double = 1.0\n @State private var isHoveringBottomNav = false\n @State private var selectedEntryIndex: Int = 0\n @State private var scrollOffset: CGFloat = 0\n @State private var selectedEntryId: UUID? = nil\n @State private var hoveredEntryId: UUID? = nil\n @State private var isHoveringChat = false // Add this state variable\n @State private var showingChatMenu = false\n @State private var chatMenuAnchor: CGPoint = .zero\n @State private var showingSidebar = false // Add this state variable\n @State private var hoveredTrashId: UUID? = nil\n @State private var hoveredExportId: UUID? = nil\n @State private var placeholderText: String = \"\" // Add this line\n @State private var isHoveringNewEntry = false\n @State private var isHoveringClock = false\n @State private var isHoveringHistory = false\n @State private var isHoveringHistoryText = false\n @State private var isHoveringHistoryPath = false\n @State private var isHoveringHistoryArrow = false\n @State private var colorScheme: ColorScheme = .light // Add state for color scheme\n @State private var isHoveringThemeToggle = false // Add state for theme toggle hover\n @State private var didCopyPrompt: Bool = false // Add state for copy prompt feedback\n let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()\n let entryHeight: CGFloat = 40\n \n let availableFonts = NSFontManager.shared.availableFontFamilies\n let standardFonts = [\"Lato-Regular\", \"Arial\", \".AppleSystemUIFont\", \"Times New Roman\"]\n let fontSizes: [CGFloat] = [16, 18, 20, 22, 24, 26]\n let placeholderOptions = [\n \"\\n\\nBegin writing\",\n \"\\n\\nPick a thought and go\",\n \"\\n\\nStart typing\",\n \"\\n\\nWhat's on your mind\",\n \"\\n\\nJust start\",\n \"\\n\\nType your first thought\",\n \"\\n\\nStart with one sentence\",\n \"\\n\\nJust say it\"\n ]\n \n // Add file manager and save timer\n private let fileManager = FileManager.default\n private let saveTimer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()\n \n // Add cached documents directory\n private let documentsDirectory: URL = {\n let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(\"Freewrite\")\n \n // Create Freewrite directory if it doesn't exist\n if !FileManager.default.fileExists(atPath: directory.path) {\n do {\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n print(\"Successfully created Freewrite directory\")\n } catch {\n print(\"Error creating directory: \\(error)\")\n }\n }\n \n return directory\n }()\n \n // Add shared prompt constant\n private let aiChatPrompt = \"\"\"\n below is my journal entry. wyt? talk through it with me like a friend. don't therpaize me and give me a whole breakdown, don't repeat my thoughts with headings. really take all of this, and tell me back stuff truly as if you're an old homie.\n \n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n\n do not just go through every single thing i say, and say it back to me. you need to proccess everythikng is say, make connections i don't see it, and deliver it all back to me as a story that makes me feel what you think i wanna feel. thats what the best therapists do.\n\n ideally, you're style/tone should sound like the user themselves. it's as if the user is hearing their own tone but it should still feel different, because you have different things to say and don't just repeat back they say.\n\n else, start by saying, \"hey, thanks for showing me this. my thoughts:\"\n \n my entry:\n \"\"\"\n \n private let claudePrompt = \"\"\"\n Take a look at my journal entry below. I'd like you to analyze it and respond with deep insight that feels personal, not clinical.\n Imagine you're not just a friend, but a mentor who truly gets both my tech background and my psychological patterns. I want you to uncover the deeper meaning and emotional undercurrents behind my scattered thoughts.\n Keep it casual, dont say yo, help me make new connections i don't see, comfort, validate, challenge, all of it. dont be afraid to say a lot. format with markdown headings if needed.\n Use vivid metaphors and powerful imagery to help me see what I'm really building. Organize your thoughts with meaningful headings that create a narrative journey through my ideas.\n Don't just validate my thoughts - reframe them in a way that shows me what I'm really seeking beneath the surface. Go beyond the product concepts to the emotional core of what I'm trying to solve.\n Be willing to be profound and philosophical without sounding like you're giving therapy. I want someone who can see the patterns I can't see myself and articulate them in a way that feels like an epiphany.\n Start with 'hey, thanks for showing me this. my thoughts:' and then use markdown headings to structure your response.\n\n Here's my journal entry:\n \"\"\"\n \n // Initialize with saved theme preference if available\n init() {\n // Load saved color scheme preference\n let savedScheme = UserDefaults.standard.string(forKey: \"colorScheme\") ?? \"light\"\n _colorScheme = State(initialValue: savedScheme == \"dark\" ? .dark : .light)\n }\n \n // Modify getDocumentsDirectory to use cached value\n private func getDocumentsDirectory() -> URL {\n return documentsDirectory\n }\n \n // Add function to save text\n private func saveText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n print(\"Attempting to save file to: \\(fileURL.path)\")\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved file\")\n } catch {\n print(\"Error saving file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }\n \n // Add function to load text\n private func loadText() {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(\"entry.md\")\n \n print(\"Attempting to load file from: \\(fileURL.path)\")\n \n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded file\")\n } else {\n print(\"File does not exist yet\")\n }\n } catch {\n print(\"Error loading file: \\(error)\")\n print(\"Error details: \\(error.localizedDescription)\")\n }\n }\n \n // Add function to load existing entries\n private func loadExistingEntries() {\n let documentsDirectory = getDocumentsDirectory()\n print(\"Looking for entries in: \\(documentsDirectory.path)\")\n \n do {\n let fileURLs = try fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)\n let mdFiles = fileURLs.filter { $0.pathExtension == \"md\" }\n \n print(\"Found \\(mdFiles.count) .md files\")\n \n // Process each file\n let entriesWithDates = mdFiles.compactMap { fileURL -> (entry: HumanEntry, date: Date, content: String)? in\n let filename = fileURL.lastPathComponent\n print(\"Processing: \\(filename)\")\n \n // Extract UUID and date from filename - pattern [uuid]-[yyyy-MM-dd-HH-mm-ss].md\n guard let uuidMatch = filename.range(of: \"\\\\[(.*?)\\\\]\", options: .regularExpression),\n let dateMatch = filename.range(of: \"\\\\[(\\\\d{4}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2}-\\\\d{2})\\\\]\", options: .regularExpression),\n let uuid = UUID(uuidString: String(filename[uuidMatch].dropFirst().dropLast())) else {\n print(\"Failed to extract UUID or date from filename: \\(filename)\")\n return nil\n }\n \n // Parse the date string\n let dateString = String(filename[dateMatch].dropFirst().dropLast())\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd-HH-mm-ss\"\n \n guard let fileDate = dateFormatter.date(from: dateString) else {\n print(\"Failed to parse date from filename: \\(filename)\")\n return nil\n }\n \n // Read file contents for preview\n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Format display date\n dateFormatter.dateFormat = \"MMM d\"\n let displayDate = dateFormatter.string(from: fileDate)\n \n return (\n entry: HumanEntry(\n id: uuid,\n date: displayDate,\n filename: filename,\n previewText: truncated\n ),\n date: fileDate,\n content: content // Store the full content to check for welcome message\n )\n } catch {\n print(\"Error reading file: \\(error)\")\n return nil\n }\n }\n \n // Sort and extract entries\n entries = entriesWithDates\n .sorted { $0.date > $1.date } // Sort by actual date from filename\n .map { $0.entry }\n \n print(\"Successfully loaded and sorted \\(entries.count) entries\")\n \n // Check if we need to create a new entry\n let calendar = Calendar.current\n let today = Date()\n let todayStart = calendar.startOfDay(for: today)\n \n // Check if there's an empty entry from today\n let hasEmptyEntryToday = entries.contains { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }\n \n // Check if we have only one entry and it's the welcome message\n let hasOnlyWelcomeEntry = entries.count == 1 && entriesWithDates.first?.content.contains(\"Welcome to Freewrite.\") == true\n \n if entries.isEmpty {\n // First time user - create entry with welcome message\n print(\"First time user, creating welcome entry\")\n createNewEntry()\n } else if !hasEmptyEntryToday && !hasOnlyWelcomeEntry {\n // No empty entry for today and not just the welcome entry - create new entry\n print(\"No empty entry for today, creating new entry\")\n createNewEntry()\n } else {\n // Select the most recent empty entry from today or the welcome entry\n if let todayEntry = entries.first(where: { entry in\n // Convert the display date (e.g. \"Mar 14\") to a Date object\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"MMM d\"\n if let entryDate = dateFormatter.date(from: entry.date) {\n // Set year component to current year since our stored dates don't include year\n var components = calendar.dateComponents([.year, .month, .day], from: entryDate)\n components.year = calendar.component(.year, from: today)\n \n // Get start of day for the entry date\n if let entryDateWithYear = calendar.date(from: components) {\n let entryDayStart = calendar.startOfDay(for: entryDateWithYear)\n return calendar.isDate(entryDayStart, inSameDayAs: todayStart) && entry.previewText.isEmpty\n }\n }\n return false\n }) {\n selectedEntryId = todayEntry.id\n loadEntry(entry: todayEntry)\n } else if hasOnlyWelcomeEntry {\n // If we only have the welcome entry, select it\n selectedEntryId = entries[0].id\n loadEntry(entry: entries[0])\n }\n }\n \n } catch {\n print(\"Error loading directory contents: \\(error)\")\n print(\"Creating default entry after error\")\n createNewEntry()\n }\n }\n \n var randomButtonTitle: String {\n return currentRandomFont.isEmpty ? \"Random\" : \"Random [\\(currentRandomFont)]\"\n }\n \n var timerButtonTitle: String {\n if !timerIsRunning && timeRemaining == 900 {\n return \"15:00\"\n }\n let minutes = timeRemaining / 60\n let seconds = timeRemaining % 60\n return String(format: \"%d:%02d\", minutes, seconds)\n }\n \n var timerColor: Color {\n if timerIsRunning {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : .gray.opacity(0.8)\n } else {\n return isHoveringTimer ? (colorScheme == .light ? .black : .white) : (colorScheme == .light ? .gray : .gray.opacity(0.8))\n }\n }\n \n var lineHeight: CGFloat {\n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let defaultLineHeight = getLineHeight(font: font)\n return (fontSize * 1.5) - defaultLineHeight\n }\n \n var fontSizeButtonTitle: String {\n return \"\\(Int(fontSize))px\"\n }\n \n var placeholderOffset: CGFloat {\n // Instead of using calculated line height, use a simple offset\n return fontSize / 2\n }\n \n // Add a color utility computed property\n var popoverBackgroundColor: Color {\n return colorScheme == .light ? Color(NSColor.controlBackgroundColor) : Color(NSColor.darkGray)\n }\n \n var popoverTextColor: Color {\n return colorScheme == .light ? Color.primary : Color.white\n }\n \n @State private var viewHeight: CGFloat = 0\n \n var body: some View {\n let buttonBackground = colorScheme == .light ? Color.white : Color.black\n let navHeight: CGFloat = 68\n let textColor = colorScheme == .light ? Color.gray : Color.gray.opacity(0.8)\n let textHoverColor = colorScheme == .light ? Color.black : Color.white\n \n HStack(spacing: 0) {\n // Main content\n ZStack {\n Color(colorScheme == .light ? .white : .black)\n .ignoresSafeArea()\n \n \n TextEditor(text: Binding(\n get: { text },\n set: { newValue in\n // Ensure the text always starts with two newlines\n if !newValue.hasPrefix(\"\\n\\n\") {\n text = \"\\n\\n\" + newValue.trimmingCharacters(in: .newlines)\n } else {\n text = newValue\n }\n }\n ))\n .background(Color(colorScheme == .light ? .white : .black))\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? Color(red: 0.20, green: 0.20, blue: 0.20) : Color(red: 0.9, green: 0.9, blue: 0.9))\n .scrollContentBackground(.hidden)\n .scrollIndicators(.never)\n .lineSpacing(lineHeight)\n .frame(maxWidth: 650)\n \n \n .id(\"\\(selectedFont)-\\(fontSize)-\\(colorScheme)\")\n .padding(.bottom, bottomNavOpacity > 0 ? navHeight : 0)\n .ignoresSafeArea()\n .colorScheme(colorScheme)\n .onAppear {\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Removed findSubview code which was causing errors\n }\n .overlay(\n ZStack(alignment: .topLeading) {\n if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n Text(placeholderText)\n .font(.custom(selectedFont, size: fontSize))\n .foregroundColor(colorScheme == .light ? .gray.opacity(0.5) : .gray.opacity(0.6))\n // .padding(.top, 8)\n // .padding(.leading, 8)\n .allowsHitTesting(false)\n .offset(x: 5, y: placeholderOffset)\n }\n }, alignment: .topLeading\n )\n .onGeometryChange(for: CGFloat.self) { proxy in\n proxy.size.height\n } action: { height in\n viewHeight = height\n }\n .contentMargins(.bottom, viewHeight / 4)\n \n \n VStack {\n Spacer()\n HStack {\n // Font buttons (moved to left)\n HStack(spacing: 8) {\n Button(fontSizeButtonTitle) {\n if let currentIndex = fontSizes.firstIndex(of: fontSize) {\n let nextIndex = (currentIndex + 1) % fontSizes.count\n fontSize = fontSizes[nextIndex]\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringSize ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringSize = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Lato\") {\n selectedFont = \"Lato-Regular\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Lato\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Lato\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Arial\") {\n selectedFont = \"Arial\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Arial\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Arial\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"System\") {\n selectedFont = \".AppleSystemUIFont\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"System\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"System\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Serif\") {\n selectedFont = \"Times New Roman\"\n currentRandomFont = \"\"\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Serif\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Serif\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(randomButtonTitle) {\n if let randomFont = availableFonts.randomElement() {\n selectedFont = randomFont\n currentRandomFont = randomFont\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(hoveredFont == \"Random\" ? textHoverColor : textColor)\n .onHover { hovering in\n hoveredFont = hovering ? \"Random\" : nil\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n \n Spacer()\n \n // Utility buttons (moved to right)\n HStack(spacing: 8) {\n Button(timerButtonTitle) {\n let now = Date()\n if let lastClick = lastClickTime,\n now.timeIntervalSince(lastClick) < 0.3 {\n timeRemaining = 900\n timerIsRunning = false\n lastClickTime = nil\n } else {\n timerIsRunning.toggle()\n lastClickTime = now\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(timerColor)\n .onHover { hovering in\n isHoveringTimer = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .onAppear {\n NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in\n if isHoveringTimer {\n let scrollBuffer = event.deltaY * 0.25\n \n if abs(scrollBuffer) >= 0.1 {\n let currentMinutes = timeRemaining / 60\n NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now)\n let direction = -scrollBuffer > 0 ? 5 : -5\n let newMinutes = currentMinutes + direction\n let roundedMinutes = (newMinutes / 5) * 5\n let newTime = roundedMinutes * 60\n timeRemaining = min(max(newTime, 0), 2700)\n }\n }\n return event\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(\"Chat\") {\n showingChatMenu = true\n // Ensure didCopyPrompt is reset when opening the menu\n didCopyPrompt = false\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringChat ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringChat = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n .popover(isPresented: $showingChatMenu, attachmentAnchor: .point(UnitPoint(x: 0.5, y: 0)), arrowEdge: .top) {\n VStack(spacing: 0) { // Wrap everything in a VStack for consistent styling and onChange\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Calculate potential URL lengths\n let gptFullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n let claudeFullText = claudePrompt + \"\\n\\n\" + trimmedText\n let encodedGptText = gptFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n let encodedClaudeText = claudeFullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? \"\"\n \n let gptUrlLength = \"https://chat.openai.com/?m=\".count + encodedGptText.count\n let claudeUrlLength = \"https://claude.ai/new?q=\".count + encodedClaudeText.count\n let isUrlTooLong = gptUrlLength > 6000 || claudeUrlLength > 6000\n \n if isUrlTooLong {\n // View for long text (URL too long)\n Text(\"Hey, your entry is long. It'll break the URL. Instead, copy prompt by clicking below and paste into AI of your choice!\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .lineLimit(nil)\n .multilineTextAlignment(.leading)\n .frame(width: 200, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n \n Divider()\n \n Button(action: {\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n } else if text.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix(\"hi. my name is farza.\") {\n Text(\"Yo. Sorry, you can't chat with the guide lol. Please write your own entry.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else if text.count < 350 {\n Text(\"Please free write for at minimum 5 minutes first. Then click this. Trust.\")\n .font(.system(size: 14))\n .foregroundColor(popoverTextColor)\n .frame(width: 250)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n } else {\n // View for normal text length\n Button(action: {\n showingChatMenu = false\n openChatGPT()\n }) {\n Text(\"ChatGPT\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n showingChatMenu = false\n openClaude()\n }) {\n Text(\"Claude\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Divider()\n \n Button(action: {\n // Don't dismiss menu, just copy and update state\n copyPromptToClipboard()\n didCopyPrompt = true\n }) {\n Text(didCopyPrompt ? \"Copied!\" : \"Copy Prompt\")\n .frame(maxWidth: .infinity, alignment: .leading)\n .padding(.horizontal, 12)\n .padding(.vertical, 8)\n }\n .buttonStyle(.plain)\n .foregroundColor(popoverTextColor)\n .onHover { hovering in\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n .frame(minWidth: 120, maxWidth: 250) // Allow width to adjust\n .background(popoverBackgroundColor)\n .cornerRadius(8)\n .shadow(color: Color.black.opacity(0.1), radius: 4, y: 2)\n // Reset copied state when popover dismisses\n .onChange(of: showingChatMenu) { newValue in\n if !newValue {\n didCopyPrompt = false\n }\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(isFullscreen ? \"Minimize\" : \"Fullscreen\") {\n if let window = NSApplication.shared.windows.first {\n window.toggleFullScreen(nil)\n }\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringFullscreen ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringFullscreen = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n Button(action: {\n createNewEntry()\n }) {\n Text(\"New Entry\")\n .font(.system(size: 13))\n }\n .buttonStyle(.plain)\n .foregroundColor(isHoveringNewEntry ? textHoverColor : textColor)\n .onHover { hovering in\n isHoveringNewEntry = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n Text(\"•\")\n .foregroundColor(.gray)\n \n // Theme toggle button\n Button(action: {\n colorScheme = colorScheme == .light ? .dark : .light\n // Save preference\n UserDefaults.standard.set(colorScheme == .light ? \"light\" : \"dark\", forKey: \"colorScheme\")\n }) {\n Image(systemName: colorScheme == .light ? \"moon.fill\" : \"sun.max.fill\")\n .foregroundColor(isHoveringThemeToggle ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringThemeToggle = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n\n Text(\"•\")\n .foregroundColor(.gray)\n \n // Version history button\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showingSidebar.toggle()\n }\n }) {\n Image(systemName: \"clock.arrow.circlepath\")\n .foregroundColor(isHoveringClock ? textHoverColor : textColor)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n isHoveringClock = hovering\n isHoveringBottomNav = hovering\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n .padding(8)\n .cornerRadius(6)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n }\n }\n .padding()\n .background(Color(colorScheme == .light ? .white : .black))\n .opacity(bottomNavOpacity)\n .onHover { hovering in\n isHoveringBottomNav = hovering\n if hovering {\n withAnimation(.easeOut(duration: 0.2)) {\n bottomNavOpacity = 1.0\n }\n } else if timerIsRunning {\n withAnimation(.easeIn(duration: 1.0)) {\n bottomNavOpacity = 0.0\n }\n }\n }\n }\n }\n \n // Right sidebar\n if showingSidebar {\n Divider()\n \n VStack(spacing: 0) {\n // Header\n Button(action: {\n NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: getDocumentsDirectory().path)\n }) {\n HStack {\n VStack(alignment: .leading, spacing: 4) {\n HStack(spacing: 4) {\n Text(\"History\")\n .font(.system(size: 13))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n Image(systemName: \"arrow.up.right\")\n .font(.system(size: 10))\n .foregroundColor(isHoveringHistory ? textHoverColor : textColor)\n }\n Text(getDocumentsDirectory().path)\n .font(.system(size: 10))\n .foregroundColor(.secondary)\n .lineLimit(1)\n }\n Spacer()\n }\n }\n .buttonStyle(.plain)\n .padding(.horizontal, 16)\n .padding(.vertical, 12)\n .onHover { hovering in\n isHoveringHistory = hovering\n }\n \n Divider()\n \n // Entries List\n ScrollView {\n LazyVStack(spacing: 0) {\n ForEach(entries) { entry in\n Button(action: {\n if selectedEntryId != entry.id {\n // Save current entry before switching\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n \n selectedEntryId = entry.id\n loadEntry(entry: entry)\n }\n }) {\n HStack(alignment: .top) {\n VStack(alignment: .leading, spacing: 4) {\n HStack {\n Text(entry.previewText)\n .font(.system(size: 13))\n .lineLimit(1)\n .foregroundColor(.primary)\n \n Spacer()\n \n // Export/Trash icons that appear on hover\n if hoveredEntryId == entry.id {\n HStack(spacing: 8) {\n // Export PDF button\n Button(action: {\n exportEntryAsPDF(entry: entry)\n }) {\n Image(systemName: \"arrow.down.circle\")\n .font(.system(size: 11))\n .foregroundColor(hoveredExportId == entry.id ? \n (colorScheme == .light ? .black : .white) : \n (colorScheme == .light ? .gray : .gray.opacity(0.8)))\n }\n .buttonStyle(.plain)\n .help(\"Export entry as PDF\")\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredExportId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n \n // Trash icon\n Button(action: {\n deleteEntry(entry: entry)\n }) {\n Image(systemName: \"trash\")\n .font(.system(size: 11))\n .foregroundColor(hoveredTrashId == entry.id ? .red : .gray)\n }\n .buttonStyle(.plain)\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredTrashId = hovering ? entry.id : nil\n }\n if hovering {\n NSCursor.pointingHand.push()\n } else {\n NSCursor.pop()\n }\n }\n }\n }\n }\n \n Text(entry.date)\n .font(.system(size: 12))\n .foregroundColor(.secondary)\n }\n }\n .frame(maxWidth: .infinity)\n .padding(.horizontal, 16)\n .padding(.vertical, 8)\n .background(\n RoundedRectangle(cornerRadius: 4)\n .fill(backgroundColor(for: entry))\n )\n }\n .buttonStyle(PlainButtonStyle())\n .contentShape(Rectangle())\n .onHover { hovering in\n withAnimation(.easeInOut(duration: 0.2)) {\n hoveredEntryId = hovering ? entry.id : nil\n }\n }\n .onAppear {\n NSCursor.pop() // Reset cursor when button appears\n }\n .help(\"Click to select this entry\") // Add tooltip\n \n if entry.id != entries.last?.id {\n Divider()\n }\n }\n }\n }\n .scrollIndicators(.never)\n }\n .frame(width: 200)\n .background(Color(colorScheme == .light ? .white : NSColor.black))\n }\n }\n .frame(minWidth: 1100, minHeight: 600)\n .animation(.easeInOut(duration: 0.2), value: showingSidebar)\n .preferredColorScheme(colorScheme)\n .onAppear {\n showingSidebar = false // Hide sidebar by default\n loadExistingEntries()\n }\n .onChange(of: text) { _ in\n // Save current entry when text changes\n if let currentId = selectedEntryId,\n let currentEntry = entries.first(where: { $0.id == currentId }) {\n saveEntry(entry: currentEntry)\n }\n }\n .onReceive(timer) { _ in\n if timerIsRunning && timeRemaining > 0 {\n timeRemaining -= 1\n } else if timeRemaining == 0 {\n timerIsRunning = false\n if !isHoveringBottomNav {\n withAnimation(.easeOut(duration: 1.0)) {\n bottomNavOpacity = 1.0\n }\n }\n }\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willEnterFullScreenNotification)) { _ in\n isFullscreen = true\n }\n .onReceive(NotificationCenter.default.publisher(for: NSWindow.willExitFullScreenNotification)) { _ in\n isFullscreen = false\n }\n }\n \n private func backgroundColor(for entry: HumanEntry) -> Color {\n if entry.id == selectedEntryId {\n return Color.gray.opacity(0.1) // More subtle selection highlight\n } else if entry.id == hoveredEntryId {\n return Color.gray.opacity(0.05) // Even more subtle hover state\n } else {\n return Color.clear\n }\n }\n \n private func updatePreviewText(for entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let preview = content\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .trimmingCharacters(in: .whitespacesAndNewlines)\n let truncated = preview.isEmpty ? \"\" : (preview.count > 30 ? String(preview.prefix(30)) + \"...\" : preview)\n \n // Find and update the entry in the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries[index].previewText = truncated\n }\n } catch {\n print(\"Error updating preview text: \\(error)\")\n }\n }\n \n private func saveEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try text.write(to: fileURL, atomically: true, encoding: .utf8)\n print(\"Successfully saved entry: \\(entry.filename)\")\n updatePreviewText(for: entry) // Update preview after saving\n } catch {\n print(\"Error saving entry: \\(error)\")\n }\n }\n \n private func loadEntry(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n if fileManager.fileExists(atPath: fileURL.path) {\n text = try String(contentsOf: fileURL, encoding: .utf8)\n print(\"Successfully loaded entry: \\(entry.filename)\")\n }\n } catch {\n print(\"Error loading entry: \\(error)\")\n }\n }\n \n private func createNewEntry() {\n let newEntry = HumanEntry.createNew()\n entries.insert(newEntry, at: 0) // Add to the beginning\n selectedEntryId = newEntry.id\n \n // If this is the first entry (entries was empty before adding this one)\n if entries.count == 1 {\n // Read welcome message from default.md\n if let defaultMessageURL = Bundle.main.url(forResource: \"default\", withExtension: \"md\"),\n let defaultMessage = try? String(contentsOf: defaultMessageURL, encoding: .utf8) {\n text = \"\\n\\n\" + defaultMessage\n }\n // Save the welcome message immediately\n saveEntry(entry: newEntry)\n // Update the preview text\n updatePreviewText(for: newEntry)\n } else {\n // Regular new entry starts with newlines\n text = \"\\n\\n\"\n // Randomize placeholder text for new entry\n placeholderText = placeholderOptions.randomElement() ?? \"\\n\\nBegin writing\"\n // Save the empty entry\n saveEntry(entry: newEntry)\n }\n }\n \n private func openChatGPT() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://chat.openai.com/?m=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n \n private func openClaude() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = claudePrompt + \"\\n\\n\" + trimmedText\n \n if let encodedText = fullText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),\n let url = URL(string: \"https://claude.ai/new?q=\" + encodedText) {\n NSWorkspace.shared.open(url)\n }\n }\n\n private func copyPromptToClipboard() {\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n let fullText = aiChatPrompt + \"\\n\\n\" + trimmedText\n\n let pasteboard = NSPasteboard.general\n pasteboard.clearContents()\n pasteboard.setString(fullText, forType: .string)\n print(\"Prompt copied to clipboard\")\n }\n \n private func deleteEntry(entry: HumanEntry) {\n // Delete the file from the filesystem\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n try fileManager.removeItem(at: fileURL)\n print(\"Successfully deleted file: \\(entry.filename)\")\n \n // Remove the entry from the entries array\n if let index = entries.firstIndex(where: { $0.id == entry.id }) {\n entries.remove(at: index)\n \n // If the deleted entry was selected, select the first entry or create a new one\n if selectedEntryId == entry.id {\n if let firstEntry = entries.first {\n selectedEntryId = firstEntry.id\n loadEntry(entry: firstEntry)\n } else {\n createNewEntry()\n }\n }\n }\n } catch {\n print(\"Error deleting file: \\(error)\")\n }\n }\n \n // Extract a title from entry content for PDF export\n private func extractTitleFromContent(_ content: String, date: String) -> String {\n // Clean up content by removing leading/trailing whitespace and newlines\n let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // If content is empty, just use the date\n if trimmedContent.isEmpty {\n return \"Entry \\(date)\"\n }\n \n // Split content into words, ignoring newlines and removing punctuation\n let words = trimmedContent\n .replacingOccurrences(of: \"\\n\", with: \" \")\n .components(separatedBy: .whitespaces)\n .filter { !$0.isEmpty }\n .map { word in\n word.trimmingCharacters(in: CharacterSet(charactersIn: \".,!?;:\\\"'()[]{}<>\"))\n .lowercased()\n }\n .filter { !$0.isEmpty }\n \n // If we have at least 4 words, use them\n if words.count >= 4 {\n return \"\\(words[0])-\\(words[1])-\\(words[2])-\\(words[3])\"\n }\n \n // If we have fewer than 4 words, use what we have\n if !words.isEmpty {\n return words.joined(separator: \"-\")\n }\n \n // Fallback to date if no words found\n return \"Entry \\(date)\"\n }\n \n ", "suffix_code": "\n \n private func createPDFFromText(text: String) -> Data? {\n // Letter size page dimensions\n let pageWidth: CGFloat = 612.0 // 8.5 x 72\n let pageHeight: CGFloat = 792.0 // 11 x 72\n let margin: CGFloat = 72.0 // 1-inch margins\n \n // Calculate content area\n let contentRect = CGRect(\n x: margin,\n y: margin,\n width: pageWidth - (margin * 2),\n height: pageHeight - (margin * 2)\n )\n \n // Create PDF data container\n let pdfData = NSMutableData()\n \n // Configure text formatting attributes\n let paragraphStyle = NSMutableParagraphStyle()\n paragraphStyle.lineSpacing = lineHeight\n \n let font = NSFont(name: selectedFont, size: fontSize) ?? .systemFont(ofSize: fontSize)\n let textAttributes: [NSAttributedString.Key: Any] = [\n .font: font,\n .foregroundColor: NSColor(red: 0.20, green: 0.20, blue: 0.20, alpha: 1.0),\n .paragraphStyle: paragraphStyle\n ]\n \n // Trim the initial newlines before creating the PDF\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Create the attributed string with formatting\n let attributedString = NSAttributedString(string: trimmedText, attributes: textAttributes)\n \n // Create a Core Text framesetter for text layout\n let framesetter = CTFramesetterCreateWithAttributedString(attributedString)\n \n // Create a PDF context with the data consumer\n guard let pdfContext = CGContext(consumer: CGDataConsumer(data: pdfData as CFMutableData)!, mediaBox: nil, nil) else {\n print(\"Failed to create PDF context\")\n return nil\n }\n \n // Track position within text\n var currentRange = CFRange(location: 0, length: 0)\n var pageIndex = 0\n \n // Create a path for the text frame\n let framePath = CGMutablePath()\n framePath.addRect(contentRect)\n \n // Continue creating pages until all text is processed\n while currentRange.location < attributedString.length {\n // Begin a new PDF page\n pdfContext.beginPage(mediaBox: nil)\n \n // Fill the page with white background\n pdfContext.setFillColor(NSColor.white.cgColor)\n pdfContext.fill(CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight))\n \n // Create a frame for this page's text\n let frame = CTFramesetterCreateFrame(\n framesetter, \n currentRange, \n framePath, \n nil\n )\n \n // Draw the text frame\n CTFrameDraw(frame, pdfContext)\n \n // Get the range of text that was actually displayed in this frame\n let visibleRange = CTFrameGetVisibleStringRange(frame)\n \n // Move to the next block of text for the next page\n currentRange.location += visibleRange.length\n \n // Finish the page\n pdfContext.endPage()\n pageIndex += 1\n \n // Safety check - don't allow infinite loops\n if pageIndex > 1000 {\n print(\"Safety limit reached - stopping PDF generation\")\n break\n }\n }\n \n // Finalize the PDF document\n pdfContext.closePDF()\n \n return pdfData as Data\n }\n}\n\n// Helper function to calculate line height\nfunc getLineHeight(font: NSFont) -> CGFloat {\n return font.ascender - font.descender + font.leading\n}\n\n// Add helper extension to find NSTextView\nextension NSView {\n func findTextView() -> NSView? {\n if self is NSTextView {\n return self\n }\n for subview in subviews {\n if let textView = subview.findTextView() {\n return textView\n }\n }\n return nil\n }\n}\n\n// Add helper extension for finding subviews of a specific type\nextension NSView {\n func findSubview<T: NSView>(ofType type: T.Type) -> T? {\n if let typedSelf = self as? T {\n return typedSelf\n }\n for subview in subviews {\n if let found = subview.findSubview(ofType: type) {\n return found\n }\n }\n return nil\n }\n}\n\n#Preview {\n ContentView()\n}\n", "middle_code": "private func exportEntryAsPDF(entry: HumanEntry) {\n if selectedEntryId == entry.id {\n saveEntry(entry: entry)\n }\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n let entryContent = try String(contentsOf: fileURL, encoding: .utf8)\n let suggestedFilename = extractTitleFromContent(entryContent, date: entry.date) + \".pdf\"\n let savePanel = NSSavePanel()\n savePanel.allowedContentTypes = [UTType.pdf]\n savePanel.nameFieldStringValue = suggestedFilename\n savePanel.isExtensionHidden = false \n if savePanel.runModal() == .OK, let url = savePanel.url {\n if let pdfData = createPDFFromText(text: entryContent) {\n try pdfData.write(to: url)\n print(\"Successfully exported PDF to: \\(url.path)\")\n }\n }\n } catch {\n print(\"Error in PDF export: \\(error)\")\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/freewrite/freewrite/freewriteApp.swift", "//\n// freewriteApp.swift\n// freewrite\n//\n// Created by thorfinn on 2/14/25.\n//\n\nimport SwiftUI\n\n@main\nstruct freewriteApp: App {\n @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n @AppStorage(\"colorScheme\") private var colorSchemeString: String = \"light\"\n \n init() {\n // Register Lato font\n if let fontURL = Bundle.main.url(forResource: \"Lato-Regular\", withExtension: \"ttf\") {\n CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, nil)\n }\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .toolbar(.hidden, for: .windowToolbar)\n .preferredColorScheme(colorSchemeString == \"dark\" ? .dark : .light)\n }\n .windowStyle(.hiddenTitleBar)\n .defaultSize(width: 1100, height: 600)\n .windowToolbarStyle(.unifiedCompact)\n .windowResizability(.contentSize)\n }\n}\n\n// Add AppDelegate to handle window configuration\nclass AppDelegate: NSObject, NSApplicationDelegate {\n func applicationDidFinishLaunching(_ notification: Notification) {\n if let window = NSApplication.shared.windows.first {\n // Ensure window starts in windowed mode\n if window.styleMask.contains(.fullScreen) {\n window.toggleFullScreen(nil)\n }\n \n // Center the window on the screen\n window.center()\n }\n }\n} \n"]], "task_instance_info": {"created_time": "2025-08-21 03:24:27", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func exportEntryAsPDF ( entry: HumanEntry ) { }", "code_description": "This code segment functions to: Export textual content into a PDF document format by processing user-selected save locations, applying consistent formatting parameters, and handling file system operations with error management. It transforms plain text input into paginated output while maintaining source formatting preferences and implements user interaction workflows for destination selection."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func exportEntryAsPDF(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n \n do {\n // Load entry content\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Check if content is empty\n guard !trimmedContent.isEmpty else {\n print(\"No content to export\")\n return\n }\n \n // Generate PDF data\n guard let pdfData = createPDFFromText(text: content) else {\n print(\"Failed to generate PDF data\")\n return\n }\n \n // Create output filename\n let title = extractTitleFromContent(content, date: entry.date)\n let pdfFilename = \"\\(title).pdf\"\n let pdfURL = documentsDirectory.appendingPathComponent(pdfFilename)\n \n // Save PDF file\n try pdfData.write(to: pdfURL)\n \n // Open in default viewer\n NSWorkspace.shared.open(pdfURL)\n \n } catch {\n print(\"Error exporting PDF: \\(error)\")\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-24-59"}, "editdistance_info": {"edit_distance": 29.9065, "calculate_time": "2025-08-21 03:24:59", "true_code_clean": "private func exportEntryAsPDF(entry: HumanEntry) {\n if selectedEntryId == entry.id {\n saveEntry(entry: entry)\n }\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n let entryContent = try String(contentsOf: fileURL, encoding: .utf8)\n let suggestedFilename = extractTitleFromContent(entryContent, date: entry.date) + \".pdf\"\n let savePanel = NSSavePanel()\n savePanel.allowedContentTypes = [UTType.pdf]\n savePanel.nameFieldStringValue = suggestedFilename\n savePanel.isExtensionHidden = false \n if savePanel.runModal() == .OK, let url = savePanel.url {\n if let pdfData = createPDFFromText(text: entryContent) {\n try pdfData.write(to: url)\n print(\"Successfully exported PDF to: \\(url.path)\")\n }\n }\n } catch {\n print(\"Error in PDF export: \\(error)\")\n }\n }", "predict_code_clean": "private func exportEntryAsPDF(entry: HumanEntry) {\n let documentsDirectory = getDocumentsDirectory()\n let fileURL = documentsDirectory.appendingPathComponent(entry.filename)\n do {\n let content = try String(contentsOf: fileURL, encoding: .utf8)\n let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)\n guard !trimmedContent.isEmpty else {\n print(\"No content to export\")\n return\n }\n guard let pdfData = createPDFFromText(text: content) else {\n print(\"Failed to generate PDF data\")\n return\n }\n let title = extractTitleFromContent(content, date: entry.date)\n let pdfFilename = \"\\(title).pdf\"\n let pdfURL = documentsDirectory.appendingPathComponent(pdfFilename)\n try pdfData.write(to: pdfURL)\n NSWorkspace.shared.open(pdfURL)\n } catch {\n print(\"Error exporting PDF: \\(error)\")\n }\n}"}} | |