# 🔧 Troubleshooting Guide

Having issues? This guide will help you fix common problems.

---

## 🚫 Build Errors

### Error: "Cannot find 'KeyboardShortcuts' in scope"

**What it means:** The external package isn't installed.

**Solution:**
1. Go to: **File → Add Package Dependencies...**
2. Paste URL: `https://github.com/sindresorhus/KeyboardShortcuts`
3. Click **"Add Package"** twice
4. Wait for download to complete
5. Clean build: **Product → Clean Build Folder** (Cmd+Shift+K)
6. Rebuild: **Product → Build** (Cmd+B)

---

### Error: "Multiple commands produce 'LangOverApp.swift'"

**What it means:** You have two main app files.

**Solution:**
1. Look for **"LangToLangApp.swift"** in the file list
2. Right-click it → **Delete** → **Move to Trash**
3. Keep only **"LangOverApp.swift"**
4. Rebuild

---

### Error: "No such module 'SwiftUI'"

**What it means:** Deployment target is too old.

**Solution:**
1. Click the **blue project icon** at the top of file list
2. In **General** tab, find **"Minimum Deployment"**
3. Change to: **macOS 13.0** or later
4. Rebuild

---

### Error: "Type 'SMAppService' has no member 'mainApp'"

**What it means:** You're targeting an older macOS version.

**Solution:**
1. In **General** tab, set **"Minimum Deployment"** to **macOS 13.0**
2. Or comment out the `startAtLogin` code in `Settings.swift` (lines 46-56)

---

### Error: "Missing Info.plist file"

**What it means:** Xcode can't find the configuration file.

**Solution:**
1. Make sure **Info.plist** is in the file list
2. Click on the **blue project icon** → **Build Settings** tab
3. Search for: **"Info.plist"**
4. Set path to: `Info.plist` (or the correct location)

---

### Error: "Command CompileSwiftSources failed"

**What it means:** Swift syntax error in one of the files.

**Solution:**
1. Look at the **full error message** in the Report Navigator (⌘9)
2. It will show which file and line number
3. Double-check you copied all code correctly
4. Common issues:
   - Missing closing brace `}`
   - Missing import statement
   - Typo in variable name

---

## 🖥️ Runtime Issues

### App doesn't appear in menu bar

**Possible causes:**
1. **Not a menu bar app** → Check Info.plist has `LSUIElement = YES`
2. **App crashed on launch** → Check Console for errors
3. **Icon is hidden** → Look very carefully in top-right corner

**Solution:**
1. Click **blue project icon** → **Info** tab
2. Find (or add): **"Application is agent (UIElement)"**
3. Set to: **YES**
4. Rebuild and run

**If still not visible:**
- Check the **Console** in Xcode (Cmd+Shift+Y)
- Look for red error messages
- The app might be crashing on launch

---

### Hotkey doesn't work

**Possible causes:**
1. **No Accessibility permission**
2. **App is disabled**
3. **Hotkey conflict with another app**

**Solutions:**

**A. Check Accessibility Permission:**
1. Open **System Settings** (or System Preferences)
2. Go to: **Privacy & Security → Accessibility**
3. Find **LangOver** in the list
4. Toggle it **ON** (you may need to click 🔒 first)
5. If not in list: Try relaunching the app

**B. Check if app is enabled:**
1. Click the **LangOver menu bar icon**
2. Does it say **"Disable"** or **"Enable"**?
   - If it says "Enable", click it (it's currently disabled)

**C. Check for conflicts:**
1. Try changing the hotkey:
   - Menu bar → **Preferences**
   - Click the hotkey recorder
   - Press a different combination (e.g., Cmd+Shift+L)
2. Some apps steal global hotkeys (e.g., Spotlight, Alfred)

---

### Text doesn't convert

**Possible causes:**
1. **Text not in English or Hebrew**
2. **App doesn't have Accessibility permission**
3. **Text field is read-only**

**Solutions:**

**A. Check the text:**
- LangOver MVP only supports English ↔ Hebrew
- If text is in another language, it won't convert
- Try typing: `akuo` → Should become `שלום`

**B. Check permission again:**
- System Settings → Privacy & Security → Accessibility
- LangOver should be ✓ enabled

**C. Try a different app:**
- Some apps (browsers, read-only fields) block text modification
- Test in **TextEdit** or **Notes** first
- These apps definitely work

**D. Check selection:**
- Make sure text is **selected** (highlighted)
- Or place cursor at end of text (it will convert from cursor to line break)

---

### Converted text is wrong

**Examples:**
- Types `hello` → Gets `אגממר` (correct: `הקללם`)
- Characters seem mixed up

**Cause:** Hebrew keyboard mapping variation.

**Solution:**
The mapping in `LayoutConverter.swift` assumes the **standard Hebrew (SI 1452)** layout.

If you have a different Hebrew layout:
1. Open **LayoutConverter.swift**
2. Find the `convertEnglishToHebrew` function (line ~37)
3. Adjust the character mapping to match your keyboard
4. Test by typing one letter at a time and seeing what converts

**How to find your mapping:**
1. Switch to Hebrew keyboard in System Settings
2. Open TextEdit
3. Press each English key and note the Hebrew character
4. Update the dictionary in the code

---

### First Launch dialog doesn't appear

**Possible causes:**
1. **Already completed first launch** (Settings saved)
2. **Dialog is behind another window**

**Solution:**

**A. Reset first launch:**
1. Quit the app
2. Open **Terminal** (in Applications/Utilities)
3. Run this command:
   ```bash
   defaults delete com.yourname.LangOver hasCompletedFirstLaunch
   ```
4. Relaunch the app
5. First launch dialog should appear

**B. Check if dialog is hidden:**
- Cmd+Tab to LangOver
- Check if window is behind others

---

### Preferences window won't open

**Possible causes:**
1. **Window is already open** (check behind other windows)
2. **Crash when opening**

**Solution:**

**A. Look for the window:**
- Cmd+Tab to cycle through windows
- Look for "LangOver Preferences" title bar

**B. Check Console:**
1. In Xcode, show **Debug Area** (Cmd+Shift+Y)
2. Try clicking "Preferences" again
3. Look for error messages in red

**C. Force close and retry:**
1. Quit LangOver
2. Relaunch from Xcode
3. Try opening Preferences again

---

### "Start at Login" doesn't work

**Possible causes:**
1. **macOS version too old** (requires 13.0+)
2. **Permission issue**

**Solution:**

**A. Check macOS version:**
- Apple menu → About This Mac
- Must be **macOS 13.0 (Ventura)** or later

**B. If older macOS:**
- This feature requires modern API
- You can manually add to login items:
  - System Settings → General → Login Items
  - Click "+" and add LangOver.app

**C. Check Console for errors:**
- Look for errors mentioning "SMAppService"

---

### App crashes on launch

**What to do:**

**1. Check the crash log:**
- In Xcode, open **Report Navigator** (Cmd+9)
- Click the latest run
- Look for red errors
- Copy the error message

**2. Common crash causes:**

**A. "Cannot find 'KeyboardShortcuts'"**
- Solution: Add the package (see Build Errors above)

**B. "EXC_BAD_ACCESS" or "Fatal error"**
- Solution: Check that all @Published properties in Settings.swift have default values

**C. "Could not find any keyboard layouts"**
- Solution: The keyboard detector might have failed
- Open `KeyboardDetector.swift`
- Check that `getDefaultKeyboards()` is defined (line ~38)

**3. Nuclear option - Clean slate:**
```bash
# In Xcode:
Product → Clean Build Folder (Cmd+Shift+K)

# Delete derived data:
# Xcode → Settings → Locations → Derived Data → Click arrow → Delete folder

# Rebuild:
Product → Build (Cmd+B)
```

---

## 🐞 Debugging Tips

### Enable verbose logging

Add this to the start of any function to see when it's called:

```swift
print("🔍 [FunctionName] called")
```

Example in `HotkeyService.swift`:
```swift
func handleHotkeyPress() {
    print("🔍 Hotkey pressed!")
    // rest of function...
}
```

Run the app, press the hotkey, and watch the Console.

---

### Check Accessibility permission in code

Add this to `AppDelegate.swift` → `applicationDidFinishLaunching`:

```swift
let hasPermission = AccessibilityService.hasAccessibilityPermission()
print("🔐 Accessibility permission: \(hasPermission)")
```

This will print `true` or `false` in the Console.

---

### Test text conversion manually

Add this to `LayoutConverter.swift` to test without running the full app:

```swift
// At the bottom of the file:
func testConversion() {
    let test1 = LayoutConverter.convert(text: "akuo", between: [])
    print("Test 1: akuo → \(test1 ?? "FAILED")")
    
    let test2 = LayoutConverter.convert(text: "שלום", between: [])
    print("Test 2: שלום → \(test2 ?? "FAILED")")
}
```

Call this from anywhere to verify conversion works.

---

### Inspect UserDefaults

See what settings are saved:

```bash
# In Terminal:
defaults read com.yourname.LangOver
```

This shows all saved preferences.

**Reset all settings:**
```bash
defaults delete com.yourname.LangOver
```

---

## 🔍 Advanced Diagnostics

### Check if app is in Accessibility list

Run this in Terminal:
```bash
sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db \
"SELECT service, client, auth_value FROM access WHERE service='kTCCServiceAccessibility';"
```

Look for your app's bundle ID in the output.

---

### Monitor global hotkey events

Add this to `HotkeyService.swift`:

```swift
func startListening(onTrigger: @escaping () -> Void) {
    print("👂 Started listening for hotkey")
    KeyboardShortcuts.onKeyUp(for: .toggleConversion) {
        print("⌨️ Hotkey triggered!")
        if Settings.shared.isEnabled {
            print("✅ App is enabled, running conversion")
            onTrigger()
        } else {
            print("⏸️ App is disabled, ignoring")
        }
    }
}
```

This will tell you exactly when the hotkey is pressed and why it might be ignored.

---

## 🆘 Still Having Issues?

### Collect diagnostic info:

1. **Xcode Console output**
   - Cmd+Shift+Y to show Console
   - Copy all output when reproducing the issue

2. **System info:**
   - macOS version (Apple menu → About This Mac)
   - Xcode version (Xcode → About Xcode)

3. **Steps to reproduce:**
   - What you did
   - What you expected
   - What actually happened

4. **Screenshots:**
   - Error messages
   - Xcode settings
   - System Settings (if relevant)

---

## 🧹 Clean Reinstall

If all else fails, start fresh:

1. **Quit LangOver**
2. **Delete app:**
   - Find LangOver.app in Derived Data
   - Delete it
3. **Clear settings:**
   ```bash
   defaults delete com.yourname.LangOver
   ```
4. **Remove from Accessibility list:**
   - System Settings → Privacy & Security → Accessibility
   - Select LangOver → Click "-" to remove
5. **Clean Xcode:**
   - Product → Clean Build Folder (Cmd+Shift+K)
6. **Rebuild:**
   - Product → Build (Cmd+B)
7. **Run:**
   - Product → Run (Cmd+R)

---

## 📚 Useful Resources

- **Xcode Documentation:** Help → Xcode Help
- **Swift Forums:** forums.swift.org
- **macOS Accessibility:** developer.apple.com/accessibility
- **KeyboardShortcuts Library:** github.com/sindresorhus/KeyboardShortcuts

---

**Remember:** Most issues are either:
1. Missing Accessibility permission
2. Missing KeyboardShortcuts package
3. Wrong deployment target

Check those three first! 🎯
