├── documentation ├── lorem-chatum.gif └── lorem-chatum.mp4 ├── .eslintrc.json ├── package.json ├── scripts ├── prepare.js ├── dev.js ├── version.js ├── build.js ├── release.js ├── build-multiplatform.js └── build-artifacts.js ├── src ├── v2-indesign-2023-and-newer │ ├── install-Win.bat │ ├── install-Mac.command │ ├── LICENSE.txt │ └── Lorem-Chatum-v2.idjs └── v1-indesign-2022-and-older │ └── LICENSE.txt ├── test ├── integration-test.js └── run-tests.js ├── .gitignore ├── INSTALLATION.md ├── DEVELOPMENT.md ├── LICENSE.txt └── README.md /documentation/lorem-chatum.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twardoch/lorem-chatum-for-indesign/HEAD/documentation/lorem-chatum.gif -------------------------------------------------------------------------------- /documentation/lorem-chatum.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twardoch/lorem-chatum-for-indesign/HEAD/documentation/lorem-chatum.mp4 -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "es6": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended" 8 | ], 9 | "parserOptions": { 10 | "ecmaVersion": 2020, 11 | "sourceType": "module" 12 | }, 13 | "rules": { 14 | "no-console": "off", 15 | "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], 16 | "prefer-const": "error", 17 | "no-var": "error", 18 | "eqeqeq": "error", 19 | "curly": "error", 20 | "brace-style": ["error", "1tbs"], 21 | "comma-dangle": ["error", "never"], 22 | "quotes": ["error", "single", { "avoidEscape": true }], 23 | "semi": ["error", "always"], 24 | "indent": ["error", 2], 25 | "no-trailing-spaces": "error", 26 | "eol-last": "error" 27 | }, 28 | "overrides": [ 29 | { 30 | "files": ["src/**/*.jsx"], 31 | "env": { 32 | "node": false, 33 | "es6": false 34 | }, 35 | "parserOptions": { 36 | "ecmaVersion": 3, 37 | "sourceType": "script" 38 | }, 39 | "rules": { 40 | "no-var": "off", 41 | "prefer-const": "off", 42 | "no-undef": "off" 43 | } 44 | }, 45 | { 46 | "files": ["src/**/*.idjs"], 47 | "env": { 48 | "node": false, 49 | "browser": true, 50 | "es6": true 51 | }, 52 | "parserOptions": { 53 | "ecmaVersion": 2020, 54 | "sourceType": "script" 55 | }, 56 | "rules": { 57 | "no-undef": "off" 58 | } 59 | } 60 | ] 61 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lorem-chatum-for-indesign", 3 | "version": "2.0.0", 4 | "description": "Generate contextually-aware placeholder text in Adobe InDesign using the power of ChatGPT", 5 | "main": "src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs", 6 | "scripts": { 7 | "test": "node test/run-tests.js", 8 | "test:watch": "node test/run-tests.js --watch", 9 | "test:integration": "node test/integration-test.js", 10 | "lint": "eslint src/ test/ --ext .js,.jsx,.idjs", 11 | "lint:fix": "eslint src/ test/ --ext .js,.jsx,.idjs --fix", 12 | "build": "node scripts/build.js", 13 | "build:multiplatform": "node scripts/build-multiplatform.js", 14 | "build:artifacts": "node scripts/build-artifacts.js", 15 | "release": "node scripts/release.js", 16 | "version": "node scripts/version.js", 17 | "prepare": "node scripts/prepare.js", 18 | "dev": "node scripts/dev.js", 19 | "clean": "node scripts/dev.js clean" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/twardoch/lorem-chatum-for-indesign.git" 24 | }, 25 | "keywords": [ 26 | "adobe", 27 | "indesign", 28 | "script", 29 | "placeholder", 30 | "text", 31 | "chatgpt", 32 | "lorem-ipsum" 33 | ], 34 | "author": "Adam Twardoch", 35 | "license": "Apache-2.0", 36 | "bugs": { 37 | "url": "https://github.com/twardoch/lorem-chatum-for-indesign/issues" 38 | }, 39 | "homepage": "https://github.com/twardoch/lorem-chatum-for-indesign#readme", 40 | "devDependencies": { 41 | "eslint": "^8.57.0", 42 | "fs-extra": "^11.2.0", 43 | "chalk": "^5.3.0", 44 | "archiver": "^6.0.1", 45 | "semver": "^7.6.0" 46 | }, 47 | "engines": { 48 | "node": ">=16.0.0" 49 | }, 50 | "files": [ 51 | "src/", 52 | "scripts/", 53 | "LICENSE.txt", 54 | "README.md" 55 | ] 56 | } -------------------------------------------------------------------------------- /scripts/prepare.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/prepare.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const { execSync } = require('child_process'); 7 | 8 | /** 9 | * Prepare the project for development 10 | */ 11 | async function prepare() { 12 | console.log('Preparing project for development...'); 13 | 14 | try { 15 | // Ensure directories exist 16 | await fs.ensureDir(path.join(__dirname, '../build')); 17 | await fs.ensureDir(path.join(__dirname, '../dist')); 18 | await fs.ensureDir(path.join(__dirname, '../test/temp')); 19 | 20 | // Install dependencies if needed 21 | try { 22 | const packageJson = JSON.parse(await fs.readFile(path.join(__dirname, '../package.json'), 'utf8')); 23 | if (packageJson.devDependencies) { 24 | console.log('Installing dependencies...'); 25 | execSync('npm install', { stdio: 'inherit', cwd: path.join(__dirname, '..') }); 26 | } 27 | } catch (error) { 28 | console.warn('Could not install dependencies:', error.message); 29 | } 30 | 31 | // Check git hooks 32 | const gitHooksDir = path.join(__dirname, '../.git/hooks'); 33 | if (await fs.pathExists(gitHooksDir)) { 34 | const preCommitHook = path.join(gitHooksDir, 'pre-commit'); 35 | if (!await fs.pathExists(preCommitHook)) { 36 | const hookContent = `#!/bin/sh 37 | # Run tests before commit 38 | npm test 39 | `; 40 | await fs.writeFile(preCommitHook, hookContent); 41 | await fs.chmod(preCommitHook, '755'); 42 | console.log('Created pre-commit hook'); 43 | } 44 | } 45 | 46 | console.log('✅ Project preparation complete!'); 47 | 48 | } catch (error) { 49 | console.error('❌ Project preparation failed:', error.message); 50 | process.exit(1); 51 | } 52 | } 53 | 54 | if (require.main === module) { 55 | prepare(); 56 | } 57 | 58 | module.exports = { prepare }; -------------------------------------------------------------------------------- /src/v2-indesign-2023-and-newer/install-Win.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal enabledelayedexpansion 3 | 4 | echo. 5 | echo ### LOREM CHATUM 6 | echo. 7 | echo Go to https://platform.openai.com/account/api-keys and create an OpenAI API secret key. 8 | echo. 9 | echo Now paste the key here and press Enter: 10 | set /p OPENAI_API_KEY= 11 | 12 | set SCRIPT_NAME=Lorem-Chatum-v2.idjs 13 | set INDESIGN_BASE_PATH=%USERPROFILE%\AppData\Roaming\Adobe\InDesign 14 | set SCRIPTS_PANEL=Scripts Panel 15 | 16 | for /f "tokens=* delims=" %%v in ('dir /b /ad /o-n "%INDESIGN_BASE_PATH%\Version *.*"') do ( 17 | set LATEST_VERSION_FOLDER=%%v 18 | goto :break 19 | ) 20 | :break 21 | 22 | for /f "tokens=* delims=" %%l in ('dir /b /ad "%INDESIGN_BASE_PATH%\%LATEST_VERSION_FOLDER%"') do ( 23 | set LANGUAGE_FOLDER=%%l 24 | goto :break2 25 | ) 26 | :break2 27 | 28 | set TARGET_FOLDER=%INDESIGN_BASE_PATH%\%LATEST_VERSION_FOLDER%\%LANGUAGE_FOLDER%\%SCRIPTS_PANEL% 29 | set TARGET_FILE=%TARGET_FOLDER%\%SCRIPT_NAME% 30 | 31 | echo Original script path: %SCRIPT_NAME% 32 | echo Target folder: %TARGET_FOLDER% 33 | 34 | copy "%SCRIPT_NAME%" "%TARGET_FOLDER%" >nul 35 | if errorlevel 1 ( 36 | echo Error: Failed to copy the script to the target folder. 37 | exit /b 1 38 | ) 39 | 40 | echo Replacing API key... 41 | ( 42 | for /f "tokens=1,* delims=]" %%a in ('find /n /v "" "%TARGET_FILE%"') do ( 43 | set "line=%%b" 44 | if "!line!" == "const OPENAI_API_KEY = ""sk-"";" ( 45 | echo const OPENAI_API_KEY = ""%OPENAI_API_KEY%""; 46 | ) else ( 47 | echo.!line! 48 | ) 49 | ) 50 | ) > "%TARGET_FILE%.tmp" 51 | 52 | move /y "%TARGET_FILE%.tmp" "%TARGET_FILE%" >nul 53 | 54 | echo. 55 | echo Successfully installed %SCRIPT_NAME% in %TARGET_FOLDER%. 56 | echo. 57 | echo 1. Run Adobe InDesign, open Window > Utilities > Scripts, and in the Script panel, open User. 58 | echo 2. Select a text frame and 2x-click Lorem-Chatum.idjs. 59 | echo. 60 | pause 61 | -------------------------------------------------------------------------------- /src/v2-indesign-2023-and-newer/install-Mac.command: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | # This script installs the Lorem Chatum script in Adobe InDesign 5 | # It prompts the user to enter their OpenAI API secret key 6 | # It then locates the InDesign Scripts Panel folder and installs the script there 7 | 8 | import re 9 | import shutil 10 | from pathlib import Path 11 | 12 | 13 | def install_indesign_script(file_name): 14 | # Prompt user to enter OpenAI API secret key 15 | print("\n\n\n### LOREM CHATUM\n\n") 16 | print( 17 | "Go to https://platform.openai.com/account/api-keys and create an OpenAI API secret key." 18 | ) 19 | print("\nNow paste the key here and press Enter:") 20 | openAiKey = input() 21 | 22 | # Locate the file in the same folder as the current Python file 23 | script_path = Path(__file__).parent / file_name 24 | 25 | # Locate the InDesign Scripts Panel folder 26 | indesign_base_path = Path.home() / "Library" / "Preferences" / "Adobe InDesign" 27 | 28 | # Find the highest version number folder 29 | version_folders = sorted( 30 | indesign_base_path.glob("Version *.*"), 31 | key=lambda x: tuple(map(int, re.findall(r"\d+", x.name))), 32 | reverse=True, 33 | ) 34 | 35 | if not version_folders: 36 | raise FileNotFoundError("No Adobe InDesign Version folder found") 37 | 38 | latest_version_folder = version_folders[0] 39 | 40 | # Find the first language folder 41 | language_folders = list(latest_version_folder.glob("*_*")) 42 | 43 | if not language_folders: 44 | raise FileNotFoundError( 45 | "No language folder found in the Adobe InDesign Version folder" 46 | ) 47 | 48 | language_folder = language_folders[0] 49 | 50 | # Copy the script file into the Scripts Panel folder 51 | scripts_panel_folder = language_folder / "Scripts" / "Scripts Panel" 52 | scripts_panel_path = scripts_panel_folder / file_name 53 | scripts_panel_path.write_text( 54 | script_path.read_text().replace( 55 | """const OPENAI_API_KEY = "sk-";""", 56 | f"""const OPENAI_API_KEY = "{openAiKey}";""", 57 | ) 58 | ) 59 | print( 60 | f"""\n\nSuccessfully installed `{file_name}` in `{scripts_panel_folder}`.\n\n1. Run Adobe InDesign, open `Window > Utilities > Scripts`, and in the Script panel, open `User`.\n\n2. Select a text frame and 2x-click `Lorem-Chatum.idjs`.\n\n""" 61 | ) 62 | 63 | 64 | # Example usage 65 | install_indesign_script("Lorem-Chatum-v2.idjs") 66 | -------------------------------------------------------------------------------- /scripts/dev.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/dev.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const { execSync, spawn } = require('child_process'); 7 | 8 | /** 9 | * Development workflow script 10 | */ 11 | async function dev() { 12 | console.log('Starting development workflow...'); 13 | 14 | const args = process.argv.slice(2); 15 | const command = args[0]; 16 | 17 | switch (command) { 18 | case 'test': 19 | console.log('Running tests...'); 20 | execSync('node test/run-tests.js', { stdio: 'inherit' }); 21 | break; 22 | 23 | case 'test:watch': 24 | console.log('Starting test watcher...'); 25 | execSync('node test/run-tests.js --watch', { stdio: 'inherit' }); 26 | break; 27 | 28 | case 'build': 29 | console.log('Building project...'); 30 | execSync('node scripts/build.js', { stdio: 'inherit' }); 31 | break; 32 | 33 | case 'version': 34 | console.log('Checking version...'); 35 | execSync('node scripts/version.js', { stdio: 'inherit' }); 36 | break; 37 | 38 | case 'release': 39 | const version = args[1]; 40 | if (!version) { 41 | console.error('Please provide a version number'); 42 | process.exit(1); 43 | } 44 | console.log(`Releasing version ${version}...`); 45 | execSync(`node scripts/release.js ${version}`, { stdio: 'inherit' }); 46 | break; 47 | 48 | case 'integration': 49 | console.log('Running integration tests...'); 50 | execSync('node test/integration-test.js', { stdio: 'inherit' }); 51 | break; 52 | 53 | case 'clean': 54 | console.log('Cleaning build artifacts...'); 55 | await fs.remove(path.join(__dirname, '../build')); 56 | await fs.remove(path.join(__dirname, '../dist')); 57 | await fs.remove(path.join(__dirname, '../test/temp')); 58 | console.log('✅ Cleaned build artifacts'); 59 | break; 60 | 61 | default: 62 | console.log('Available commands:'); 63 | console.log(' test - Run tests'); 64 | console.log(' test:watch - Run tests in watch mode'); 65 | console.log(' build - Build project'); 66 | console.log(' version - Check current version'); 67 | console.log(' release - Release version'); 68 | console.log(' integration - Run integration tests'); 69 | console.log(' clean - Clean build artifacts'); 70 | break; 71 | } 72 | } 73 | 74 | if (require.main === module) { 75 | dev(); 76 | } 77 | 78 | module.exports = { dev }; -------------------------------------------------------------------------------- /test/integration-test.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: test/integration-test.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const { execSync } = require('child_process'); 7 | const { build } = require('../scripts/build'); 8 | 9 | const TEST_DIR = path.join(__dirname, 'temp'); 10 | const ROOT_DIR = path.join(__dirname, '..'); 11 | 12 | /** 13 | * Integration test for build and release process 14 | */ 15 | async function runIntegrationTest() { 16 | console.log('Running integration test...'); 17 | 18 | try { 19 | // Clean up any existing test directory 20 | await fs.remove(TEST_DIR); 21 | 22 | // Test version script 23 | console.log('\nTesting version script...'); 24 | const { getVersion } = require('../scripts/version'); 25 | const version = getVersion(); 26 | console.log(`Current version: ${version}`); 27 | 28 | // Test build process 29 | console.log('\nTesting build process...'); 30 | await build(); 31 | 32 | // Verify build outputs 33 | const buildDir = path.join(ROOT_DIR, 'build'); 34 | const distDir = path.join(ROOT_DIR, 'dist'); 35 | 36 | if (!await fs.pathExists(buildDir)) { 37 | throw new Error('Build directory not created'); 38 | } 39 | 40 | if (!await fs.pathExists(distDir)) { 41 | throw new Error('Dist directory not created'); 42 | } 43 | 44 | // Check for zip file 45 | const zipFiles = await fs.readdir(distDir); 46 | const zipFile = zipFiles.find(file => file.endsWith('.zip')); 47 | 48 | if (!zipFile) { 49 | throw new Error('No zip file created'); 50 | } 51 | 52 | console.log(`Created zip file: ${zipFile}`); 53 | 54 | // Test installer files 55 | const installersDir = path.join(distDir, 'installers'); 56 | if (await fs.pathExists(installersDir)) { 57 | const installers = await fs.readdir(installersDir); 58 | console.log(`Created installers: ${installers.join(', ')}`); 59 | } 60 | 61 | // Test that source files are properly versioned 62 | const v2Script = path.join(buildDir, 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs'); 63 | if (await fs.pathExists(v2Script)) { 64 | const content = await fs.readFile(v2Script, 'utf8'); 65 | if (content.includes(`v${version}`)) { 66 | console.log('✓ Source files properly versioned'); 67 | } else { 68 | console.log('⚠ Source files may not be properly versioned'); 69 | } 70 | } 71 | 72 | console.log('\n✅ Integration test passed!'); 73 | 74 | } catch (error) { 75 | console.error('❌ Integration test failed:', error.message); 76 | process.exit(1); 77 | } 78 | } 79 | 80 | if (require.main === module) { 81 | runIntegrationTest(); 82 | } 83 | 84 | module.exports = { runIntegrationTest }; -------------------------------------------------------------------------------- /scripts/version.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/version.js 3 | 4 | const fs = require('fs'); 5 | const path = require('path'); 6 | const { execSync } = require('child_process'); 7 | 8 | /** 9 | * Get version from git tags or fallback to package.json 10 | * @returns {string} The current version 11 | */ 12 | function getVersion() { 13 | try { 14 | // Try to get version from git tags 15 | const gitTag = execSync('git describe --tags --exact-match HEAD 2>/dev/null', { 16 | encoding: 'utf8' 17 | }).trim(); 18 | 19 | if (gitTag.match(/^v?\d+\.\d+\.\d+/)) { 20 | return gitTag.replace(/^v/, ''); // Remove 'v' prefix if present 21 | } 22 | } catch (error) { 23 | // If no exact tag match, try to get latest tag and add commit info 24 | try { 25 | const latestTag = execSync('git describe --tags --abbrev=0 2>/dev/null', { 26 | encoding: 'utf8' 27 | }).trim(); 28 | 29 | const commitHash = execSync('git rev-parse --short HEAD', { 30 | encoding: 'utf8' 31 | }).trim(); 32 | 33 | if (latestTag.match(/^v?\d+\.\d+\.\d+/)) { 34 | const cleanTag = latestTag.replace(/^v/, ''); 35 | return `${cleanTag}-dev+${commitHash}`; 36 | } 37 | } catch (error) { 38 | // Fallback to package.json 39 | const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')); 40 | return packageJson.version; 41 | } 42 | } 43 | 44 | // Final fallback 45 | return '0.0.0'; 46 | } 47 | 48 | /** 49 | * Update version in source files 50 | * @param {string} version - The version to set 51 | */ 52 | function updateVersionInFiles(version) { 53 | const files = [ 54 | 'src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx', 55 | 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs' 56 | ]; 57 | 58 | files.forEach(filePath => { 59 | const fullPath = path.join(__dirname, '..', filePath); 60 | if (fs.existsSync(fullPath)) { 61 | let content = fs.readFileSync(fullPath, 'utf8'); 62 | 63 | // Update version in comment header 64 | content = content.replace( 65 | /\/\/ Lorem Chatum v[\d\.]+ for Adobe InDesign/, 66 | `// Lorem Chatum v${version} for Adobe InDesign` 67 | ); 68 | 69 | // Add or update version constant 70 | if (content.includes('const VERSION')) { 71 | content = content.replace( 72 | /const VERSION = ["'][^"']*["'];/, 73 | `const VERSION = "${version}";` 74 | ); 75 | } else { 76 | // Add VERSION constant after API key 77 | content = content.replace( 78 | /(const OPENAI_API_KEY = ["'][^"']*["'];)/, 79 | `$1\nconst VERSION = "${version}";` 80 | ); 81 | } 82 | 83 | fs.writeFileSync(fullPath, content, 'utf8'); 84 | console.log(`Updated version to ${version} in ${filePath}`); 85 | } 86 | }); 87 | } 88 | 89 | if (require.main === module) { 90 | const version = getVersion(); 91 | console.log(`Current version: ${version}`); 92 | updateVersionInFiles(version); 93 | } 94 | 95 | module.exports = { getVersion, updateVersionInFiles }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | 7 | # Build outputs 8 | build/ 9 | dist/ 10 | *.tgz 11 | 12 | # Test outputs 13 | test/temp/ 14 | coverage/ 15 | 16 | # IDE files 17 | .DS_Store 18 | .vscode/ 19 | .idea/ 20 | *.swp 21 | *.swo 22 | *~ 23 | 24 | # OS files 25 | Thumbs.db 26 | desktop.ini 27 | 28 | # Environment variables 29 | .env 30 | .env.local 31 | .env.development.local 32 | .env.test.local 33 | .env.production.local 34 | 35 | # Logs 36 | logs/ 37 | *.log 38 | 39 | # Runtime data 40 | pids/ 41 | *.pid 42 | *.seed 43 | *.pid.lock 44 | 45 | # Temporary files 46 | tmp/ 47 | temp/ 48 | .tmp/ 49 | 50 | # Editor backups 51 | *~ 52 | .#* 53 | \#*# 54 | 55 | # Package lock files (we use npm) 56 | package-lock.json 57 | yarn.lock 58 | 59 | # API keys (security) 60 | **/OPENAI_API_KEY* 61 | **/*api-key* 62 | **/*secret* 63 | 64 | # Build artifacts 65 | *.zip 66 | *.tar.gz 67 | *.tar.bz2 68 | *.dmg 69 | *.pkg 70 | *.deb 71 | *.rpm 72 | 73 | # InDesign files (for testing) 74 | *.indd 75 | *.idml 76 | *.inx 77 | 78 | # Adobe files 79 | *.jsx.bak 80 | *.idjs.bak 81 | 82 | # Python (legacy from previous gitignore) 83 | __pycache__/ 84 | *.py[cod] 85 | *$py.class 86 | *.so 87 | .Python 88 | develop-eggs/ 89 | downloads/ 90 | eggs/ 91 | .eggs/ 92 | lib/ 93 | lib64/ 94 | parts/ 95 | sdist/ 96 | var/ 97 | wheels/ 98 | pip-wheel-metadata/ 99 | share/python-wheels/ 100 | *.egg-info/ 101 | .installed.cfg 102 | *.egg 103 | MANIFEST 104 | 105 | # PyInstaller 106 | # Usually these files are written by a python script from a template 107 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 108 | *.manifest 109 | *.spec 110 | 111 | # Installer logs 112 | pip-log.txt 113 | pip-delete-this-directory.txt 114 | 115 | # Unit test / coverage reports 116 | htmlcov/ 117 | .tox/ 118 | .nox/ 119 | .coverage 120 | .coverage.* 121 | .cache 122 | nosetests.xml 123 | coverage.xml 124 | *.cover 125 | *.py,cover 126 | .hypothesis/ 127 | .pytest_cache/ 128 | 129 | # Translations 130 | *.mo 131 | *.pot 132 | 133 | # Django stuff: 134 | *.log 135 | local_settings.py 136 | db.sqlite3 137 | db.sqlite3-journal 138 | 139 | # Flask stuff: 140 | instance/ 141 | .webassets-cache 142 | 143 | # Scrapy stuff: 144 | .scrapy 145 | 146 | # Sphinx documentation 147 | docs/_build/ 148 | 149 | # PyBuilder 150 | target/ 151 | 152 | # Jupyter Notebook 153 | .ipynb_checkpoints 154 | 155 | # IPython 156 | profile_default/ 157 | ipython_config.py 158 | 159 | # pyenv 160 | .python-version 161 | 162 | # pipenv 163 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 164 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 165 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 166 | # install all needed dependencies. 167 | #Pipfile.lock 168 | 169 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 170 | __pypackages__/ 171 | 172 | # Celery stuff 173 | celerybeat-schedule 174 | celerybeat.pid 175 | 176 | # SageMath parsed files 177 | *.sage.py 178 | 179 | # Environments 180 | .env 181 | .venv 182 | env/ 183 | venv/ 184 | ENV/ 185 | env.bak/ 186 | venv.bak/ 187 | 188 | # Spyder project settings 189 | .spyderproject 190 | .spyproject 191 | 192 | # Rope project settings 193 | .ropeproject 194 | 195 | # mkdocs documentation 196 | /site 197 | 198 | # mypy 199 | .mypy_cache/ 200 | .dmypy.json 201 | dmypy.json 202 | 203 | # Pyre type checker 204 | .pyre/ 205 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/build.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const archiver = require('archiver'); 7 | const { getVersion } = require('./version'); 8 | const { buildMultiplatform } = require('./build-multiplatform'); 9 | const { buildArtifacts } = require('./build-artifacts'); 10 | 11 | const BUILD_DIR = path.join(__dirname, '../build'); 12 | const DIST_DIR = path.join(__dirname, '../dist'); 13 | 14 | /** 15 | * Clean build and dist directories 16 | */ 17 | async function clean() { 18 | await fs.remove(BUILD_DIR); 19 | await fs.remove(DIST_DIR); 20 | await fs.ensureDir(BUILD_DIR); 21 | await fs.ensureDir(DIST_DIR); 22 | console.log('Cleaned build and dist directories'); 23 | } 24 | 25 | /** 26 | * Copy source files to build directory 27 | */ 28 | async function copySource() { 29 | await fs.copy(path.join(__dirname, '../src'), path.join(BUILD_DIR, 'src')); 30 | await fs.copy(path.join(__dirname, '../LICENSE.txt'), path.join(BUILD_DIR, 'LICENSE.txt')); 31 | await fs.copy(path.join(__dirname, '../README.md'), path.join(BUILD_DIR, 'README.md')); 32 | 33 | // Copy documentation if it exists 34 | const docPath = path.join(__dirname, '../documentation'); 35 | if (await fs.pathExists(docPath)) { 36 | await fs.copy(docPath, path.join(BUILD_DIR, 'documentation')); 37 | } 38 | 39 | console.log('Copied source files to build directory'); 40 | } 41 | 42 | /** 43 | * Create zip archive 44 | */ 45 | async function createZip() { 46 | const version = getVersion(); 47 | const zipPath = path.join(DIST_DIR, `lorem-chatum-for-indesign-${version}.zip`); 48 | 49 | return new Promise((resolve, reject) => { 50 | const output = fs.createWriteStream(zipPath); 51 | const archive = archiver('zip', { 52 | zlib: { level: 9 } // Best compression 53 | }); 54 | 55 | output.on('close', () => { 56 | console.log(`Created ${zipPath} (${archive.pointer()} bytes)`); 57 | resolve(zipPath); 58 | }); 59 | 60 | archive.on('error', reject); 61 | archive.pipe(output); 62 | 63 | // Add all files from build directory 64 | archive.directory(BUILD_DIR, false); 65 | archive.finalize(); 66 | }); 67 | } 68 | 69 | /** 70 | * Create platform-specific installers 71 | */ 72 | async function createInstallers() { 73 | const version = getVersion(); 74 | const installersDir = path.join(DIST_DIR, 'installers'); 75 | await fs.ensureDir(installersDir); 76 | 77 | // Copy v2 installers 78 | await fs.copy( 79 | path.join(BUILD_DIR, 'src/v2-indesign-2023-and-newer/install-Mac.command'), 80 | path.join(installersDir, `lorem-chatum-v${version}-install-Mac.command`) 81 | ); 82 | 83 | await fs.copy( 84 | path.join(BUILD_DIR, 'src/v2-indesign-2023-and-newer/install-Win.bat'), 85 | path.join(installersDir, `lorem-chatum-v${version}-install-Win.bat`) 86 | ); 87 | 88 | console.log('Created platform-specific installers'); 89 | } 90 | 91 | /** 92 | * Main build function 93 | */ 94 | async function build() { 95 | console.log('Starting build process...'); 96 | const startTime = Date.now(); 97 | 98 | try { 99 | await clean(); 100 | await copySource(); 101 | await createZip(); 102 | await createInstallers(); 103 | await buildMultiplatform(); 104 | await buildArtifacts(); 105 | 106 | const duration = Date.now() - startTime; 107 | console.log(`Build completed successfully in ${duration}ms`); 108 | } catch (error) { 109 | console.error('Build failed:', error); 110 | process.exit(1); 111 | } 112 | } 113 | 114 | if (require.main === module) { 115 | build(); 116 | } 117 | 118 | module.exports = { build }; -------------------------------------------------------------------------------- /scripts/release.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/release.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const { execSync } = require('child_process'); 7 | const { getVersion, updateVersionInFiles } = require('./version'); 8 | const { build } = require('./build'); 9 | 10 | /** 11 | * Check if working directory is clean 12 | */ 13 | function checkCleanWorkingDirectory() { 14 | try { 15 | const status = execSync('git status --porcelain', { encoding: 'utf8' }); 16 | if (status.trim()) { 17 | console.error('Working directory is not clean. Please commit or stash changes first.'); 18 | process.exit(1); 19 | } 20 | } catch (error) { 21 | console.error('Failed to check git status:', error.message); 22 | process.exit(1); 23 | } 24 | } 25 | 26 | /** 27 | * Validate that we're on the correct branch 28 | */ 29 | function validateBranch() { 30 | try { 31 | const branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim(); 32 | if (branch !== 'main' && branch !== 'master') { 33 | console.warn(`Warning: You are on branch '${branch}', not 'main' or 'master'`); 34 | } 35 | } catch (error) { 36 | console.error('Failed to check current branch:', error.message); 37 | process.exit(1); 38 | } 39 | } 40 | 41 | /** 42 | * Create and push git tag 43 | */ 44 | function createGitTag(version) { 45 | try { 46 | const tagName = `v${version}`; 47 | 48 | // Check if tag already exists 49 | try { 50 | execSync(`git rev-parse ${tagName}`, { stdio: 'ignore' }); 51 | console.error(`Tag ${tagName} already exists`); 52 | process.exit(1); 53 | } catch (error) { 54 | // Tag doesn't exist, which is what we want 55 | } 56 | 57 | // Create tag 58 | execSync(`git tag -a ${tagName} -m "Release ${version}"`, { stdio: 'inherit' }); 59 | console.log(`Created tag: ${tagName}`); 60 | 61 | // Push tag 62 | execSync(`git push origin ${tagName}`, { stdio: 'inherit' }); 63 | console.log(`Pushed tag: ${tagName}`); 64 | 65 | return tagName; 66 | } catch (error) { 67 | console.error('Failed to create or push tag:', error.message); 68 | process.exit(1); 69 | } 70 | } 71 | 72 | /** 73 | * Update package.json version 74 | */ 75 | function updatePackageVersion(version) { 76 | const packagePath = path.join(__dirname, '../package.json'); 77 | const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8')); 78 | packageJson.version = version; 79 | fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\n'); 80 | console.log(`Updated package.json version to ${version}`); 81 | } 82 | 83 | /** 84 | * Main release function 85 | */ 86 | async function release() { 87 | console.log('Starting release process...'); 88 | 89 | const args = process.argv.slice(2); 90 | const version = args[0]; 91 | 92 | if (!version) { 93 | console.error('Please provide a version number (e.g., npm run release 2.1.0)'); 94 | process.exit(1); 95 | } 96 | 97 | if (!/^\d+\.\d+\.\d+$/.test(version)) { 98 | console.error('Version must be in format X.Y.Z (e.g., 2.1.0)'); 99 | process.exit(1); 100 | } 101 | 102 | try { 103 | // Pre-release checks 104 | validateBranch(); 105 | checkCleanWorkingDirectory(); 106 | 107 | // Update versions 108 | updatePackageVersion(version); 109 | updateVersionInFiles(version); 110 | 111 | // Commit version changes 112 | execSync(`git add package.json src/`, { stdio: 'inherit' }); 113 | execSync(`git commit -m "chore: bump version to ${version}"`, { stdio: 'inherit' }); 114 | 115 | // Create and push tag 116 | createGitTag(version); 117 | 118 | // Build 119 | await build(); 120 | 121 | console.log(`\nRelease ${version} completed successfully!`); 122 | console.log('GitHub Actions will now build and create the release artifacts.'); 123 | 124 | } catch (error) { 125 | console.error('Release failed:', error.message); 126 | process.exit(1); 127 | } 128 | } 129 | 130 | if (require.main === module) { 131 | release(); 132 | } 133 | 134 | module.exports = { release }; -------------------------------------------------------------------------------- /INSTALLATION.md: -------------------------------------------------------------------------------- 1 | # Installation Guide 2 | 3 | This guide provides detailed instructions for installing Lorem Chatum for Adobe InDesign. 4 | 5 | ## Prerequisites 6 | 7 | - Adobe InDesign 2022 or newer 8 | - OpenAI API key (get one at https://platform.openai.com/account/api-keys) 9 | - Your OpenAI account must have billing set up 10 | 11 | ## Quick Installation 12 | 13 | ### 1. Download the Latest Release 14 | 15 | Go to the [releases page](https://github.com/twardoch/lorem-chatum-for-indesign/releases) and download the appropriate package: 16 | 17 | - **Windows**: `lorem-chatum-vX.X.X-windows.zip` 18 | - **macOS**: `lorem-chatum-vX.X.X-macos.zip` 19 | - **Universal**: `lorem-chatum-vX.X.X-universal.zip` (all platforms) 20 | 21 | ### 2. Extract the Archive 22 | 23 | Extract the downloaded zip file to a temporary location. 24 | 25 | ### 3. Run the Installer 26 | 27 | #### Windows 28 | 1. Double-click `install-Win.bat` 29 | 2. When prompted, paste your OpenAI API key 30 | 3. Press Enter to continue 31 | 32 | #### macOS 33 | 1. Double-click `install-Mac.command` 34 | 2. When prompted, paste your OpenAI API key 35 | 3. Press Enter to continue 36 | 37 | ### 4. Restart InDesign 38 | 39 | If Adobe InDesign was running during installation, restart it to load the new script. 40 | 41 | ## Manual Installation 42 | 43 | If the automated installer doesn't work, you can install manually: 44 | 45 | ### Step 1: Locate Your Scripts Panel Folder 46 | 47 | Open Adobe InDesign and go to: 48 | - **Window > Utilities > Scripts** 49 | - Right-click on the "User" folder 50 | - Select "Reveal in Finder" (macOS) or "Reveal in Explorer" (Windows) 51 | 52 | This will open your Scripts Panel folder. 53 | 54 | ### Step 2: Choose the Right Script Version 55 | 56 | - **InDesign 2023 and newer**: Use `Lorem-Chatum-v2.idjs` 57 | - **InDesign 2022 and older**: Use `Lorem-Chatum-v1.jsx` 58 | 59 | ### Step 3: Add Your API Key 60 | 61 | 1. Open the script file in a text editor 62 | 2. Find the line that says: 63 | ```javascript 64 | const OPENAI_API_KEY = "sk-"; 65 | ``` 66 | 3. Replace `"sk-"` with your actual API key: 67 | ```javascript 68 | const OPENAI_API_KEY = "sk-your-actual-api-key-here"; 69 | ``` 70 | 4. Save the file 71 | 72 | ### Step 4: Copy to Scripts Panel 73 | 74 | Copy the modified script file to your Scripts Panel folder. 75 | 76 | ### Step 5: Restart InDesign 77 | 78 | Restart Adobe InDesign if it was running. 79 | 80 | ## Troubleshooting 81 | 82 | ### Common Issues 83 | 84 | #### "Script not found" Error 85 | - Make sure you copied the script to the correct Scripts Panel folder 86 | - Restart InDesign after copying the script 87 | 88 | #### "API key not valid" Error 89 | - Verify your API key is correct and starts with "sk-" 90 | - Make sure your OpenAI account has billing set up 91 | - Check that you have sufficient credits in your OpenAI account 92 | 93 | #### "No text frame selected" Error 94 | - Select a text frame before running the script 95 | - Make sure the text frame is not grouped or locked 96 | 97 | #### Permission Errors (macOS) 98 | If you get permission errors with the installer: 99 | 1. Open Terminal 100 | 2. Navigate to the folder containing the installer 101 | 3. Run: `chmod +x install-Mac.command` 102 | 4. Try running the installer again 103 | 104 | #### Script Doesn't Appear in Scripts Panel 105 | - Check that the script file has the correct extension (.idjs for v2, .jsx for v1) 106 | - Verify you're looking in the "User" folder in the Scripts Panel 107 | - Try refreshing the Scripts Panel by right-clicking and selecting "Refresh" 108 | 109 | ### Getting Help 110 | 111 | If you continue to have issues: 112 | 113 | 1. Check the [GitHub Issues](https://github.com/twardoch/lorem-chatum-for-indesign/issues) page 114 | 2. Create a new issue with: 115 | - Your operating system 116 | - InDesign version 117 | - Error message (if any) 118 | - Steps you've already tried 119 | 120 | ## Uninstallation 121 | 122 | To remove Lorem Chatum: 123 | 124 | 1. Open the Scripts Panel folder (Window > Utilities > Scripts > right-click User > Reveal in Finder/Explorer) 125 | 2. Delete the Lorem Chatum script files: 126 | - `Lorem-Chatum-v2.idjs` 127 | - `Lorem-Chatum-v1.jsx` 128 | 3. Restart InDesign 129 | 130 | ## Security Notes 131 | 132 | - Your API key is stored in plain text in the script file 133 | - Only install scripts from trusted sources 134 | - Keep your API key secure and don't share it 135 | - Monitor your OpenAI usage to avoid unexpected charges 136 | 137 | ## Version Information 138 | 139 | This installation guide is for Lorem Chatum version 2.0.0 and newer. For older versions, refer to the documentation included with your download. -------------------------------------------------------------------------------- /scripts/build-multiplatform.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/build-multiplatform.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const archiver = require('archiver'); 7 | const { getVersion } = require('./version'); 8 | 9 | const BUILD_DIR = path.join(__dirname, '../build'); 10 | const DIST_DIR = path.join(__dirname, '../dist'); 11 | const PLATFORMS_DIR = path.join(DIST_DIR, 'platforms'); 12 | 13 | /** 14 | * Create platform-specific packages 15 | */ 16 | async function createPlatformPackages() { 17 | const version = getVersion(); 18 | await fs.ensureDir(PLATFORMS_DIR); 19 | 20 | const platforms = [ 21 | { 22 | name: 'macos', 23 | displayName: 'macOS', 24 | files: [ 25 | 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs', 26 | 'src/v2-indesign-2023-and-newer/install-Mac.command', 27 | 'src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx', 28 | 'LICENSE.txt', 29 | 'README.md' 30 | ], 31 | installer: 'install-Mac.command' 32 | }, 33 | { 34 | name: 'windows', 35 | displayName: 'Windows', 36 | files: [ 37 | 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs', 38 | 'src/v2-indesign-2023-and-newer/install-Win.bat', 39 | 'src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx', 40 | 'LICENSE.txt', 41 | 'README.md' 42 | ], 43 | installer: 'install-Win.bat' 44 | }, 45 | { 46 | name: 'universal', 47 | displayName: 'Universal', 48 | files: [ 49 | 'src/', 50 | 'LICENSE.txt', 51 | 'README.md', 52 | 'documentation/' 53 | ], 54 | installer: null 55 | } 56 | ]; 57 | 58 | for (const platform of platforms) { 59 | await createPlatformPackage(platform, version); 60 | } 61 | } 62 | 63 | /** 64 | * Create a platform-specific package 65 | */ 66 | async function createPlatformPackage(platform, version) { 67 | const packageDir = path.join(PLATFORMS_DIR, platform.name); 68 | await fs.ensureDir(packageDir); 69 | 70 | console.log(`Creating ${platform.displayName} package...`); 71 | 72 | // Copy files 73 | for (const file of platform.files) { 74 | const srcPath = path.join(BUILD_DIR, file); 75 | const destPath = path.join(packageDir, file); 76 | 77 | if (await fs.pathExists(srcPath)) { 78 | await fs.copy(srcPath, destPath); 79 | } 80 | } 81 | 82 | // Create platform-specific README 83 | await createPlatformReadme(platform, packageDir, version); 84 | 85 | // Create ZIP archive 86 | const zipPath = path.join(DIST_DIR, `lorem-chatum-${version}-${platform.name}.zip`); 87 | await createZipArchive(packageDir, zipPath); 88 | 89 | console.log(`Created ${platform.displayName} package: ${path.basename(zipPath)}`); 90 | } 91 | 92 | /** 93 | * Create platform-specific README 94 | */ 95 | async function createPlatformReadme(platform, packageDir, version) { 96 | const readmePath = path.join(packageDir, 'README.md'); 97 | 98 | let content = `# Lorem Chatum v${version} - ${platform.displayName} Package 99 | 100 | This package contains the ${platform.displayName}-specific version of Lorem Chatum for Adobe InDesign. 101 | 102 | ## Quick Start 103 | 104 | `; 105 | 106 | if (platform.installer) { 107 | content += `### Automated Installation (Recommended) 108 | 109 | 1. Have your OpenAI API key ready 110 | 2. Double-click \`${platform.installer}\` 111 | 3. Follow the prompts to enter your API key 112 | 4. The script will be automatically installed 113 | 114 | ### Manual Installation 115 | 116 | `; 117 | } 118 | 119 | content += `1. Open your Adobe InDesign Scripts Panel folder: 120 | - **InDesign 2023+**: Copy \`Lorem-Chatum-v2.idjs\` to your Scripts Panel folder 121 | - **InDesign 2022 and older**: Copy \`Lorem-Chatum-v1.jsx\` to your Scripts Panel folder 122 | 123 | 2. Edit the script file to add your OpenAI API key: 124 | - Find the line: \`const OPENAI_API_KEY = "sk-";\` 125 | - Replace \`"sk-"\` with your actual API key 126 | 127 | 3. Restart InDesign if it was running 128 | 129 | ## Usage 130 | 131 | 1. Open InDesign and go to Window > Utilities > Scripts 132 | 2. Find the Lorem Chatum script in the User folder 133 | 3. Select a text frame and double-click the script 134 | 135 | ## Support 136 | 137 | For full documentation and support, visit: 138 | https://github.com/twardoch/lorem-chatum-for-indesign 139 | 140 | ## Version Information 141 | 142 | - Version: ${version} 143 | - Platform: ${platform.displayName} 144 | - Build Date: ${new Date().toISOString()} 145 | `; 146 | 147 | await fs.writeFile(readmePath, content); 148 | } 149 | 150 | /** 151 | * Create ZIP archive from directory 152 | */ 153 | async function createZipArchive(sourceDir, zipPath) { 154 | return new Promise((resolve, reject) => { 155 | const output = fs.createWriteStream(zipPath); 156 | const archive = archiver('zip', { 157 | zlib: { level: 9 } 158 | }); 159 | 160 | output.on('close', () => resolve(zipPath)); 161 | archive.on('error', reject); 162 | 163 | archive.pipe(output); 164 | archive.directory(sourceDir, false); 165 | archive.finalize(); 166 | }); 167 | } 168 | 169 | /** 170 | * Create checksums for all files 171 | */ 172 | async function createChecksums() { 173 | const crypto = require('crypto'); 174 | const checksumFile = path.join(DIST_DIR, 'checksums.txt'); 175 | 176 | const files = await fs.readdir(DIST_DIR); 177 | const zipFiles = files.filter(file => file.endsWith('.zip')); 178 | 179 | let checksumContent = `# Lorem Chatum Release Checksums\n# Generated: ${new Date().toISOString()}\n\n`; 180 | 181 | for (const file of zipFiles) { 182 | const filePath = path.join(DIST_DIR, file); 183 | const fileBuffer = await fs.readFile(filePath); 184 | const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex'); 185 | checksumContent += `${hash} ${file}\n`; 186 | } 187 | 188 | await fs.writeFile(checksumFile, checksumContent); 189 | console.log('Created checksums file'); 190 | } 191 | 192 | /** 193 | * Main function 194 | */ 195 | async function buildMultiplatform() { 196 | console.log('Building multiplatform packages...'); 197 | 198 | try { 199 | await createPlatformPackages(); 200 | await createChecksums(); 201 | 202 | console.log('✅ Multiplatform build completed successfully!'); 203 | 204 | } catch (error) { 205 | console.error('❌ Multiplatform build failed:', error); 206 | process.exit(1); 207 | } 208 | } 209 | 210 | if (require.main === module) { 211 | buildMultiplatform(); 212 | } 213 | 214 | module.exports = { buildMultiplatform, createPlatformPackages }; -------------------------------------------------------------------------------- /DEVELOPMENT.md: -------------------------------------------------------------------------------- 1 | # Development Guide 2 | 3 | This guide explains how to set up the development environment and contribute to Lorem Chatum. 4 | 5 | ## Development Setup 6 | 7 | ### Prerequisites 8 | 9 | - Node.js 16 or newer 10 | - npm (comes with Node.js) 11 | - Git 12 | 13 | ### Initial Setup 14 | 15 | 1. **Clone the repository** 16 | ```bash 17 | git clone https://github.com/twardoch/lorem-chatum-for-indesign.git 18 | cd lorem-chatum-for-indesign 19 | ``` 20 | 21 | 2. **Install dependencies** 22 | ```bash 23 | npm install 24 | ``` 25 | 26 | 3. **Prepare the development environment** 27 | ```bash 28 | npm run prepare 29 | ``` 30 | 31 | ## Project Structure 32 | 33 | ``` 34 | lorem-chatum-for-indesign/ 35 | ├── src/ 36 | │ ├── v1-indesign-2022-and-older/ # Legacy ExtendScript version 37 | │ │ ├── Lorem-Chatum-v1.jsx 38 | │ │ └── LICENSE.txt 39 | │ └── v2-indesign-2023-and-newer/ # Modern UXP version 40 | │ ├── Lorem-Chatum-v2.idjs 41 | │ ├── install-Mac.command 42 | │ ├── install-Win.bat 43 | │ └── LICENSE.txt 44 | ├── scripts/ # Build and development scripts 45 | │ ├── build.js # Main build script 46 | │ ├── build-multiplatform.js # Platform-specific builds 47 | │ ├── build-artifacts.js # Artifact generation 48 | │ ├── version.js # Version management 49 | │ ├── release.js # Release automation 50 | │ ├── prepare.js # Dev environment setup 51 | │ └── dev.js # Development utilities 52 | ├── test/ # Test suite 53 | │ ├── run-tests.js # Main test runner 54 | │ └── integration-test.js # Integration tests 55 | ├── .github/workflows/ # GitHub Actions 56 | │ ├── ci.yml # Continuous Integration 57 | │ ├── release.yml # Release automation 58 | │ └── scheduled.yml # Scheduled maintenance 59 | ├── build/ # Build output (gitignored) 60 | ├── dist/ # Distribution files (gitignored) 61 | ├── package.json # Project configuration 62 | ├── README.md # Main documentation 63 | ├── INSTALLATION.md # Installation guide 64 | ├── DEVELOPMENT.md # This file 65 | └── LICENSE.txt # License 66 | ``` 67 | 68 | ## Available Scripts 69 | 70 | ### Testing 71 | ```bash 72 | npm test # Run all tests 73 | npm run test:watch # Run tests in watch mode 74 | npm run test:integration # Run integration tests 75 | ``` 76 | 77 | ### Building 78 | ```bash 79 | npm run build # Full build process 80 | npm run build:multiplatform # Build platform-specific packages 81 | npm run build:artifacts # Generate release artifacts 82 | ``` 83 | 84 | ### Development 85 | ```bash 86 | npm run dev test # Run tests 87 | npm run dev build # Build project 88 | npm run dev version # Check version 89 | npm run dev clean # Clean build artifacts 90 | ``` 91 | 92 | ### Linting 93 | ```bash 94 | npm run lint # Check code style 95 | npm run lint:fix # Fix code style issues 96 | ``` 97 | 98 | ### Versioning and Release 99 | ```bash 100 | npm run version # Update version in source files 101 | npm run release 2.1.0 # Create and push release tag 102 | ``` 103 | 104 | ## Development Workflow 105 | 106 | ### Making Changes 107 | 108 | 1. **Create a feature branch** 109 | ```bash 110 | git checkout -b feature/your-feature-name 111 | ``` 112 | 113 | 2. **Make your changes** 114 | - Edit source files in `src/` 115 | - Add tests if needed 116 | - Update documentation 117 | 118 | 3. **Test your changes** 119 | ```bash 120 | npm test 121 | npm run test:integration 122 | ``` 123 | 124 | 4. **Build and verify** 125 | ```bash 126 | npm run build 127 | ``` 128 | 129 | 5. **Commit and push** 130 | ```bash 131 | git add . 132 | git commit -m "feat: your feature description" 133 | git push origin feature/your-feature-name 134 | ``` 135 | 136 | 6. **Create a pull request** 137 | 138 | ### Testing 139 | 140 | The project includes comprehensive testing: 141 | 142 | - **Unit tests**: Test individual functions and components 143 | - **Integration tests**: Test the full build process 144 | - **File validation**: Verify file structure and syntax 145 | - **Package validation**: Check package.json and dependencies 146 | 147 | Tests run automatically on: 148 | - Every commit (via git hooks) 149 | - Pull requests (via GitHub Actions) 150 | - Scheduled maintenance (weekly) 151 | 152 | ### Building 153 | 154 | The build process: 155 | 156 | 1. **Clean**: Remove old build artifacts 157 | 2. **Copy Source**: Copy source files to build directory 158 | 3. **Version**: Update version numbers in source files 159 | 4. **Package**: Create zip archives 160 | 5. **Installers**: Create platform-specific installers 161 | 6. **Multiplatform**: Build platform-specific packages 162 | 7. **Artifacts**: Generate metadata and release artifacts 163 | 164 | ### Versioning 165 | 166 | The project uses semantic versioning (semver): 167 | - `MAJOR.MINOR.PATCH` (e.g., 2.1.0) 168 | - Version is managed through git tags 169 | - Source files are automatically updated with version numbers 170 | 171 | ## Code Style 172 | 173 | ### JavaScript/ExtendScript 174 | - Use ES6+ features for v2 (UXP) 175 | - Use ES3 compatible code for v1 (ExtendScript) 176 | - Follow existing code patterns 177 | - Add comments for complex logic 178 | - Use meaningful variable names 179 | 180 | ### File Headers 181 | All source files should include: 182 | ```javascript 183 | // this_file: relative/path/to/file.js 184 | ``` 185 | 186 | ### Documentation 187 | - Update README.md for user-facing changes 188 | - Update INSTALLATION.md for installation changes 189 | - Update this file for development changes 190 | - Add inline comments for complex code 191 | 192 | ## Architecture 193 | 194 | ### V1 (ExtendScript - Legacy) 195 | - **Target**: InDesign 2022 and older 196 | - **Engine**: ExtendScript (ES3) 197 | - **Dependencies**: 198 | - `restix.jsx` for HTTP requests 199 | - `json.jsx` for JSON handling 200 | - **License**: GPL v3.0 (due to dependencies) 201 | 202 | ### V2 (UXP - Modern) 203 | - **Target**: InDesign 2023 and newer 204 | - **Engine**: UXP JavaScript (ES6+) 205 | - **Features**: 206 | - Native `fetch()` API 207 | - Async/await support 208 | - Modern dialog system 209 | - Better error handling 210 | - **License**: Apache 2.0 211 | 212 | ### Build System 213 | - **Node.js**: Build scripts and tooling 214 | - **GitHub Actions**: CI/CD automation 215 | - **Semantic versioning**: Git tag-based versioning 216 | - **Multi-platform**: Windows, macOS, Universal packages 217 | 218 | ## Contributing 219 | 220 | ### Bug Reports 221 | 1. Check existing issues first 222 | 2. Create detailed issue with: 223 | - Steps to reproduce 224 | - Expected vs actual behavior 225 | - System information 226 | - InDesign version 227 | 228 | ### Feature Requests 229 | 1. Check existing issues and discussions 230 | 2. Describe the use case 231 | 3. Propose implementation approach 232 | 4. Consider backward compatibility 233 | 234 | ### Code Contributions 235 | 1. Follow the development workflow above 236 | 2. Add tests for new features 237 | 3. Update documentation 238 | 4. Ensure all tests pass 239 | 5. Follow existing code style 240 | 241 | ### Documentation 242 | 1. Use clear, concise language 243 | 2. Include code examples 244 | 3. Test instructions on different platforms 245 | 4. Update relevant files (README, INSTALLATION, etc.) 246 | 247 | ## Release Process 248 | 249 | ### Automated Release (Recommended) 250 | ```bash 251 | npm run release 2.1.0 252 | ``` 253 | 254 | This will: 255 | 1. Update version in package.json and source files 256 | 2. Create and push a git tag 257 | 3. Trigger GitHub Actions to build and create release 258 | 259 | ### Manual Release 260 | 1. Update version numbers manually 261 | 2. Create git tag: `git tag -a v2.1.0 -m "Release 2.1.0"` 262 | 3. Push tag: `git push origin v2.1.0` 263 | 4. GitHub Actions will handle the rest 264 | 265 | ### What Happens During Release 266 | 1. **CI runs**: Tests and builds on multiple platforms 267 | 2. **Artifacts created**: Zip files, installers, metadata 268 | 3. **GitHub release**: Created with downloadable assets 269 | 4. **NPM publish**: Package published to npm registry 270 | 271 | ## Security 272 | 273 | ### API Key Handling 274 | - API keys are stored in source files (user responsibility) 275 | - Never commit API keys to repository 276 | - Document security considerations clearly 277 | 278 | ### Dependencies 279 | - Regular security audits via `npm audit` 280 | - Automated dependency updates 281 | - Vulnerability scanning in CI 282 | 283 | ### Code Review 284 | - All changes require review 285 | - Automated security checks 286 | - Manual verification of sensitive changes 287 | 288 | ## Troubleshooting 289 | 290 | ### Common Development Issues 291 | 292 | #### Build Failures 293 | - Check Node.js version (16+) 294 | - Run `npm install` to update dependencies 295 | - Check for file permission issues 296 | 297 | #### Test Failures 298 | - Run tests individually to isolate issues 299 | - Check that all files are present 300 | - Verify package.json configuration 301 | 302 | #### Version Issues 303 | - Ensure git tags are properly formatted 304 | - Check that version script has execute permissions 305 | - Verify git repository is clean 306 | 307 | ## Getting Help 308 | 309 | - **GitHub Issues**: Bug reports and feature requests 310 | - **Discussions**: General questions and ideas 311 | - **Discord**: Real-time chat (if available) 312 | - **Documentation**: Check README and guides first 313 | 314 | ## License 315 | 316 | This project is licensed under the Apache 2.0 License for v2 and GPL v3.0 for v1. See the LICENSE.txt files for details. -------------------------------------------------------------------------------- /test/run-tests.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: test/run-tests.js 3 | 4 | const fs = require('fs'); 5 | const path = require('path'); 6 | const { execSync } = require('child_process'); 7 | 8 | const TEST_DIR = __dirname; 9 | const ROOT_DIR = path.join(__dirname, '..'); 10 | 11 | /** 12 | * Colors for console output 13 | */ 14 | const colors = { 15 | reset: '\x1b[0m', 16 | bright: '\x1b[1m', 17 | red: '\x1b[31m', 18 | green: '\x1b[32m', 19 | yellow: '\x1b[33m', 20 | blue: '\x1b[34m', 21 | cyan: '\x1b[36m' 22 | }; 23 | 24 | /** 25 | * Test result tracking 26 | */ 27 | let testResults = { 28 | passed: 0, 29 | failed: 0, 30 | tests: [] 31 | }; 32 | 33 | /** 34 | * Test assertion functions 35 | */ 36 | function assert(condition, message) { 37 | if (condition) { 38 | console.log(`${colors.green}✓${colors.reset} ${message}`); 39 | return true; 40 | } else { 41 | console.log(`${colors.red}✗${colors.reset} ${message}`); 42 | return false; 43 | } 44 | } 45 | 46 | function assertEqual(actual, expected, message) { 47 | const passed = actual === expected; 48 | if (passed) { 49 | console.log(`${colors.green}✓${colors.reset} ${message}`); 50 | } else { 51 | console.log(`${colors.red}✗${colors.reset} ${message}`); 52 | console.log(` Expected: ${expected}`); 53 | console.log(` Actual: ${actual}`); 54 | } 55 | return passed; 56 | } 57 | 58 | function assertMatch(actual, regex, message) { 59 | const passed = regex.test(actual); 60 | if (passed) { 61 | console.log(`${colors.green}✓${colors.reset} ${message}`); 62 | } else { 63 | console.log(`${colors.red}✗${colors.reset} ${message}`); 64 | console.log(` Expected to match: ${regex}`); 65 | console.log(` Actual: ${actual}`); 66 | } 67 | return passed; 68 | } 69 | 70 | /** 71 | * Run a test function 72 | */ 73 | function runTest(testName, testFunction) { 74 | console.log(`\n${colors.cyan}Running test: ${testName}${colors.reset}`); 75 | 76 | try { 77 | const results = testFunction(); 78 | const passed = results.every(result => result === true); 79 | 80 | testResults.tests.push({ 81 | name: testName, 82 | passed: passed, 83 | results: results 84 | }); 85 | 86 | if (passed) { 87 | testResults.passed++; 88 | console.log(`${colors.green}Test passed: ${testName}${colors.reset}`); 89 | } else { 90 | testResults.failed++; 91 | console.log(`${colors.red}Test failed: ${testName}${colors.reset}`); 92 | } 93 | } catch (error) { 94 | testResults.failed++; 95 | testResults.tests.push({ 96 | name: testName, 97 | passed: false, 98 | error: error.message 99 | }); 100 | console.log(`${colors.red}Test error: ${testName}${colors.reset}`); 101 | console.log(`${colors.red}Error: ${error.message}${colors.reset}`); 102 | } 103 | } 104 | 105 | /** 106 | * Test: File structure validation 107 | */ 108 | function testFileStructure() { 109 | const results = []; 110 | 111 | // Check main files exist 112 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'package.json')), 'package.json exists')); 113 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'README.md')), 'README.md exists')); 114 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'LICENSE.txt')), 'LICENSE.txt exists')); 115 | 116 | // Check source files exist 117 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx')), 'v1 script exists')); 118 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs')), 'v2 script exists')); 119 | 120 | // Check installer files exist 121 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'src/v2-indesign-2023-and-newer/install-Mac.command')), 'Mac installer exists')); 122 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'src/v2-indesign-2023-and-newer/install-Win.bat')), 'Windows installer exists')); 123 | 124 | // Check script files exist 125 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'scripts/version.js')), 'version.js script exists')); 126 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'scripts/build.js')), 'build.js script exists')); 127 | results.push(assert(fs.existsSync(path.join(ROOT_DIR, 'scripts/release.js')), 'release.js script exists')); 128 | 129 | return results; 130 | } 131 | 132 | /** 133 | * Test: Package.json validation 134 | */ 135 | function testPackageJson() { 136 | const results = []; 137 | 138 | try { 139 | const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT_DIR, 'package.json'), 'utf8')); 140 | 141 | results.push(assert(packageJson.name === 'lorem-chatum-for-indesign', 'Package name is correct')); 142 | results.push(assert(typeof packageJson.version === 'string', 'Version is a string')); 143 | results.push(assertMatch(packageJson.version, /^\d+\.\d+\.\d+/, 'Version follows semver format')); 144 | results.push(assert(packageJson.license === 'Apache-2.0', 'License is Apache-2.0')); 145 | results.push(assert(packageJson.scripts && typeof packageJson.scripts === 'object', 'Scripts section exists')); 146 | results.push(assert(packageJson.scripts.test, 'Test script exists')); 147 | results.push(assert(packageJson.scripts.build, 'Build script exists')); 148 | results.push(assert(packageJson.scripts.release, 'Release script exists')); 149 | 150 | } catch (error) { 151 | results.push(assert(false, `Failed to parse package.json: ${error.message}`)); 152 | } 153 | 154 | return results; 155 | } 156 | 157 | /** 158 | * Test: Version script functionality 159 | */ 160 | function testVersionScript() { 161 | const results = []; 162 | 163 | try { 164 | const { getVersion } = require(path.join(ROOT_DIR, 'scripts/version.js')); 165 | const version = getVersion(); 166 | 167 | results.push(assert(typeof version === 'string', 'getVersion returns a string')); 168 | results.push(assert(version.length > 0, 'Version is not empty')); 169 | results.push(assertMatch(version, /^\d+\.\d+\.\d+/, 'Version follows semver format (basic)')); 170 | 171 | } catch (error) { 172 | results.push(assert(false, `Version script test failed: ${error.message}`)); 173 | } 174 | 175 | return results; 176 | } 177 | 178 | /** 179 | * Test: Source file syntax validation 180 | */ 181 | function testSourceFileSyntax() { 182 | const results = []; 183 | 184 | const sourceFiles = [ 185 | 'src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx', 186 | 'src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs' 187 | ]; 188 | 189 | sourceFiles.forEach(filePath => { 190 | try { 191 | const fullPath = path.join(ROOT_DIR, filePath); 192 | const content = fs.readFileSync(fullPath, 'utf8'); 193 | 194 | // Basic syntax checks 195 | results.push(assert(content.includes('OPENAI_API_KEY'), `${filePath} contains OPENAI_API_KEY`)); 196 | results.push(assert(content.includes('Lorem Chatum'), `${filePath} contains Lorem Chatum header`)); 197 | results.push(assert(content.length > 1000, `${filePath} has substantial content`)); 198 | 199 | // Check for required functions (v2 specific) 200 | if (filePath.includes('v2')) { 201 | results.push(assert(content.includes('async function'), `${filePath} uses async functions`)); 202 | results.push(assert(content.includes('fetch'), `${filePath} uses fetch for API calls`)); 203 | } 204 | 205 | } catch (error) { 206 | results.push(assert(false, `Failed to read ${filePath}: ${error.message}`)); 207 | } 208 | }); 209 | 210 | return results; 211 | } 212 | 213 | /** 214 | * Test: Build script functionality 215 | */ 216 | function testBuildScript() { 217 | const results = []; 218 | 219 | try { 220 | // Test that build script can be imported 221 | const { build } = require(path.join(ROOT_DIR, 'scripts/build.js')); 222 | results.push(assert(typeof build === 'function', 'Build function is exported')); 223 | 224 | // Test that fs-extra and archiver are available 225 | const fsExtra = require('fs-extra'); 226 | const archiver = require('archiver'); 227 | results.push(assert(typeof fsExtra.ensureDir === 'function', 'fs-extra is available')); 228 | results.push(assert(typeof archiver === 'function', 'archiver is available')); 229 | 230 | } catch (error) { 231 | results.push(assert(false, `Build script test failed: ${error.message}`)); 232 | } 233 | 234 | return results; 235 | } 236 | 237 | /** 238 | * Test: Installer file validation 239 | */ 240 | function testInstallerFiles() { 241 | const results = []; 242 | 243 | try { 244 | const macInstaller = fs.readFileSync(path.join(ROOT_DIR, 'src/v2-indesign-2023-and-newer/install-Mac.command'), 'utf8'); 245 | const winInstaller = fs.readFileSync(path.join(ROOT_DIR, 'src/v2-indesign-2023-and-newer/install-Win.bat'), 'utf8'); 246 | 247 | // Mac installer checks 248 | results.push(assert(macInstaller.includes('#!/usr/bin/env python3'), 'Mac installer has correct shebang')); 249 | results.push(assert(macInstaller.includes('platform.openai.com'), 'Mac installer mentions OpenAI')); 250 | results.push(assert(macInstaller.includes('LOREM CHATUM'), 'Mac installer has title')); 251 | 252 | // Windows installer checks 253 | results.push(assert(winInstaller.includes('@echo off'), 'Windows installer has correct header')); 254 | results.push(assert(winInstaller.includes('platform.openai.com'), 'Windows installer mentions OpenAI')); 255 | results.push(assert(winInstaller.includes('LOREM CHATUM'), 'Windows installer has title')); 256 | 257 | } catch (error) { 258 | results.push(assert(false, `Installer file test failed: ${error.message}`)); 259 | } 260 | 261 | return results; 262 | } 263 | 264 | /** 265 | * Main test runner 266 | */ 267 | function runAllTests() { 268 | console.log(`${colors.bright}${colors.blue}Lorem Chatum Test Suite${colors.reset}`); 269 | console.log(`${colors.blue}========================${colors.reset}`); 270 | 271 | const testSuites = [ 272 | ['File Structure', testFileStructure], 273 | ['Package.json', testPackageJson], 274 | ['Version Script', testVersionScript], 275 | ['Source File Syntax', testSourceFileSyntax], 276 | ['Build Script', testBuildScript], 277 | ['Installer Files', testInstallerFiles] 278 | ]; 279 | 280 | testSuites.forEach(([name, testFunction]) => { 281 | runTest(name, testFunction); 282 | }); 283 | 284 | // Print summary 285 | console.log(`\n${colors.bright}${colors.blue}Test Summary${colors.reset}`); 286 | console.log(`${colors.blue}============${colors.reset}`); 287 | console.log(`${colors.green}Passed: ${testResults.passed}${colors.reset}`); 288 | console.log(`${colors.red}Failed: ${testResults.failed}${colors.reset}`); 289 | console.log(`Total: ${testResults.passed + testResults.failed}`); 290 | 291 | if (testResults.failed > 0) { 292 | console.log(`\n${colors.red}Some tests failed!${colors.reset}`); 293 | process.exit(1); 294 | } else { 295 | console.log(`\n${colors.green}All tests passed!${colors.reset}`); 296 | } 297 | } 298 | 299 | // Watch mode 300 | if (process.argv.includes('--watch')) { 301 | console.log('Starting test watcher...'); 302 | 303 | const chokidar = require('chokidar'); 304 | const watcher = chokidar.watch([ 305 | path.join(ROOT_DIR, 'src/**/*'), 306 | path.join(ROOT_DIR, 'test/**/*'), 307 | path.join(ROOT_DIR, 'scripts/**/*'), 308 | path.join(ROOT_DIR, 'package.json') 309 | ], { 310 | ignoreInitial: true, 311 | ignored: /node_modules/ 312 | }); 313 | 314 | watcher.on('change', (path) => { 315 | console.log(`\n${colors.yellow}File changed: ${path}${colors.reset}`); 316 | console.log('Re-running tests...\n'); 317 | runAllTests(); 318 | }); 319 | 320 | // Initial run 321 | runAllTests(); 322 | } else { 323 | // Single run 324 | runAllTests(); 325 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/v2-indesign-2023-and-newer/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs: -------------------------------------------------------------------------------- 1 | // Lorem Chatum v2.0 for Adobe InDesign 2023 and newer 2 | 3 | // Copyright (c) 2023 by Adam Twardoch 4 | // https://github.com/twardoch/lorem-chatum-for-indesign 5 | // Licensed under the Apache 2.0 License 6 | 7 | // Create a new OpenAI API secret key at https://platform.openai.com/account/api-keys 8 | // and paste it below 9 | const OPENAI_API_KEY = "sk-"; 10 | 11 | 12 | let TEXT_COLOR; 13 | if (app.generalPreferences.uiBrightnessPreference <= 0.5) { 14 | TEXT_COLOR = "white"; 15 | } else { 16 | TEXT_COLOR = "black"; 17 | } 18 | 19 | 20 | async function alert(msg) { 21 | /** 22 | * This function creates a dialog box with a message and an OK button. 23 | * @param {string} msg - The message to display in the dialog box. 24 | * @returns {Promise} - A promise that resolves when the OK button is clicked. 25 | */ 26 | return new Promise((resolve) => { 27 | const dialog = document.createElement("dialog"); 28 | dialog.innerHTML = ` 29 |
30 | 31 | ${msg} 32 | 33 | 34 | OK 35 | 36 |
37 | `; 38 | 39 | 40 | const okButton = dialog.querySelector("#ok-button"); 41 | okButton.addEventListener("click", () => { 42 | dialog.close(); 43 | resolve(); 44 | }); 45 | 46 | document.body.appendChild(dialog); 47 | dialog.showModal(); 48 | }); 49 | } 50 | 51 | async function showProgress() { 52 | /** 53 | * This function creates a dialog box with a message indicating that the script is running. 54 | * @returns {Promise} - A promise that resolves when the dialog box is closed. 55 | */ 56 | const dialog = document.createElement("dialog"); 57 | dialog.innerHTML = ` 58 |
59 | 60 | Lorem Chatum dolor... 61 | 62 |
63 | `; 64 | document.body.appendChild(dialog); 65 | const progressBar = dialog.querySelector("#progress-bar"); 66 | dialog.showModal(); 67 | return { dialog, progressBar }; 68 | } 69 | 70 | async function openAIApi(apiKey, prompt, lang, maxTokens) { 71 | /** 72 | * This function sends a request to the OpenAI API to generate text based on a prompt. 73 | * @param {string} apiKey - The OpenAI API key. 74 | * @param {string} prompt - The prompt to generate text from. 75 | * @param {string} lang - The language to generate text in. 76 | * @param {number} maxTokens - The maximum number of tokens to generate. 77 | * @returns {Promise} - A promise that resolves with the generated text. 78 | */ 79 | let requestBody = JSON.stringify({ 80 | model: 'gpt-3.5-turbo', 81 | messages: [ 82 | { 83 | role: 'system', 84 | content: 85 | 'Write an essay in ' + lang + ', to the max length, by continuing the prompt. Do not ask anything, do not add anything that is not requested.', 86 | }, 87 | { role: 'user', content: prompt }, 88 | ], 89 | temperature: 1, 90 | max_tokens: maxTokens, 91 | top_p: 1, 92 | n: 1, 93 | frequency_penalty: 0, 94 | presence_penalty: 0, 95 | }); 96 | 97 | let response = await fetch('https://api.openai.com/v1/chat/completions', { 98 | method: 'POST', 99 | headers: { 100 | 'Content-Type': 'application/json', 101 | 'Authorization': 'Bearer ' + apiKey, 102 | }, 103 | body: requestBody 104 | }); 105 | 106 | if (!response.ok) { 107 | if (response.statusText == 'unauthorized') { 108 | throw new Error(`Click here to create an OpenAI API secret key, then paste it at the beginning of this script, and run again.`); 109 | } else { 110 | throw new Error(`Error connecting to OpenAI API: ${response.statusText}.`); 111 | } 112 | } 113 | 114 | let responseData = await response.json(); 115 | let completion = responseData.choices[0].message.content; 116 | return completion; 117 | } 118 | 119 | async function getText(textFrame) { 120 | /** 121 | * This function gets the text content of a text frame. 122 | * @param {TextFrame} textFrame - The text frame to get the text content from. 123 | * @returns {Promise} - A promise that resolves with the text content of the text frame. 124 | */ 125 | var text = ""; 126 | var words = textFrame.words; 127 | if (words != null) { 128 | for (var i = 0; i < words.length; i++) { 129 | var word = words.item(i); 130 | var wordContent = word.contents; 131 | 132 | if (typeof wordContent === 'string') { 133 | text += wordContent + " "; 134 | } 135 | } 136 | } 137 | 138 | return text; 139 | } 140 | 141 | async function getContext(textFrame) { 142 | /** 143 | * This function gets the context for generating text based on a text frame. 144 | * @param {TextFrame} textFrame - The text frame to get the context from. 145 | * @returns {Promise} - A promise that resolves with the context for generating text. 146 | */ 147 | var context = await getText(textFrame); 148 | if (context.length === 0) { 149 | context = await collectPageText(textFrame); 150 | } 151 | return context; 152 | } 153 | 154 | async function collectPageText(textFrame) { 155 | /** 156 | * This function collects text from all text frames on a page. 157 | * @param {TextFrame} textFrame - The text frame to collect text from. 158 | * @returns {Promise} - A promise that resolves with the collected text. 159 | */ 160 | var currentPage = textFrame.parentPage; 161 | var pages = []; 162 | 163 | pages.push(currentPage); 164 | 165 | var combinedText = ''; 166 | var maxWords = 500; 167 | for (var i = 0; i < pages.length; i++) { 168 | combinedText += await getTextFromPage(pages[i]); 169 | if (wordCount(combinedText) >= maxWords) { 170 | combinedText = await capTextAtWords(combinedText, maxWords); 171 | break; 172 | } 173 | } 174 | 175 | return combinedText; 176 | } 177 | 178 | async function getTextFromPage(page) { 179 | /** 180 | * This function gets the text content of all text frames on a page. 181 | * @param {Page} page - The page to get the text content from. 182 | * @returns {Promise} - A promise that resolves with the text content of all text frames on the page. 183 | */ 184 | var textFrames = page.textFrames; 185 | var combinedText = ''; 186 | for (var i = 0; i < textFrames.length; i++) { 187 | var textFrame = textFrames.item(i); 188 | combinedText += await getText(textFrame); 189 | } 190 | 191 | return combinedText; 192 | } 193 | 194 | async function wordCount(text) { 195 | /** 196 | * This function counts the number of words in a string. 197 | * @param {string} text - The string to count the words in. 198 | * @returns {Promise} - A promise that resolves with the number of words in the string. 199 | */ 200 | var words = text.replace(/^\s+|\s+$/g, '').split(/\s+/); 201 | return words.length; 202 | } 203 | 204 | async function capTextAtWords(text, wordLimit) { 205 | /** 206 | * This function caps the number of words in a string. 207 | * @param {string} text - The string to cap the number of words in. 208 | * @param {number} wordLimit - The maximum number of words to allow in the string. 209 | * @returns {Promise} - A promise that resolves with the capped string. 210 | */ 211 | var words = text.replace(/^\s+|\s+$/g, '').split(/\s+/); 212 | var cappedWords = words.slice(0, wordLimit); 213 | return cappedWords.join(' '); 214 | } 215 | 216 | async function estimateTokens(textFrame) { 217 | /** 218 | * This function estimates the number of tokens needed to generate text for a text frame. 219 | * @param {TextFrame} textFrame - The text frame to estimate the number of tokens for. 220 | * @returns {Promise} - A promise that resolves with the estimated number of tokens. 221 | */ 222 | var frameWidth = textFrame.geometricBounds[3] - textFrame.geometricBounds[1]; 223 | var frameHeight = textFrame.geometricBounds[2] - textFrame.geometricBounds[0]; 224 | var fontSize = textFrame.texts.item(0).pointSize; 225 | var lineHeight = fontSize * 1.2; 226 | 227 | var avgCharWidth = fontSize * 0.6; 228 | var charsPerLine = Math.floor(frameWidth / avgCharWidth); 229 | var lines = Math.floor(frameHeight / lineHeight); 230 | 231 | var estimatedChars = charsPerLine * lines; 232 | console.warn(" frameHeight: " + frameHeight); 233 | console.warn(" frameWidth: " + frameWidth); 234 | console.warn(" lineHeight: " + lineHeight); 235 | console.warn(" fontSize: " + fontSize); 236 | console.warn(" Lines: " + lines); 237 | console.warn(" Chars per line: " + charsPerLine); 238 | console.warn(" Chars: " + estimatedChars); 239 | var estimatedTokens = Math.min(Math.ceil(estimatedChars), 4095); 240 | 241 | return estimatedTokens; 242 | } 243 | 244 | async function getOpenAIApiKey() { 245 | /** 246 | * This function gets the OpenAI API key. 247 | * @returns {Promise} - A promise that resolves with the OpenAI API key. 248 | */ 249 | return OPENAI_API_KEY; 250 | } 251 | 252 | async function getOpenAICompletion(context, lang, estimatedTokens) { 253 | /** 254 | * This function generates text using the OpenAI API. 255 | * @param {string} context - The context for generating text. 256 | * @param {string} lang - The language to generate text in. 257 | * @param {number} estimatedTokens - The estimated number of tokens needed to generate text. 258 | * @returns {Promise} - A promise that resolves with the generated text. 259 | */ 260 | var apiKey = await getOpenAIApiKey(); 261 | var prompt = context.replace(/[\r\n]+/g, ' ') + ' '; 262 | var completion = ''; 263 | 264 | try { 265 | completion = await openAIApi(apiKey, prompt, lang, estimatedTokens); 266 | } catch (error) { 267 | await alert('OpenAI error: ' + error.message); 268 | } 269 | 270 | return ' ' + completion.replace(/^\n/, ''); 271 | } 272 | 273 | async function completeSelectedFrameText() { 274 | /** 275 | * This function generates text and adds it to the selected text frame. 276 | */ 277 | if ( 278 | app.documents.length === 0 || 279 | app.selection.length !== 1 || 280 | app.selection[0].constructorName !== 'TextFrame' 281 | ) { 282 | await alert('Please select a text frame, and set the Character language to the desired language.'); 283 | return; 284 | } 285 | doc = app.activeDocument; 286 | const horizontalMeasurementUnits = doc.viewPreferences.horizontalMeasurementUnits; 287 | doc.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; 288 | const verticalMeasurementUnits = doc.viewPreferences.verticalMeasurementUnits; 289 | doc.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points; 290 | const typographicMeasurementUnits = doc.viewPreferences.typographicMeasurementUnits; 291 | doc.viewPreferences.typographicMeasurementUnits = MeasurementUnits.points; 292 | const textSizeMeasurementUnits = doc.viewPreferences.textSizeMeasurementUnits; 293 | doc.viewPreferences.textSizeMeasurementUnits = MeasurementUnits.points; 294 | 295 | const { dialog: progressDialog } = await showProgress(); 296 | try { 297 | var textFrame = app.selection[0]; 298 | var context = await getContext(textFrame); 299 | var lang = textFrame.texts.item(0).appliedLanguage.name.split(":")[0]; 300 | console.warn("CONTEXT: " + context); 301 | var estimatedTokens = await estimateTokens(textFrame); 302 | console.warn("TOKENS: " + estimatedTokens + " LANG: " + lang); 303 | var completion = await getOpenAICompletion(context, lang, estimatedTokens); 304 | console.warn("COMPLETION: " + completion); 305 | textFrame.contents += completion; 306 | } finally { 307 | progressDialog.close(); 308 | } 309 | doc.viewPreferences.horizontalMeasurementUnits = horizontalMeasurementUnits; 310 | doc.viewPreferences.verticalMeasurementUnits = verticalMeasurementUnits; 311 | doc.viewPreferences.typographicMeasurementUnits = typographicMeasurementUnits; 312 | doc.viewPreferences.textSizeMeasurementUnits = textSizeMeasurementUnits; 313 | 314 | } 315 | 316 | await completeSelectedFrameText(); 317 | -------------------------------------------------------------------------------- /scripts/build-artifacts.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // this_file: scripts/build-artifacts.js 3 | 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | const crypto = require('crypto'); 7 | const { getVersion } = require('./version'); 8 | 9 | const DIST_DIR = path.join(__dirname, '../dist'); 10 | const ARTIFACTS_DIR = path.join(DIST_DIR, 'artifacts'); 11 | 12 | /** 13 | * Generate artifact metadata 14 | */ 15 | async function generateArtifactMetadata() { 16 | const version = getVersion(); 17 | const buildDate = new Date().toISOString(); 18 | 19 | const metadata = { 20 | version, 21 | buildDate, 22 | platform: process.platform, 23 | nodeVersion: process.version, 24 | artifacts: [], 25 | checksums: {} 26 | }; 27 | 28 | // Scan for artifacts 29 | const files = await fs.readdir(DIST_DIR); 30 | 31 | for (const file of files) { 32 | const filePath = path.join(DIST_DIR, file); 33 | const stat = await fs.stat(filePath); 34 | 35 | if (stat.isFile() && (file.endsWith('.zip') || file.endsWith('.tar.gz'))) { 36 | const fileBuffer = await fs.readFile(filePath); 37 | const sha256 = crypto.createHash('sha256').update(fileBuffer).digest('hex'); 38 | const sha1 = crypto.createHash('sha1').update(fileBuffer).digest('hex'); 39 | 40 | metadata.artifacts.push({ 41 | name: file, 42 | size: stat.size, 43 | sha256, 44 | sha1, 45 | created: stat.ctime.toISOString() 46 | }); 47 | 48 | metadata.checksums[file] = { 49 | sha256, 50 | sha1 51 | }; 52 | } 53 | } 54 | 55 | return metadata; 56 | } 57 | 58 | /** 59 | * Create release manifest 60 | */ 61 | async function createReleaseManifest() { 62 | const metadata = await generateArtifactMetadata(); 63 | 64 | const manifest = { 65 | name: 'lorem-chatum-for-indesign', 66 | version: metadata.version, 67 | description: 'Generate contextually-aware placeholder text in Adobe InDesign using ChatGPT', 68 | homepage: 'https://github.com/twardoch/lorem-chatum-for-indesign', 69 | repository: 'https://github.com/twardoch/lorem-chatum-for-indesign.git', 70 | license: 'Apache-2.0', 71 | author: 'Adam Twardoch', 72 | build: { 73 | date: metadata.buildDate, 74 | platform: metadata.platform, 75 | nodeVersion: metadata.nodeVersion 76 | }, 77 | downloads: metadata.artifacts.map(artifact => ({ 78 | name: artifact.name, 79 | size: artifact.size, 80 | url: `https://github.com/twardoch/lorem-chatum-for-indesign/releases/download/v${metadata.version}/${artifact.name}`, 81 | checksums: { 82 | sha256: artifact.sha256, 83 | sha1: artifact.sha1 84 | } 85 | })), 86 | installation: { 87 | macos: { 88 | file: `lorem-chatum-${metadata.version}-macos.zip`, 89 | installer: 'install-Mac.command', 90 | requirements: ['Adobe InDesign 2022 or newer', 'OpenAI API key'] 91 | }, 92 | windows: { 93 | file: `lorem-chatum-${metadata.version}-windows.zip`, 94 | installer: 'install-Win.bat', 95 | requirements: ['Adobe InDesign 2022 or newer', 'OpenAI API key'] 96 | }, 97 | universal: { 98 | file: `lorem-chatum-${metadata.version}-universal.zip`, 99 | installer: 'Manual installation required', 100 | requirements: ['Adobe InDesign 2022 or newer', 'OpenAI API key'] 101 | } 102 | } 103 | }; 104 | 105 | return manifest; 106 | } 107 | 108 | /** 109 | * Create binary distribution info 110 | */ 111 | async function createBinaryInfo() { 112 | const version = getVersion(); 113 | 114 | const binaryInfo = { 115 | name: 'Lorem Chatum for Adobe InDesign', 116 | version: version, 117 | type: 'javascript-addon', 118 | target: 'adobe-indesign', 119 | supported_versions: { 120 | 'indesign-2023+': { 121 | script: 'Lorem-Chatum-v2.idjs', 122 | engine: 'UXP JavaScript', 123 | features: ['async-await', 'fetch-api', 'modern-dialogs'] 124 | }, 125 | 'indesign-2022-': { 126 | script: 'Lorem-Chatum-v1.jsx', 127 | engine: 'ExtendScript', 128 | features: ['legacy-dialogs', 'restix-http'] 129 | } 130 | }, 131 | platforms: { 132 | 'windows': { 133 | supported: true, 134 | installer: 'install-Win.bat', 135 | requirements: ['Windows 10+', 'Adobe InDesign'] 136 | }, 137 | 'macos': { 138 | supported: true, 139 | installer: 'install-Mac.command', 140 | requirements: ['macOS 10.14+', 'Adobe InDesign'] 141 | }, 142 | 'linux': { 143 | supported: false, 144 | reason: 'Adobe InDesign not available on Linux' 145 | } 146 | }, 147 | dependencies: { 148 | runtime: ['OpenAI API access'], 149 | development: ['Node.js 16+', 'npm'] 150 | } 151 | }; 152 | 153 | return binaryInfo; 154 | } 155 | 156 | /** 157 | * Generate installation scripts 158 | */ 159 | async function generateInstallationScripts() { 160 | const version = getVersion(); 161 | 162 | // PowerShell installer for Windows 163 | const powershellInstaller = `# Lorem Chatum v${version} - PowerShell Installer 164 | # This script installs Lorem Chatum for Adobe InDesign 165 | 166 | param( 167 | [Parameter(Mandatory=$true)] 168 | [string]$ApiKey, 169 | 170 | [Parameter(Mandatory=$false)] 171 | [string]$InDesignVersion = "auto" 172 | ) 173 | 174 | Write-Host "Lorem Chatum v${version} Installer" -ForegroundColor Green 175 | Write-Host "=================================" -ForegroundColor Green 176 | 177 | # Validate API key format 178 | if (-not $ApiKey.StartsWith("sk-")) { 179 | Write-Error "Invalid API key format. Must start with 'sk-'" 180 | exit 1 181 | } 182 | 183 | # Find InDesign installation 184 | $indesignPath = "$env:USERPROFILE\\AppData\\Roaming\\Adobe\\InDesign" 185 | if (-not (Test-Path $indesignPath)) { 186 | Write-Error "Adobe InDesign not found. Please install InDesign first." 187 | exit 1 188 | } 189 | 190 | # Find latest version 191 | $versions = Get-ChildItem -Path $indesignPath -Directory | Where-Object { $_.Name -like "Version*" } | Sort-Object Name -Descending 192 | if ($versions.Count -eq 0) { 193 | Write-Error "No InDesign versions found" 194 | exit 1 195 | } 196 | 197 | $latestVersion = $versions[0] 198 | Write-Host "Found InDesign version: $($latestVersion.Name)" -ForegroundColor Yellow 199 | 200 | # Find Scripts Panel folder 201 | $scriptsPath = Join-Path $latestVersion.FullName "en_US\\Scripts\\Scripts Panel" 202 | if (-not (Test-Path $scriptsPath)) { 203 | Write-Error "Scripts Panel folder not found at: $scriptsPath" 204 | exit 1 205 | } 206 | 207 | # Install scripts 208 | $scriptV2 = "Lorem-Chatum-v2.idjs" 209 | $scriptV1 = "Lorem-Chatum-v1.jsx" 210 | 211 | # Copy and modify v2 script 212 | if (Test-Path $scriptV2) { 213 | $content = Get-Content $scriptV2 -Raw 214 | $content = $content -replace 'const OPENAI_API_KEY = "sk-";', "const OPENAI_API_KEY = \`"$ApiKey\`";" 215 | $targetPath = Join-Path $scriptsPath $scriptV2 216 | Set-Content -Path $targetPath -Value $content 217 | Write-Host "Installed: $scriptV2" -ForegroundColor Green 218 | } 219 | 220 | # Copy and modify v1 script 221 | if (Test-Path $scriptV1) { 222 | $content = Get-Content $scriptV1 -Raw 223 | $content = $content -replace "const OPENAI_API_KEY = 'sk-';", "const OPENAI_API_KEY = '$ApiKey';" 224 | $targetPath = Join-Path $scriptsPath $scriptV1 225 | Set-Content -Path $targetPath -Value $content 226 | Write-Host "Installed: $scriptV1" -ForegroundColor Green 227 | } 228 | 229 | Write-Host "Installation completed successfully!" -ForegroundColor Green 230 | Write-Host "Please restart Adobe InDesign if it's currently running." -ForegroundColor Yellow 231 | `; 232 | 233 | // Bash installer for macOS/Linux 234 | const bashInstaller = `#!/bin/bash 235 | # Lorem Chatum v${version} - Bash Installer 236 | # This script installs Lorem Chatum for Adobe InDesign 237 | 238 | set -e 239 | 240 | SCRIPT_DIR="$(cd "$(dirname "\${BASH_SOURCE[0]}")" && pwd)" 241 | API_KEY="" 242 | INDESIGN_VERSION="auto" 243 | 244 | echo "Lorem Chatum v${version} Installer" 245 | echo "=================================" 246 | 247 | # Parse command line arguments 248 | while [[ $# -gt 0 ]]; do 249 | case $1 in 250 | --api-key) 251 | API_KEY="$2" 252 | shift 2 253 | ;; 254 | --indesign-version) 255 | INDESIGN_VERSION="$2" 256 | shift 2 257 | ;; 258 | -h|--help) 259 | echo "Usage: $0 --api-key [--indesign-version ]" 260 | echo " --api-key: Your OpenAI API key (required)" 261 | echo " --indesign-version: Specific InDesign version (optional)" 262 | exit 0 263 | ;; 264 | *) 265 | echo "Unknown option: $1" 266 | exit 1 267 | ;; 268 | esac 269 | done 270 | 271 | # Check if API key is provided 272 | if [[ -z "$API_KEY" ]]; then 273 | echo "Error: API key is required" 274 | echo "Usage: $0 --api-key " 275 | exit 1 276 | fi 277 | 278 | # Validate API key format 279 | if [[ ! "$API_KEY" =~ ^sk- ]]; then 280 | echo "Error: Invalid API key format. Must start with 'sk-'" 281 | exit 1 282 | fi 283 | 284 | # Find InDesign installation 285 | INDESIGN_BASE="$HOME/Library/Preferences/Adobe InDesign" 286 | if [[ ! -d "$INDESIGN_BASE" ]]; then 287 | echo "Error: Adobe InDesign not found. Please install InDesign first." 288 | exit 1 289 | fi 290 | 291 | # Find latest version 292 | LATEST_VERSION=$(ls -1 "$INDESIGN_BASE" | grep "Version" | sort -V | tail -1) 293 | if [[ -z "$LATEST_VERSION" ]]; then 294 | echo "Error: No InDesign versions found" 295 | exit 1 296 | fi 297 | 298 | echo "Found InDesign version: $LATEST_VERSION" 299 | 300 | # Find Scripts Panel folder 301 | SCRIPTS_PATH="$INDESIGN_BASE/$LATEST_VERSION/en_US/Scripts/Scripts Panel" 302 | if [[ ! -d "$SCRIPTS_PATH" ]]; then 303 | echo "Error: Scripts Panel folder not found at: $SCRIPTS_PATH" 304 | exit 1 305 | fi 306 | 307 | # Install scripts 308 | SCRIPT_V2="Lorem-Chatum-v2.idjs" 309 | SCRIPT_V1="Lorem-Chatum-v1.jsx" 310 | 311 | # Copy and modify v2 script 312 | if [[ -f "$SCRIPT_V2" ]]; then 313 | sed "s/const OPENAI_API_KEY = \\"sk-\\";/const OPENAI_API_KEY = \\"$API_KEY\\";/" "$SCRIPT_V2" > "$SCRIPTS_PATH/$SCRIPT_V2" 314 | echo "Installed: $SCRIPT_V2" 315 | fi 316 | 317 | # Copy and modify v1 script 318 | if [[ -f "$SCRIPT_V1" ]]; then 319 | sed "s/const OPENAI_API_KEY = 'sk-';/const OPENAI_API_KEY = '$API_KEY';/" "$SCRIPT_V1" > "$SCRIPTS_PATH/$SCRIPT_V1" 320 | echo "Installed: $SCRIPT_V1" 321 | fi 322 | 323 | echo "Installation completed successfully!" 324 | echo "Please restart Adobe InDesign if it's currently running." 325 | `; 326 | 327 | return { 328 | powershell: powershellInstaller, 329 | bash: bashInstaller 330 | }; 331 | } 332 | 333 | /** 334 | * Main function to build artifacts 335 | */ 336 | async function buildArtifacts() { 337 | console.log('Building release artifacts...'); 338 | 339 | try { 340 | await fs.ensureDir(ARTIFACTS_DIR); 341 | 342 | // Generate metadata 343 | const metadata = await generateArtifactMetadata(); 344 | await fs.writeFile( 345 | path.join(ARTIFACTS_DIR, 'metadata.json'), 346 | JSON.stringify(metadata, null, 2) 347 | ); 348 | 349 | // Create release manifest 350 | const manifest = await createReleaseManifest(); 351 | await fs.writeFile( 352 | path.join(ARTIFACTS_DIR, 'release-manifest.json'), 353 | JSON.stringify(manifest, null, 2) 354 | ); 355 | 356 | // Create binary info 357 | const binaryInfo = await createBinaryInfo(); 358 | await fs.writeFile( 359 | path.join(ARTIFACTS_DIR, 'binary-info.json'), 360 | JSON.stringify(binaryInfo, null, 2) 361 | ); 362 | 363 | // Generate installation scripts 364 | const installScripts = await generateInstallationScripts(); 365 | await fs.writeFile( 366 | path.join(ARTIFACTS_DIR, 'install.ps1'), 367 | installScripts.powershell 368 | ); 369 | await fs.writeFile( 370 | path.join(ARTIFACTS_DIR, 'install.sh'), 371 | installScripts.bash 372 | ); 373 | 374 | // Make bash script executable 375 | await fs.chmod(path.join(ARTIFACTS_DIR, 'install.sh'), '755'); 376 | 377 | // Create SBOM (Software Bill of Materials) 378 | const packageJson = JSON.parse(await fs.readFile(path.join(__dirname, '../package.json'), 'utf8')); 379 | const sbom = { 380 | name: packageJson.name, 381 | version: packageJson.version, 382 | description: packageJson.description, 383 | license: packageJson.license, 384 | author: packageJson.author, 385 | dependencies: packageJson.devDependencies || {}, 386 | generated: new Date().toISOString() 387 | }; 388 | 389 | await fs.writeFile( 390 | path.join(ARTIFACTS_DIR, 'sbom.json'), 391 | JSON.stringify(sbom, null, 2) 392 | ); 393 | 394 | console.log('✅ Release artifacts created successfully!'); 395 | console.log('Generated files:'); 396 | console.log(' - metadata.json'); 397 | console.log(' - release-manifest.json'); 398 | console.log(' - binary-info.json'); 399 | console.log(' - install.ps1'); 400 | console.log(' - install.sh'); 401 | console.log(' - sbom.json'); 402 | 403 | } catch (error) { 404 | console.error('❌ Artifact generation failed:', error); 405 | process.exit(1); 406 | } 407 | } 408 | 409 | if (require.main === module) { 410 | buildArtifacts(); 411 | } 412 | 413 | module.exports = { buildArtifacts, generateArtifactMetadata, createReleaseManifest }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # _Lorem Chatum_ for Adobe InDesign 2 | 3 | **Generate contextually-aware placeholder text in Adobe InDesign using the power of ChatGPT.** 4 | 5 | ![_Lorem Chatum_ for Adobe InDesign](./documentation/lorem-chatum.gif) 6 | 7 | _Lorem Chatum_ is a script for Adobe InDesign that revolutionizes the way you create placeholder text. Instead of traditional static _lorem ipsum_, it leverages OpenAI's ChatGPT (specifically the `gpt-3.5-turbo` model) to generate multilingual, contextually relevant text. This helps you create more realistic and visually cohesive design mockups. 8 | 9 | ## What it Does 10 | 11 | _Lorem Chatum_ offers two primary functionalities: 12 | 13 | 1. **Fill Empty Text Frames:** If you select an empty text frame, the script analyzes other text content on the current InDesign page to understand the context. It then prompts ChatGPT to generate new text that fits this context and the selected frame's language. 14 | 2. **Extend Existing Text:** If you select a text frame that already contains text, _Lorem Chatum_ uses that existing text as a starting point and asks ChatGPT to continue writing, effectively extending your current content in the same style and language. 15 | 16 | The amount of text generated is intelligently estimated based on the selected text frame's size and its primary font size. 17 | 18 | ## Who It's For 19 | 20 | This tool is designed for: 21 | 22 | * Graphic Designers 23 | * Layout Artists 24 | * UI/UX Designers working with print or digital layouts in InDesign 25 | * Anyone who frequently uses placeholder text and desires something more dynamic and representative than standard _lorem ipsum_. 26 | 27 | ## Why It's Useful 28 | 29 | * **Contextual Relevance:** Generates placeholder text that aligns with the existing content on your page, making mockups look more realistic. 30 | * **Multilingual Capabilities:** Supports any language that ChatGPT can handle. Simply set the desired language in InDesign's **Character** panel for the selected text frame. 31 | * **Improved Design Process:** Helps visualize final layouts more accurately. 32 | * **Cost-Effective:** While using the OpenAI API is a paid service, it's generally inexpensive for text generation. For example, processing a volume equivalent to Leo Tolstoy’s "War and Peace" (over 1,200 pages, 780k tokens) with the `gpt-3.5-turbo` model would cost approximately US$3. *(Note: GPT-4 models are significantly more expensive).* 33 | 34 | ## OpenAI API Key Requirement 35 | 36 | To use _Lorem Chatum_, you **must** have your own OpenAI API secret key. 37 | 38 | 1. **Create an Account:** If you don't have one, sign up at [OpenAI](https://platform.openai.com/). 39 | 2. **Generate a Secret Key:** Navigate to the [API keys section](https://platform.openai.com/account/api-keys) in your OpenAI account settings and create a new secret key. It will look something like `sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`. 40 | 3. **Billing:** You'll also need to set up billing information in your OpenAI account. New accounts often come with some free credits, but sustained use will incur charges based on the amount of text processed (tokens). 41 | 42 | This key will be added to the _Lorem Chatum_ script file during installation. 43 | 44 | ## Installation 45 | 46 | First, download the latest version of the script: 47 | 48 | ➡️ **[Download _Lorem Chatum_ (main.zip)](https://github.com/twardoch/lorem-chatum-for-indesign/archive/refs/heads/main.zip)** 49 | 50 | After downloading, unzip the `lorem-chatum-for-indesign-main.zip` file and navigate into the unzipped `lorem-chatum-for-indesign-main` folder. The installation steps vary depending on your Adobe InDesign version. 51 | 52 | ### v2 for Adobe InDesign 2023 and Newer (Recommended) 53 | 54 | This version uses modern UXP JavaScript and is the actively developed version. 55 | * **License:** [Apache 2.0 License](src/v2-indesign-2023-and-newer/LICENSE.txt) 56 | 57 | The `src/v2-indesign-2023-and-newer/` folder contains the script `Lorem-Chatum-v2.idjs` and installers. 58 | 59 | **Using Installers (Easiest Method):** 60 | 61 | 1. Have your OpenAI API secret key ready (copied to your clipboard). 62 | 2. **On macOS:** 63 | * Navigate to the `src/v2-indesign-2023-and-newer/` folder. 64 | * Double-click the `install-Mac.command` file. 65 | * A terminal window will open and prompt you to paste your OpenAI API key. Paste it and press Enter. 66 | * The script will be automatically installed. 67 | 3. **On Windows:** 68 | * Navigate to the `src/v2-indesign-2023-and-newer/` folder. 69 | * Double-click the `install-Win.bat` file. 70 | * A command prompt window will open and prompt you to paste your OpenAI API key. Paste it and press Enter. 71 | * The script will be automatically installed. 72 | 73 | **Manual Installation (v2):** 74 | 75 | 1. Open `src/v2-indesign-2023-and-newer/Lorem-Chatum-v2.idjs` in a plain text editor (like VS Code, Sublime Text, or even Notepad/TextEdit). 76 | 2. Locate the line: 77 | ```javascript 78 | const OPENAI_API_KEY = "sk-"; 79 | ``` 80 | 3. Replace `"sk-"` with your actual OpenAI API secret key, keeping the quotes: 81 | ```javascript 82 | const OPENAI_API_KEY = "sk-yourActualOpenAIKeyGoesHere"; 83 | ``` 84 | 4. Save the file. 85 | 5. Copy the modified `Lorem-Chatum-v2.idjs` file to your InDesign Scripts Panel folder. Common locations: 86 | * **macOS:** `~/Library/Preferences/Adobe InDesign/Version X.X/en_US/Scripts/Scripts Panel/` (replace `Version X.X` and `en_US` with your version and language). 87 | * **Windows:** `%USERPROFILE%\AppData\Roaming\Adobe\InDesign\Version X.X\en_US\Scripts\Scripts Panel\` (replace `Version X.X` and `en_US` with your version and language). 88 | * You can also find this folder by opening InDesign, going to `Window > Utilities > Scripts`, right-clicking on the "User" folder in the Scripts panel, and selecting "Reveal in Finder" (macOS) or "Reveal in Explorer" (Windows). 89 | 90 | ### v1 for Adobe InDesign 2022 and Older (Legacy) 91 | 92 | This version uses the older ExtendScript and is considered legacy. 93 | * **License:** [GNU General Public License v3.0](src/v1-indesign-2022-and-older/LICENSE.txt) (due to a dependency). 94 | 95 | **Manual Installation (v1):** 96 | 97 | 1. Open `src/v1-indesign-2022-and-older/Lorem-Chatum-v1.jsx` in a plain text editor. 98 | 2. Locate the line: 99 | ```javascript 100 | const OPENAI_API_KEY = 'sk-'; 101 | ``` 102 | 3. Replace `'sk-'` with your actual OpenAI API secret key, keeping the quotes: 103 | ```javascript 104 | const OPENAI_API_KEY = 'sk-yourActualOpenAIKeyGoesHere'; 105 | ``` 106 | 4. Save the file. 107 | 5. Copy the modified `Lorem-Chatum-v1.jsx` file to your InDesign Scripts Panel folder (see locations mentioned in the v2 manual installation section). 108 | 109 | ## Usage 110 | 111 | Once installed (and after restarting InDesign if it was running during installation): 112 | 113 | 1. Open Adobe InDesign. 114 | 2. Go to **Window > Utilities > Scripts**. This will open the Scripts panel. 115 | 3. In the Scripts panel, expand the **User** section. You should see `Lorem-Chatum-v2.idjs` or `Lorem-Chatum-v1.jsx` listed. 116 | 117 | **Scenario 1: Filling an Empty Text Frame** 118 | 119 | 1. Ensure you have some other text frames on your current page that contain text. This text will provide context. 120 | 2. Create a new, empty text frame where you want the generated text. 121 | 3. Select the empty text frame with the **Selection Tool** (the black arrow). 122 | 4. **Important:** Set the desired language for the generated text. Select the text frame, then go to the **Character** panel (`Window > Type & Tables > Character`) and choose the language from the language dropdown menu. 123 | 5. In the Scripts panel, double-click the `Lorem-Chatum` script. 124 | 6. A progress indicator may appear. The script will: 125 | * Gather text from other frames on the current page (up to about 500 words). 126 | * Estimate the required length based on the frame size. 127 | * Send this context to ChatGPT, asking it to generate text in the specified language. 128 | * Place the generated text into your selected empty frame. 129 | 130 | **Scenario 2: Extending Existing Text in a Frame** 131 | 132 | 1. Select a text frame that already contains some text. 133 | 2. **Important:** Ensure the language of the existing text (and the desired language for continuation) is set correctly in the **Character** panel. 134 | 3. In the Scripts panel, double-click the `Lorem-Chatum` script. 135 | 4. The script will: 136 | * Take the existing text from the selected frame. 137 | * Estimate how much more text is needed to fill the frame. 138 | * Send the existing text to ChatGPT, asking it to continue writing in the same style and language. 139 | * Append the generated text to the existing content in the frame. 140 | 141 | You can repeat the process on the same frame. If you want more text in a frame that was filled, simply make the text frame larger and run the script again on that frame. 142 | 143 | ## Caveats 144 | 145 | * **Believability:** The text generated by _Lorem Chatum_ can be very authentic and believable. If you're mixing it with real content, ensure you have a system to distinguish placeholder text from final copy. 146 | * **Fact-Checking:** As with all AI-generated content, do not assume the text is factually accurate or ready for publication without review. It's for placeholder and layout purposes. 147 | * **API Costs:** While generally low, monitor your OpenAI API usage and associated costs, especially if using the script extensively. 148 | 149 | --- 150 | 151 | ## Technical Details 152 | 153 | This section delves into the inner workings of _Lorem Chatum_ and provides guidelines for contributors. 154 | 155 | ### How the Code Works 156 | 157 | While v1 (ExtendScript) and v2 (UXP) are implemented differently due to their respective environments, the core logic for interacting with InDesign and OpenAI is conceptually similar. 158 | 159 | **Core Logic (Conceptual):** 160 | 161 | 1. **Document & Selection Validation:** 162 | * Checks if a document is open. 163 | * Verifies that a single text frame is selected. 164 | * Displays an alert if these conditions aren't met. 165 | 166 | 2. **Context Acquisition:** 167 | * **Empty Text Frame:** If the selected frame `contents` is empty, the script iterates through all other text frames on the `activePage`. It concatenates their contents to form a context string. This context is capped at approximately the first 500 words to stay within reasonable limits for the OpenAI prompt. 168 | * **Non-Empty Text Frame:** If the selected frame already contains text, its `contents` are used directly as the prompt for OpenAI. 169 | 170 | 3. **Language Determination:** 171 | * The script reads the language applied to the first character (or the whole text if uniform) of the selected text frame: `textFrame.texts[0].appliedLanguage.name`. This name (e.g., "English: USA", "Polski") is parsed to extract the base language name (e.g., "English", "Polish") which is then sent to ChatGPT. 172 | 173 | 4. **Token Estimation for OpenAI API:** 174 | * To tell ChatGPT roughly how much text to generate, the script estimates the capacity of the selected text frame. This is a heuristic based on: 175 | * The frame's geometric bounds (width and height). 176 | * The point size of the text (`textFrame.texts[0].pointSize`). 177 | * An average character width (approximated as `fontSize * 0.6`). 178 | * An average line height (approximated as `fontSize * 1.2`). 179 | * From these, it estimates the number of characters the frame can hold. This character count is then used as a loose proxy for `max_tokens`. 180 | * The final `max_tokens` sent to the API is capped (e.g., at 4095 for `gpt-3.5-turbo`) to prevent errors and excessive costs. *Note: This estimation is approximate and primarily guides the length of the AI's response.* 181 | 182 | 5. **OpenAI API Interaction (`gpt-3.5-turbo` model):** 183 | * The script makes a POST request to `https://api.openai.com/v1/chat/completions`. 184 | * **System Prompt:** A directive is sent to guide the AI's behavior: 185 | ``` 186 | "Write an essay in [lang], to the max length, by continuing the prompt. Do not ask anything, do not add anything that is not requested." 187 | ``` 188 | where `[lang]` is the determined language. 189 | * **User Prompt:** The acquired context (from page or frame) is sent as the user's message. 190 | * **Key API Parameters Used:** 191 | * `model`: "gpt-3.5-turbo" 192 | * `messages`: Array containing the system and user prompts. 193 | * `temperature`: `1` (for creative responses). 194 | * `max_tokens`: The estimated number of tokens. 195 | * `top_p`: `1`. 196 | * `n`: `1` (requesting a single completion). 197 | * `frequency_penalty`: `0`. 198 | * `presence_penalty`: `0`. 199 | 200 | 6. **Text Insertion:** 201 | * The `content` from ChatGPT's response (`responseData.choices[0].message.content`) is retrieved. 202 | * A leading space is typically added, and any leading newline is removed. 203 | * This generated text is appended to the `contents` of the selected InDesign text frame. 204 | 205 | **Version-Specific Implementations:** 206 | 207 | * **v2 (`Lorem-Chatum-v2.idjs` - UXP for InDesign 2023+)** 208 | * **Technology:** Modern ECMAScript 6+ (ES6+) JavaScript, running in Adobe's UXP (Unified Extensibility Platform) environment. 209 | * **API Calls:** Uses the native `fetch` API for HTTPS requests to the OpenAI endpoint. 210 | ```javascript 211 | let response = await fetch('https://api.openai.com/v1/chat/completions', { /* ...options... */ }); 212 | ``` 213 | * **JSON Handling:** Uses native `JSON.stringify()` to prepare the request body and `await response.json()` to parse the OpenAI API's JSON response. 214 | * **User Interface (UI):** 215 | * Dialogs for alerts and progress messages are created dynamically using UXP's DOM-like APIs (`document.createElement("dialog")`) and Spectrum UXP components (``, ``, ``). 216 | ```javascript 217 | const dialog = document.createElement("dialog"); 218 | dialog.innerHTML = \`...\`; // Spectrum UXP components 219 | document.body.appendChild(dialog); 220 | dialog.showModal(); 221 | // dialog.close(); 222 | ``` 223 | * The script detects InDesign's UI brightness (`app.generalPreferences.uiBrightnessPreference`) to set dialog text color (black/white) for better visibility. 224 | * **Measurement Units:** Before performing geometric calculations for token estimation, the script temporarily sets the document's `horizontalMeasurementUnits`, `verticalMeasurementUnits`, `typographicMeasurementUnits`, and `textSizeMeasurementUnits` to `MeasurementUnits.points`. Original settings are restored afterwards. 225 | * **Installers:** 226 | * `install-Mac.command`: A Python 3 script. It interactively prompts for the OpenAI API key. It locates the latest InDesign version's Scripts Panel folder (e.g., `~/Library/Preferences/Adobe InDesign/Version X.X/en_US/Scripts/Scripts Panel/`) by scanning directories and sorting by version number. It then reads the `Lorem-Chatum-v2.idjs` template, replaces the placeholder API key, and writes the new file to the target Scripts Panel folder. 227 | * `install-Win.bat`: A Windows Batch script. It also prompts for the API key. It finds the latest InDesign version folder in `%USERPROFILE%\AppData\Roaming\Adobe\InDesign\`. It copies `Lorem-Chatum-v2.idjs` to the target Scripts Panel folder and then uses a `for` loop with `find /n /v ""` to read the script line by line, replacing the API key placeholder, and writing to a temporary file, which then replaces the original. 228 | 229 | * **v1 (`Lorem-Chatum-v1.jsx` - ExtendScript for InDesign 2022 and older)** 230 | * **Technology:** Legacy ExtendScript (a JavaScript ES3 dialect). 231 | * **API Calls:** Relies on the embedded `restix.jsx` library by Gregor Fellenz. `Restix` acts as a bridge, using VBScript (`MSXML2.ServerXMLHTTP.6.0` or `ADODB.Stream`) on Windows and AppleScript (wrapping `curl`) on macOS to perform the actual HTTPS request to OpenAI. 232 | * **JSON Handling:** Uses the embedded `json.jsx` library by Marc Autret. This provides `JSON.lave()` (similar to `JSON.stringify()`) and `JSON.eval()` (similar to `JSON.parse()`, but using `eval()`) for constructing the request body and parsing the response. 233 | * **User Interface (UI):** Uses standard ExtendScript `alert()` for messages. No progress dialog. 234 | 235 | **API Key Management:** 236 | 237 | * In both versions, the OpenAI API key is stored directly as a string constant within the script file (`OPENAI_API_KEY = "sk-..."`). 238 | * The installer scripts for v2 automate the process of writing this key into the script. For v1 or manual v2 installation, the user must edit the script file directly. 239 | * **Security Note:** Storing API keys directly in client-side scripts is generally not recommended for web applications. However, in the context of a local InDesign script run by the user, it's a pragmatic approach for ease of setup. Users should still protect their API keys. 240 | 241 | ### Coding and Contributing 242 | 243 | We welcome contributions to _Lorem Chatum_, especially for the v2 (UXP) version! 244 | 245 | **Project Structure:** 246 | 247 | * `src/v1-indesign-2022-and-older/`: Contains the legacy ExtendScript version (`.jsx`). 248 | * `src/v2-indesign-2023-and-newer/`: Contains the modern UXP JavaScript version (`.idjs`) and its installers. 249 | * `documentation/`: Contains assets like the demo GIF. 250 | 251 | **v2 (Adobe InDesign 2023 and newer - Active Development):** 252 | 253 | * This is the primary version for future development and improvements. 254 | * **License:** [Apache 2.0 License](src/v2-indesign-2023-and-newer/LICENSE.txt). 255 | * **Contributions:** 256 | * Please submit Pull Requests to the `main` branch. 257 | * Try to follow the existing coding style and patterns. 258 | * Ensure your changes work reliably in recent versions of InDesign (2023+). 259 | * **Development Tips:** 260 | * Familiarize yourself with Adobe UXP: [InDesign UXP Documentation](https://developer.adobe.com/indesign/uxp/). 261 | * The UXP Developer Tool can be helpful for debugging. 262 | * Modern JavaScript (ES6+) features can be used. 263 | 264 | **v1 (Adobe InDesign 2022 and older - Legacy):** 265 | 266 | * This version is considered "end-of-life" and is not planned for active development. It is provided for users of older InDesign versions. 267 | * **License:** [GNU General Public License v3.0](src/v1-indesign-2022-and-older/LICENSE.txt). This is due to its dependency on `Restix.jsx`, which is GPLv3 licensed. The `json.jsx` polyfill is MIT licensed. 268 | 269 | **Future Ideas (Contributions Welcome!):** 270 | 271 | The original author (Adam Twardoch, with help from ChatGPT-4 for v1) envisioned several potential enhancements: 272 | 273 | * [ ] **UXP Plugin:** Convert the v2 script into a full UXP plugin for better integration and potential panel UI. 274 | * [ ] **Improved UI:** Develop a more interactive UXP dialog/panel for settings (e.g., selecting different OpenAI models, adjusting temperature, choosing prompt styles). 275 | * [ ] **Secure API Key Storage:** If developed as a UXP plugin, explore UXP's [SecureStorage](https://developer.adobe.com/xd/uxp/uxp/reference-js/Modules/uxp/Key-Value%20Storage/SecureStorage/) for storing the OpenAI API key more securely than plain text in the script. 276 | * [ ] **More Prompting Types:** Allow users to select different styles of text generation (e.g., "more formal," "more creative," "bullet points"). 277 | * [ ] **Improved Token Estimation:** Refine the logic for estimating the number of tokens to better match the frame's capacity. 278 | * [ ] **Translation Functionality:** Add a feature where if two frames are selected (one with source text, one empty target frame), the script translates the text. 279 | * [ ] **Summarization/Shortening:** Add functionality to shorten or summarize text within a frame to resolve overflows. 280 | 281 | ### Author and Acknowledgements 282 | 283 | * **Author:** Adam Twardoch 284 | * The initial version (v1, ExtendScript) was written with significant assistance from ChatGPT-4. 285 | * **v1 Dependencies:** 286 | * JSON processing: [standalone JSON](https://github.com/indiscripts/extendscript/tree/master/JSON) code by Marc Autret (MIT License). 287 | * HTTPS API calls: [Restix](https://github.com/grefel/restix/blob/master/restix.jsx) code by Gregor Fellenz (GNU GPL v3.0). 288 | --- 289 | 290 | *The original README included some taglines and scenarios written by ChatGPT. These have been omitted in this version for brevity but can be found in the project's commit history if desired.* 291 | *The section "A few words about writing code together with ChatGPT" from the original README has also been omitted here but can be found in the commit history.* 292 | -------------------------------------------------------------------------------- /src/v1-indesign-2022-and-older/LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------