or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-lifecycle.mdcore-ipc.mdevents.mdindex.mdmenu-system.mdsystem-integration.mdtesting.mdutilities.mdwindow-management.md

utilities.mddocs/

0

# Utilities

1

2

Cross-platform utilities for path handling, image processing, device pixel calculations, and platform abstraction to ensure consistent behavior across different operating systems.

3

4

## Capabilities

5

6

### Path Utilities

7

8

Cross-platform path manipulation and directory resolution with support for all major operating systems.

9

10

```typescript { .api }

11

/**

12

* Get platform-specific path separator

13

* @returns Path separator ('/' on Unix, '\' on Windows)

14

*/

15

function sep(): Promise<string>;

16

17

/**

18

* Get platform-specific PATH environment variable delimiter

19

* @returns Delimiter (';' on Windows, ':' on Unix)

20

*/

21

function delimiter(): Promise<string>;

22

23

/**

24

* Resolve an absolute path from path segments

25

* @param paths - Path segments to resolve

26

* @returns Absolute path

27

*/

28

function resolve(...paths: string[]): Promise<string>;

29

30

/**

31

* Normalize a path by resolving '..' and '.' segments

32

* @param path - Path to normalize

33

* @returns Normalized path

34

*/

35

function normalize(path: string): Promise<string>;

36

37

/**

38

* Join path segments using platform-specific separator

39

* @param paths - Path segments to join

40

* @returns Joined path

41

*/

42

function join(...paths: string[]): Promise<string>;

43

44

/**

45

* Get directory name of a path

46

* @param path - File path

47

* @returns Directory containing the file

48

*/

49

function dirname(path: string): Promise<string>;

50

51

/**

52

* Get file extension from a path

53

* @param path - File path

54

* @returns Extension including the dot (e.g., '.txt')

55

*/

56

function extname(path: string): Promise<string>;

57

58

/**

59

* Get base filename from a path

60

* @param path - File path

61

* @param ext - Optional extension to remove from result

62

* @returns Base filename

63

*/

64

function basename(path: string, ext?: string): Promise<string>;

65

66

/**

67

* Check if a path is absolute

68

* @param path - Path to check

69

* @returns true if path is absolute

70

*/

71

function isAbsolute(path: string): Promise<boolean>;

72

73

/**

74

* Resolve bundled resource path to absolute path

75

* @param resourcePath - Relative path to resource in bundle

76

* @returns Absolute path to resource

77

*/

78

function resolveResource(resourcePath: string): Promise<string>;

79

```

80

81

### Directory Resolution

82

83

Get standard system and application-specific directories across platforms.

84

85

```typescript { .api }

86

/**

87

* User's home directory

88

* @returns Path to user's home directory

89

*/

90

function homeDir(): Promise<string>;

91

92

/**

93

* User's audio/music directory

94

* @returns Path to audio directory

95

*/

96

function audioDir(): Promise<string>;

97

98

/**

99

* User's cache directory

100

* @returns Path to cache directory

101

*/

102

function cacheDir(): Promise<string>;

103

104

/**

105

* User's configuration directory

106

* @returns Path to config directory

107

*/

108

function configDir(): Promise<string>;

109

110

/**

111

* User's data directory

112

* @returns Path to data directory

113

*/

114

function dataDir(): Promise<string>;

115

116

/**

117

* User's local data directory

118

* @returns Path to local data directory

119

*/

120

function localDataDir(): Promise<string>;

121

122

/**

123

* User's desktop directory

124

* @returns Path to desktop directory

125

*/

126

function desktopDir(): Promise<string>;

127

128

/**

129

* User's documents directory

130

* @returns Path to documents directory

131

*/

132

function documentDir(): Promise<string>;

133

134

/**

135

* User's downloads directory

136

* @returns Path to downloads directory

137

*/

138

function downloadDir(): Promise<string>;

139

140

/**

141

* Current executable's directory

142

* @returns Path to directory containing executable

143

*/

144

function executableDir(): Promise<string>;

145

146

/**

147

* System fonts directory

148

* @returns Path to fonts directory

149

*/

150

function fontDir(): Promise<string>;

151

152

/**

153

* User's pictures directory

154

* @returns Path to pictures directory

155

*/

156

function pictureDir(): Promise<string>;

157

158

/**

159

* User's public directory

160

* @returns Path to public directory

161

*/

162

function publicDir(): Promise<string>;

163

164

/**

165

* Application resources directory

166

* @returns Path to bundled resources

167

*/

168

function resourceDir(): Promise<string>;

169

170

/**

171

* Runtime directory for temporary files

172

* @returns Path to runtime directory

173

*/

174

function runtimeDir(): Promise<string>;

175

176

/**

177

* User's templates directory

178

* @returns Path to templates directory

179

*/

180

function templateDir(): Promise<string>;

181

182

/**

183

* User's videos directory

184

* @returns Path to videos directory

185

*/

186

function videoDir(): Promise<string>;

187

188

/**

189

* System temporary directory

190

* @returns Path to temp directory

191

*/

192

function tempDir(): Promise<string>;

193

```

194

195

### Application-Specific Directories

196

197

Directories specific to the current application for storing config, data, cache, and logs.

198

199

```typescript { .api }

200

/**

201

* Application-specific configuration directory

202

* @returns Path to app config directory

203

*/

204

function appConfigDir(): Promise<string>;

205

206

/**

207

* Application-specific data directory

208

* @returns Path to app data directory

209

*/

210

function appDataDir(): Promise<string>;

211

212

/**

213

* Application-specific local data directory

214

* @returns Path to app local data directory

215

*/

216

function appLocalDataDir(): Promise<string>;

217

218

/**

219

* Application-specific cache directory

220

* @returns Path to app cache directory

221

*/

222

function appCacheDir(): Promise<string>;

223

224

/**

225

* Application-specific log directory

226

* @returns Path to app log directory

227

*/

228

function appLogDir(): Promise<string>;

229

```

230

231

### Base Directory Enum

232

233

Enumeration of all available directory types for use with other APIs.

234

235

```typescript { .api }

236

enum BaseDirectory {

237

Audio = 'audio',

238

Cache = 'cache',

239

Config = 'config',

240

Data = 'data',

241

LocalData = 'localData',

242

Desktop = 'desktop',

243

Document = 'document',

244

Download = 'download',

245

Executable = 'executable',

246

Font = 'font',

247

Home = 'home',

248

Picture = 'picture',

249

Public = 'public',

250

Resource = 'resource',

251

Runtime = 'runtime',

252

Template = 'template',

253

Video = 'video',

254

AppConfig = 'appConfig',

255

AppData = 'appData',

256

AppLocalData = 'appLocalData',

257

AppCache = 'appCache',

258

AppLog = 'appLog',

259

Temp = 'temp'

260

}

261

```

262

263

### Image Processing

264

265

Image loading, processing, and format conversion utilities.

266

267

```typescript { .api }

268

/**

269

* Image representation with RGBA data

270

*/

271

class Image {

272

/**

273

* Create image from RGBA data

274

* @param rgba - RGBA pixel data (4 bytes per pixel)

275

* @param width - Image width in pixels

276

* @param height - Image height in pixels

277

* @returns Promise resolving to Image instance

278

*/

279

static new(rgba: number[], width: number, height: number): Promise<Image>;

280

281

/**

282

* Create image from byte array (PNG, JPEG, etc.)

283

* @param bytes - Image file bytes

284

* @returns Promise resolving to Image instance

285

*/

286

static fromBytes(bytes: number[] | Uint8Array | ArrayBuffer): Promise<Image>;

287

288

/**

289

* Load image from file path

290

* @param path - Path to image file

291

* @returns Promise resolving to Image instance

292

*/

293

static fromPath(path: string): Promise<Image>;

294

295

/**

296

* Get RGBA pixel data

297

* @returns RGBA data as Uint8Array

298

*/

299

rgba(): Promise<Uint8Array>;

300

301

/**

302

* Get image dimensions

303

* @returns Width and height in pixels

304

*/

305

size(): Promise<ImageSize>;

306

}

307

308

interface ImageSize {

309

width: number;

310

height: number;

311

}

312

313

/**

314

* Transform image data for different contexts

315

* @param image - Image in various formats

316

* @returns Transformed image data

317

*/

318

function transformImage<T>(image: string | Image | Uint8Array | ArrayBuffer | number[] | null): T;

319

```

320

321

### Device Pixel Interface (DPI)

322

323

Handle device pixel scaling and convert between logical and physical coordinates.

324

325

```typescript { .api }

326

/**

327

* Size in logical (device-independent) pixels

328

*/

329

class LogicalSize {

330

/**

331

* Create logical size

332

* @param width - Width in logical pixels

333

* @param height - Height in logical pixels

334

*/

335

constructor(width: number, height: number);

336

337

/**

338

* Convert to physical pixels

339

* @param scaleFactor - Device scale factor

340

* @returns Equivalent size in physical pixels

341

*/

342

toPhysical(scaleFactor: number): PhysicalSize;

343

}

344

345

/**

346

* Size in physical (actual screen) pixels

347

*/

348

class PhysicalSize {

349

/**

350

* Create physical size

351

* @param width - Width in physical pixels

352

* @param height - Height in physical pixels

353

*/

354

constructor(width: number, height: number);

355

356

/**

357

* Convert to logical pixels

358

* @param scaleFactor - Device scale factor

359

* @returns Equivalent size in logical pixels

360

*/

361

toLogical(scaleFactor: number): LogicalSize;

362

}

363

364

/**

365

* Union wrapper for size that can be either logical or physical

366

*/

367

class Size {

368

/**

369

* Create logical size wrapper

370

* @param width - Width in logical pixels

371

* @param height - Height in logical pixels

372

* @returns Size instance wrapping LogicalSize

373

*/

374

static logical(width: number, height: number): Size;

375

376

/**

377

* Create physical size wrapper

378

* @param width - Width in physical pixels

379

* @param height - Height in physical pixels

380

* @returns Size instance wrapping PhysicalSize

381

*/

382

static physical(width: number, height: number): Size;

383

}

384

385

/**

386

* Position in logical (device-independent) pixels

387

*/

388

class LogicalPosition {

389

/**

390

* Create logical position

391

* @param x - X coordinate in logical pixels

392

* @param y - Y coordinate in logical pixels

393

*/

394

constructor(x: number, y: number);

395

396

/**

397

* Convert to physical pixels

398

* @param scaleFactor - Device scale factor

399

* @returns Equivalent position in physical pixels

400

*/

401

toPhysical(scaleFactor: number): PhysicalPosition;

402

}

403

404

/**

405

* Position in physical (actual screen) pixels

406

*/

407

class PhysicalPosition {

408

/**

409

* Create physical position

410

* @param x - X coordinate in physical pixels

411

* @param y - Y coordinate in physical pixels

412

*/

413

constructor(x: number, y: number);

414

415

/**

416

* Convert to logical pixels

417

* @param scaleFactor - Device scale factor

418

* @returns Equivalent position in logical pixels

419

*/

420

toLogical(scaleFactor: number): LogicalPosition;

421

}

422

423

/**

424

* Union wrapper for position that can be either logical or physical

425

*/

426

class Position {

427

/**

428

* Create logical position wrapper

429

* @param x - X coordinate in logical pixels

430

* @param y - Y coordinate in logical pixels

431

* @returns Position instance wrapping LogicalPosition

432

*/

433

static logical(x: number, y: number): Position;

434

435

/**

436

* Create physical position wrapper

437

* @param x - X coordinate in physical pixels

438

* @param y - Y coordinate in physical pixels

439

* @returns Position instance wrapping PhysicalPosition

440

*/

441

static physical(x: number, y: number): Position;

442

}

443

```

444

445

## Usage Examples

446

447

### Path Operations

448

449

```typescript

450

import { join, resolve, dirname, basename, extname } from '@tauri-apps/api/path';

451

452

// Join path segments

453

const configPath = await join('config', 'app.json');

454

const fullPath = await join(await homeDir(), '.myapp', 'config.toml');

455

456

// Path resolution

457

const absolutePath = await resolve('../config', 'settings.json');

458

const normalizedPath = await normalize('/path/to/../config/./app.json');

459

460

// Extract path components

461

const dir = await dirname('/path/to/file.txt'); // '/path/to'

462

const filename = await basename('/path/to/file.txt'); // 'file.txt'

463

const nameOnly = await basename('/path/to/file.txt', '.txt'); // 'file'

464

const extension = await extname('/path/to/file.txt'); // '.txt'

465

466

// Check path type

467

const isAbs = await isAbsolute('/absolute/path'); // true

468

const isRel = await isAbsolute('relative/path'); // false

469

```

470

471

### Directory Access

472

473

```typescript

474

import {

475

appDataDir,

476

appConfigDir,

477

homeDir,

478

downloadDir,

479

tempDir

480

} from '@tauri-apps/api/path';

481

482

// Application directories

483

const dataDir = await appDataDir(); // ~/.local/share/myapp on Linux

484

const configDir = await appConfigDir(); // ~/.config/myapp on Linux

485

const cacheDir = await appCacheDir(); // ~/.cache/myapp on Linux

486

487

// User directories

488

const home = await homeDir(); // /home/user on Linux

489

const downloads = await downloadDir(); // ~/Downloads

490

const temp = await tempDir(); // /tmp on Unix

491

492

// Create application directories

493

import { mkdir } from '@tauri-apps/api/fs';

494

await mkdir(await join(dataDir, 'databases'), { recursive: true });

495

await mkdir(await join(configDir, 'themes'), { recursive: true });

496

```

497

498

### Resource Path Resolution

499

500

```typescript

501

import { resolveResource, convertFileSrc } from '@tauri-apps/api/path';

502

import { convertFileSrc } from '@tauri-apps/api/core';

503

504

// Resolve bundled resource

505

const iconPath = await resolveResource('icons/app-icon.png');

506

const configPath = await resolveResource('config/default.json');

507

508

// Convert to URL for web content

509

const iconUrl = convertFileSrc(iconPath);

510

const backgroundUrl = convertFileSrc(await resolveResource('images/bg.jpg'));

511

512

// Use in HTML

513

document.getElementById('app-icon').src = iconUrl;

514

document.body.style.backgroundImage = `url(${backgroundUrl})`;

515

```

516

517

### Image Processing

518

519

```typescript

520

import { Image } from '@tauri-apps/api/image';

521

import { resolveResource } from '@tauri-apps/api/path';

522

523

// Load image from file

524

const iconPath = await resolveResource('icons/app-icon.png');

525

const icon = await Image.fromPath(iconPath);

526

527

// Get image info

528

const size = await icon.size();

529

console.log(`Icon size: ${size.width}x${size.height}`);

530

531

// Get raw pixel data

532

const rgba = await icon.rgba();

533

console.log(`Image has ${rgba.length / 4} pixels`);

534

535

// Create image from data

536

const redPixel = [255, 0, 0, 255]; // Red pixel

537

const redSquare = await Image.new(

538

Array(64 * 64 * 4).fill(0).map((_, i) => redPixel[i % 4]),

539

64,

540

64

541

);

542

543

// Load from binary data

544

const response = await fetch('/api/image');

545

const buffer = await response.arrayBuffer();

546

const image = await Image.fromBytes(buffer);

547

```

548

549

### DPI-Aware Sizing

550

551

```typescript

552

import { LogicalSize, PhysicalSize, getCurrentWindow } from '@tauri-apps/api/window';

553

554

// Get current window

555

const window = getCurrentWindow();

556

557

// Work with logical coordinates (DPI-independent)

558

const logicalSize = new LogicalSize(800, 600);

559

await window.setSize(logicalSize);

560

561

// Convert between logical and physical

562

const scaleFactor = 2.0; // High-DPI display

563

const physicalSize = logicalSize.toPhysical(scaleFactor);

564

console.log(`Logical: 800x600, Physical: ${physicalSize.width}x${physicalSize.height}`);

565

566

// Position windows consistently across different DPI displays

567

const logicalPos = new LogicalPosition(100, 100);

568

await window.setPosition(logicalPos);

569

570

// Handle DPI changes

571

await window.listen('tauri://scale-change', (event) => {

572

const newScaleFactor = event.payload.scaleFactor;

573

// Adjust UI elements for new scale factor

574

});

575

```

576

577

### Cross-Platform File Handling

578

579

```typescript

580

import {

581

sep,

582

join,

583

homeDir,

584

appDataDir,

585

BaseDirectory

586

} from '@tauri-apps/api/path';

587

588

// Platform-aware path construction

589

const separator = await sep(); // '/' on Unix, '\' on Windows

590

const userFile = await join(await homeDir(), 'Documents', 'myfile.txt');

591

592

// Application data storage

593

const appData = await appDataDir();

594

const dbPath = await join(appData, 'database.sqlite');

595

const logPath = await join(await appLogDir(), 'app.log');

596

597

// Use BaseDirectory enum with other APIs

598

import { readTextFile, writeTextFile } from '@tauri-apps/api/fs';

599

600

const config = await readTextFile('config.json', {

601

dir: BaseDirectory.AppConfig

602

});

603

604

await writeTextFile('settings.json', JSON.stringify(settings), {

605

dir: BaseDirectory.AppData

606

});

607

```

608

609

### Error Handling

610

611

```typescript

612

import { join, appDataDir } from '@tauri-apps/api/path';

613

614

try {

615

const dataDir = await appDataDir();

616

const filePath = await join(dataDir, 'important.json');

617

618

// Use the path...

619

} catch (error) {

620

// Common errors:

621

// - Directory doesn't exist

622

// - Permission denied

623

// - Invalid path characters

624

console.error('Path operation failed:', error);

625

}

626

```

627

628

## Platform Differences

629

630

Different operating systems have different directory conventions:

631

632

- **Windows**: Uses `\` as path separator, different directory locations

633

- **macOS**: Unix-like paths but different app data locations

634

- **Linux**: Follows XDG Base Directory specification

635

636

The Tauri path API abstracts these differences, providing consistent behavior across platforms while respecting platform conventions for directory locations.