Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 1765 lines (1327 sloc) 62.165 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
//
// NotationController.m
// Notation
//
// Created by Zachary Schneirov on 12/19/05.
// Copyright 2005 Zachary Schneirov. All rights reserved.
//

#import "NotationController.h"
#import "NSCollection_utils.h"
#import "NoteObject.h"
#import "DeletedNoteObject.h"
#import "NSString_NV.h"
#import "BufferUtils.h"
#import "GlobalPrefs.h"
#import "NotationPrefs.h"
#import "NoteAttributeColumn.h"
#import "FrozenNotation.h"
#import "NotationFileManager.h"
#import "NotationSyncServiceManager.h"
#import "SyncSessionController.h"
#import "DeletionManager.h"
#import "BookmarksController.h"

@implementation NotationController

NSInteger compareCatalogEntryName(const void *one, const void *two) {
    return (int)CFStringCompare((CFStringRef)((*(NoteCatalogEntry **)one)->filename),
(CFStringRef)((*(NoteCatalogEntry **)two)->filename), kCFCompareCaseInsensitive);
}

NSInteger compareCatalogValueNodeID(id *a, id *b) {
NoteCatalogEntry* aEntry = (NoteCatalogEntry*)[*(id*)a pointerValue];
NoteCatalogEntry* bEntry = (NoteCatalogEntry*)[*(id*)b pointerValue];

    return aEntry->nodeID - bEntry->nodeID;
}

NSInteger compareCatalogValueFileSize(id *a, id *b) {
NoteCatalogEntry* aEntry = (NoteCatalogEntry*)[*(id*)a pointerValue];
NoteCatalogEntry* bEntry = (NoteCatalogEntry*)[*(id*)b pointerValue];

    return aEntry->logicalSize - bEntry->logicalSize;
}


- (id)init {
    if ([super init]) {
directoryChangesFound = notesChanged = aliasNeedsUpdating = NO;

allNotes = [[NSMutableArray alloc] init]; //<--the authoritative list of all memory-accessible notes
deletedNotes = [[NSMutableSet alloc] init];
labelsListController = [[LabelsListController alloc] init];
prefsController = [GlobalPrefs defaultPrefs];
notesListDataSource = [[FastListDataSource alloc] init];

allNotesBuffer = NULL;
allNotesBufferSize = 0;
manglingString = currentFilterStr = NULL;
lastWordInFilterStr = 0;
selectedNoteIndex = NSNotFound;

subscriptionCallback = NewFNSubscriptionUPP(NotesDirFNSubscriptionProc);

fsCatInfoArray = NULL;
HFSUniNameArray = NULL;
catalogEntries = NULL;
sortedCatalogEntries = NULL;
catEntriesCount = totalCatEntriesCount = 0;

bzero(&noteDirSubscription, sizeof(FNSubscriptionRef));
bzero(&noteDatabaseRef, sizeof(FSRef));
bzero(&noteDirectoryRef, sizeof(FSRef));
volumeSupportsExchangeObjects = -1;

lastCheckedDateInHours = hoursFromAbsoluteTime(CFAbsoluteTimeGetCurrent());
blockSize = 0;

lastWriteError = noErr;
unwrittenNotes = [[NSMutableSet alloc] init];
    }
    return self;
}


- (id)initWithAliasData:(NSData*)data error:(OSStatus*)err {
    OSStatus anErr = noErr;
    
    if (data && (anErr = PtrToHand([data bytes], (Handle*)&aliasHandle, [data length])) == noErr) {

FSRef targetRef;
Boolean changed;

if ((anErr = FSResolveAliasWithMountFlags(NULL, aliasHandle, &targetRef, &changed, 0)) == noErr) {
if ([self initWithDirectoryRef:&targetRef error:&anErr]) {
aliasNeedsUpdating = changed;
*err = noErr;

return self;
}
}
    }
    
    *err = anErr;
    
    return nil;
}

- (id)initWithDefaultDirectoryReturningError:(OSStatus*)err {
    FSRef targetRef;
    
    OSStatus anErr = noErr;
    if ((anErr = [NotationController getDefaultNotesDirectoryRef:&targetRef]) == noErr) {

if ([self initWithDirectoryRef:&targetRef error:&anErr]) {
*err = noErr;
return self;
}
    }
    
    *err = anErr;
    
    return nil;
}

- (id)initWithDirectoryRef:(FSRef*)directoryRef error:(OSStatus*)err {
    
    *err = noErr;
    
    if ([self init]) {
aliasNeedsUpdating = YES; //we don't know if we have an alias yet

noteDirectoryRef = *directoryRef;

//check writable and readable perms, warning user if necessary

//first read cache file
OSStatus anErr = noErr;
if ((anErr = [self _readAndInitializeSerializedNotes]) != noErr) {
*err = anErr;
return nil;
}

//set up the directory subscription, if necessary
//and sync based on notes in directory and their mod. dates
[self databaseSettingsChangedFromOldFormat:[notationPrefs notesStorageFormat]];
if (!walWriter) {
*err = kJournalingError;
return nil;
}

[self upgradeDatabaseIfNecessary];
    }
    
    return self;
}

- (id)delegate {
return delegate;
}

- (void)setDelegate:(id)theDelegate {

delegate = theDelegate;

}

- (void)upgradeDatabaseIfNecessary {
if (![notationPrefs firstTimeUsed]) {

//upgrade note-text-encodings here if there might exist notes with the wrong encoding (check NotationPrefs values)
if ([notationPrefs epochIteration] < 2) {
//this would have to be a database from epoch 1, where the default file-encoding was system-default
NSLog(@"trying to upgrade note encodings");
[allNotes makeObjectsPerformSelector:@selector(upgradeToUTF8IfUsingSystemEncoding)];
//move aside the old database as the new format breaks compatibility
(void)[self renameAndForgetNoteDatabaseFile:@"Notes & Settings (old version from 2.0b)"];
}
if ([notationPrefs epochIteration] < 3) {
[allNotes makeObjectsPerformSelector:@selector(writeFileDatesAndUpdateTrackingInfo)];
}

if ([notationPrefs epochIteration] < EPOC_ITERATION) {
NSLog(@"epociteration was upgraded from %u to %u", [notationPrefs epochIteration], EPOC_ITERATION);
notesChanged = YES;
[self flushEverything];
} else if ([notationPrefs epochIteration] > EPOC_ITERATION) {
if (NSRunCriticalAlertPanel(NSLocalizedString(@"Warning: this database was created by a newer version of Notational Velocity. Continue anyway?", nil),
NSLocalizedString(@"If you make changes, some settings and metadata will be lost.", nil),
NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Continue", nil), nil) == NSAlertDefaultReturn);
exit(0);
}
}
}

//used to ensure a newly-written Notes & Settings file is valid before finalizing the save
//read the file back from disk, deserialize it, decrypt and decompress it, and compare the notes roughly to our current notes
- (NSNumber*)verifyDataAtTemporaryFSRef:(NSValue*)fsRefValue withFinalName:(NSString*)filename {

NSDate *date = [NSDate date];

NSAssert([filename isEqualToString:NotesDatabaseFileName], @"attempting to verify something other than the database");

FSRef *notesFileRef = [fsRefValue pointerValue];
UInt64 fileSize = 0;
char *notesData = NULL;
OSStatus err = noErr, result = noErr;
if ((err = FSRefReadData(notesFileRef, BlockSizeForNotation(self), &fileSize, (void**)&notesData, forceReadMask)) != noErr)
return [NSNumber numberWithInt:err];

FrozenNotation *frozenNotation = nil;
if (!fileSize) {
result = eofErr;
goto returnResult;
}
NSData *archivedNotation = [[[NSData alloc] initWithBytesNoCopy:notesData length:fileSize freeWhenDone:NO] autorelease];
@try {
frozenNotation = [NSKeyedUnarchiver unarchiveObjectWithData:archivedNotation];
} @catch (NSException *e) {
NSLog(@"(VERIFY) Error unarchiving notes and preferences from data (%@, %@)", [e name], [e reason]);
result = kCoderErr;
goto returnResult;
}
//unpack notes using the current NotationPrefs instance (not the just-unarchived one), with which we presumably just used to encrypt it
NSMutableArray *notesToVerify = [[frozenNotation unpackedNotesWithPrefs:notationPrefs returningError:&err] retain];
if (noErr != err) {
result = err;
goto returnResult;
}
//notes were unpacked--now roughly compare notesToVerify with allNotes, plus deletedNotes and notationPrefs
if (!notesToVerify || [notesToVerify count] != [allNotes count] || [[frozenNotation deletedNotes] count] != [deletedNotes count] ||
[[frozenNotation notationPrefs] notesStorageFormat] != [notationPrefs notesStorageFormat] ||
[[frozenNotation notationPrefs] hashIterationCount] != [notationPrefs hashIterationCount]) {
result = kItemVerifyErr;
goto returnResult;
}
unsigned int i;
for (i=0; i<[notesToVerify count]; i++) {
if ([[[notesToVerify objectAtIndex:i] contentString] length] != [[[allNotes objectAtIndex:i] contentString] length]) {
result = kItemVerifyErr;
goto returnResult;
}
}

NSLog(@"verified %u notes in %g s", [notesToVerify count], (float)[[NSDate date] timeIntervalSinceDate:date]);
returnResult:
if (notesData) free(notesData);
return [NSNumber numberWithInt:result];
}


- (OSStatus)_readAndInitializeSerializedNotes {

    OSStatus err = noErr;
if ((err = [self createFileIfNotPresentInNotesDirectory:&noteDatabaseRef forFilename:NotesDatabaseFileName fileWasCreated:nil]) != noErr)
return err;

UInt64 fileSize = 0;
char *notesData = NULL;
if ((err = FSRefReadData(&noteDatabaseRef, BlockSizeForNotation(self), &fileSize, (void**)&notesData, noCacheMask)) != noErr)
return err;

FrozenNotation *frozenNotation = nil;

if (fileSize > 0) {
NSData *archivedNotation = [[NSData alloc] initWithBytesNoCopy:notesData length:fileSize freeWhenDone:NO];
@try {
frozenNotation = [NSKeyedUnarchiver unarchiveObjectWithData:archivedNotation];
} @catch (NSException *e) {
NSLog(@"Error unarchiving notes and preferences from data (%@, %@)", [e name], [e reason]);

if (notesData)
free(notesData);

//perhaps this shouldn't be an error, but the user should instead have the option of overwriting the DB with a new one?
return kCoderErr;
}

[archivedNotation autorelease];
}


[notationPrefs release];

if (!(notationPrefs = [[frozenNotation notationPrefs] retain]))
notationPrefs = [[NotationPrefs alloc] init];
[notationPrefs setDelegate:self];

[allNotes release];

syncSessionController = [[SyncSessionController alloc] initWithSyncDelegate:self notationPrefs:notationPrefs];

//frozennotation will work out passwords, keychains, decryption, etc...
if (!(allNotes = [[frozenNotation unpackedNotesReturningError:&err] retain])) {
//notes could be nil because the user cancelled password authentication
//or because they were corrupted, or for some other reason
if (err != noErr)
return err;

allNotes = [[NSMutableArray alloc] init];
} else {
[allNotes makeObjectsPerformSelector:@selector(setDelegate:) withObject:self];
//[allNotes makeObjectsPerformSelector:@selector(updateLabelConnectionsAfterDecoding)]; //not until we get an actual tag browser
}

[deletedNotes release];

if (!(deletedNotes = [[frozenNotation deletedNotes] retain]))
deletedNotes = [[NSMutableSet alloc] init];

[prefsController setNotationPrefs:notationPrefs sender:self];

if(notesData)
free(notesData);

return noErr;
}

- (BOOL)initializeJournaling {
    
    const UInt32 maxPathSize = 8 * 1024;
    UInt8 *convertedPath = (UInt8*)malloc(maxPathSize * sizeof(UInt8));
    OSStatus err = noErr;
NSData *walSessionKey = [notationPrefs WALSessionKey];

    if ((err = FSRefMakePath(&noteDirectoryRef, convertedPath, maxPathSize)) == noErr) {
//initialize the journal if necessary
if (!(walWriter = [[WALStorageController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey])) {
//journal file probably already exists, so try to recover it
WALRecoveryController *walReader = [[[WALRecoveryController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey] autorelease];
if (walReader) {

BOOL databaseCouldNotBeFlushed = NO;
NSDictionary *recoveredNotes = [walReader recoveredNotes];
if ([recoveredNotes count] > 0) {
[self processRecoveredNotes:recoveredNotes];

if (![self flushAllNoteChanges]) {
//we shouldn't continue because the journal is still the sole record of the unsaved notes, so we can't delete it
//BUT: what if the database can't be verified? We should be able to continue, and just keep adding to the WAL
//in this case the WAL should be destroyed, re-initialized, and the recovered (and de-duped) notes added back
NSLog(@"Unable to flush recovered notes back to database");
databaseCouldNotBeFlushed = YES;
//goto bail;
}
}
//is there a way that recoverNextObject could fail that would indicate a failure with the file as opposed to simple non-recovery?
//if so, it perhaps the recoveredNotes method should also return an error condition, to be checked here

//there could be other issues, too (1)

if (![walReader destroyLogFile]) {
//couldn't delete the log file, so we can't create a new one
NSLog(@"Unable to delete the old write-ahead-log file");
goto bail;
}

if (!(walWriter = [[WALStorageController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey])) {
//couldn't create a journal after recovering the old one
//if databaseCouldNotBeFlushed is true here, then we've potentially lost notes; perhaps exchangeobjects would be better here?
NSLog(@"Unable to create a new write-ahead-log after deleting the old one");
goto bail;
}

if ([recoveredNotes count] > 0) {
if (databaseCouldNotBeFlushed) {
//re-add the contents of recoveredNotes to walWriter; LSNs should take care of the order; no need to sort
//this allows for an ever-growing journal in the case of broken database serialization
//it should not be an acceptable condition for permanent use; hopefully an update would come soon
//warn the user, perhaps
[walWriter writeNoteObjects:[recoveredNotes allValues]];
}
[self refilterNotes];
}
} else {
NSLog(@"Unable to recover unsaved notes from write-ahead-log");
//1) should we let the user attempt to remove it without recovery?
goto bail;
}
}
[walWriter setDelegate:self];

return YES;
    } else {
NSLog(@"FSRefMakePath error: %d", err);
goto bail;
    }
    
bail:
free(convertedPath);
    return NO;
}

//stick the newest unique recovered notes into allNotes
- (void)processRecoveredNotes:(NSDictionary*)dict {
    const unsigned int vListBufCount = 16;
    void* keysBuffer[vListBufCount], *valuesBuffer[vListBufCount];
    unsigned int i, count = [dict count];
    
    void **keys = (count <= vListBufCount) ? keysBuffer : (void **)malloc(sizeof(void*) * count);
    void **values = (count <= vListBufCount) ? valuesBuffer : (void **)malloc(sizeof(void*) * count);
    
    if (keys && values && dict) {
CFDictionaryGetKeysAndValues((CFDictionaryRef)dict, (const void **)keys, (const void **)values);

for (i=0; i<count; i++) {

CFUUIDBytes *objUUIDBytes = (CFUUIDBytes *)keys[i];
id<SynchronizedNote> obj = (id)values[i];

NSUInteger existingNoteIndex = [allNotes indexOfNoteWithUUIDBytes:objUUIDBytes];

if ([obj isKindOfClass:[DeletedNoteObject class]]) {

if (existingNoteIndex != NSNotFound) {

NoteObject *existingNote = [allNotes objectAtIndex:existingNoteIndex];
if ([existingNote youngerThanLogObject:obj]) {
NSLog(@"got a newer deleted note");
//except that normally the undomanager doesn't exist by this point
[self _registerDeletionUndoForNote:existingNote];
[allNotes removeObjectAtIndex:existingNoteIndex];
//try to use use the deleted note object instead of allowing _addDeletedNote: to make a new one, to preserve any changes to the syncMD
[self _addDeletedNote:obj];
notesChanged = YES;
} else {
NSLog(@"got an older deleted note");
}
}
} else if (existingNoteIndex != NSNotFound) {

if ([[allNotes objectAtIndex:existingNoteIndex] youngerThanLogObject:obj]) {
// NSLog(@"replacing old note with new: %@", [[(NoteObject*)obj contentString] string]);

[(NoteObject*)obj setDelegate:self];
[(NoteObject*)obj updateLabelConnectionsAfterDecoding];
[allNotes replaceObjectAtIndex:existingNoteIndex withObject:obj];
notesChanged = YES;
} else {
// NSLog(@"note %@ is not being replaced because its LSN is %u, while the old note's LSN is %u",
// [[(NoteObject*)obj contentString] string], [(NoteObject*)obj logSequenceNumber], [[allNotes objectAtIndex:existingNoteIndex] logSequenceNumber]);
}
} else {
//NSLog(@"Found new note: %@", [(NoteObject*)obj contentString]);

[self _addNote:obj];
[(NoteObject*)obj updateLabelConnectionsAfterDecoding];
}
}

if (keys != keysBuffer)
free(keys);
if (values != valuesBuffer)
free(values);

    } else {
NSLog(@"_makeChangesInDictionary: Could not get values or keys!");
    }
}

- (void)closeJournal {
    //remove journal file if we have one
    if (walWriter) {
if (![walWriter destroyLogFile])
NSLog(@"couldn't remove wal file--is this an error for note flushing?");

[walWriter release];
walWriter = nil;
    }
}

- (void)checkJournalExistence {
    if (walWriter && ![walWriter logFileStillExists])
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}

- (void)flushEverything {

//if we could flush the database and there was a journal, then close it
if ([self flushAllNoteChanges] && walWriter) {
[self closeJournal];

//re-start the journal if we had one
if (![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}
}
}

- (BOOL)flushAllNoteChanges {
    //write only if preferences or notes have been changed
    if (notesChanged || [notationPrefs preferencesChanged]) {

//finish writing notes and/or db journal entries
[self synchronizeNoteChanges:changeWritingTimer];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synchronizeNoteChanges:) object:nil];

if (walWriter) {
if (![walWriter synchronize])
NSLog(@"Couldn't sync wal file--is this an error for note flushing?");
[NSObject cancelPreviousPerformRequestsWithTarget:walWriter selector:@selector(synchronize) object:nil];
}

NSData *serializedData = [FrozenNotation frozenDataWithExistingNotes:allNotes deletedNotes:deletedNotes prefs:notationPrefs];
if (!serializedData) {

NSLog(@"serialized data is nil!");
return NO;
}

//we should have all journal records on disk by now
if ([self storeDataAtomicallyInNotesDirectory:serializedData withName:NotesDatabaseFileName destinationRef:&noteDatabaseRef
verifyWithSelector:@selector(verifyDataAtTemporaryFSRef:withFinalName:) verificationDelegate:self] != noErr)
return NO;

[notationPrefs setPreferencesAreStored];
notesChanged = NO;

    }

    return YES;
}

- (void)handleJournalError {
    
    //we can be static because the resulting action (exit) is global to the app
    static BOOL displayedAlert = NO;
    
    if (delegate && !displayedAlert) {
//we already have a delegate, so this must be a result of the format or file changing after initialization

displayedAlert = YES;

[self flushAllNoteChanges];

NSRunAlertPanel(NSLocalizedString(@"Unable to create or access the Interim Note-Changes file. Is another copy of Notational Velocity currently running?",nil),
NSLocalizedString(@"Open Console in /Applications/Utilities/ for more information.",nil), NSLocalizedString(@"Quit",nil), NULL, NULL);


exit(1);
    }
}

//notation prefs delegate method
- (void)databaseEncryptionSettingsChanged {
//we _must_ re-init the journal (if fmt is single-db and jrnl exists) in addition to flushing DB
[self flushEverything];
}

//notation prefs delegate method
- (void)databaseSettingsChangedFromOldFormat:(int)oldFormat {
    OSStatus err = noErr;
int currentStorageFormat = [notationPrefs notesStorageFormat];
    
if (!walWriter && ![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}

    if (currentStorageFormat == SingleDatabaseFormat) {

[self stopFileNotifications];

/*if (![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}*/

    } else {
//write to disk any unwritten notes; do this before flushing database to make sure that when it is flushed, it gets the new file mod. dates
//otherwise it would be necessary to set notesChanged = YES; after this method

//also make sure not to write new notes unless changing to a different format; don't rewrite deleted notes upon launch
if (currentStorageFormat != oldFormat)
[allNotes makeObjectsPerformSelector:@selector(writeUsingCurrentFileFormatIfNonExistingOrChanged)];

//flush and close the journal if necessary
/*if (walWriter) {
if ([self flushAllNoteChanges])
[self closeJournal];
}*/
//notationPrefs should call flushAllNoteChanges after this method, anyway

if (IsZeros(&noteDirSubscription, sizeof(FNSubscriptionRef))) {

err = FNSubscribe(&noteDirectoryRef, subscriptionCallback, self, kFNNoImplicitAllSubscription | kFNNotifyInBackground, &noteDirSubscription);
if (err != noErr) {
NSLog(@"Could not subscribe to changes in notes directory!");
//just check modification time of directory?
}
}

[self synchronizeNotesFromDirectory];
    }
}

- (int)currentNoteStorageFormat {
    return [notationPrefs notesStorageFormat];
}

- (void)stopFileNotifications {
OSStatus err = noErr;
    if (!IsZeros(&noteDirSubscription, sizeof(FNSubscriptionRef))) {

if ((err = FNUnsubscribe(noteDirSubscription)) != noErr) {
NSLog(@"Could not unsubscribe from note changes callback: %d", err);
} else {
bzero(&noteDirSubscription, sizeof(FNSubscriptionRef));
}

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synchronizeNotesFromDirectory) object:nil];
    }
    
}

void NotesDirFNSubscriptionProc(FNMessage message, OptionBits flags, void * refcon, FNSubscriptionRef subscription) {
    //this only works for the Finder and perhaps the navigation manager right now
    if (kFNDirectoryModifiedMessage == message) {
//NSLog(@"note directory changed");
if (refcon) {
[NSObject cancelPreviousPerformRequestsWithTarget:(id)refcon selector:@selector(synchronizeNotesFromDirectory) object:nil];
[(id)refcon performSelector:@selector(synchronizeNotesFromDirectory) withObject:nil afterDelay:0.0];
}

    } else {
NSLog(@"we received an FNSubscr. callback and the directory didn't actually change?");
    }
}


- (BOOL)synchronizeNotesFromDirectory {
    if ([self currentNoteStorageFormat] == SingleDatabaseFormat) {
//NSLog(@"%s: called when storage format is singledatabase", _cmd);
return NO;
}

    //NSDate *date = [NSDate date];
    if ([self _readFilesInDirectory]) {
//NSLog(@"read files in directory");

directoryChangesFound = NO;
if (catEntriesCount && [allNotes count]) {
[self makeNotesMatchCatalogEntries:sortedCatalogEntries ofSize:catEntriesCount];
} else {
unsigned int i;

if (![allNotes count]) {
//no notes exist, so every file must be new
for (i=0; i<catEntriesCount; i++) {
if ([notationPrefs catalogEntryAllowed:sortedCatalogEntries[i]])
[self addNoteFromCatalogEntry:sortedCatalogEntries[i]];
}
}

if (!catEntriesCount) {
//there is nothing at all in the directory, so remove all the notes
//we probably shouldn't get here; there should be at least a database file and random .DS_Store-like crap
[[DeletionManager sharedManager] addDeletedNotes:allNotes];
}
}

if (directoryChangesFound) {
[self resortAllNotes];
[self refilterNotes];
}

//NSLog(@"file sync time: %g, ",[[NSDate date] timeIntervalSinceDate:date]);
return YES;
    }
    
    return NO;
}

//scour the notes directory for fresh meat
- (BOOL)_readFilesInDirectory {
    
    OSStatus status = noErr;
    FSIterator dirIterator;
    ItemCount totalObjects = 0, dirObjectCount = 0;
    unsigned int i = 0, catIndex = 0;
    
    //something like 16 VM pages used here?
    if (!fsCatInfoArray) fsCatInfoArray = (FSCatalogInfo *)calloc(kMaxFileIteratorCount, sizeof(FSCatalogInfo));
    if (!HFSUniNameArray) HFSUniNameArray = (HFSUniStr255 *)calloc(kMaxFileIteratorCount, sizeof(HFSUniStr255));

    if ((status = FSOpenIterator(&noteDirectoryRef, kFSIterateFlat, &dirIterator)) == noErr) {
//catEntriesCount = 0;

        do {
            // Grab a batch of source files to process from the source directory
            status = FSGetCatalogInfoBulk(dirIterator, kMaxFileIteratorCount, &dirObjectCount, NULL,
kFSCatInfoNodeFlags | kFSCatInfoFinderInfo | kFSCatInfoContentMod | kFSCatInfoDataSizes | kFSCatInfoNodeID,
fsCatInfoArray, NULL, NULL, HFSUniNameArray);

            if ((status == errFSNoMoreItems || status == noErr) && dirObjectCount) {
                status = noErr;

totalObjects += dirObjectCount;
if (totalObjects > totalCatEntriesCount) {
unsigned int oldCatEntriesCount = totalCatEntriesCount;

totalCatEntriesCount = totalObjects;
catalogEntries = (NoteCatalogEntry *)realloc(catalogEntries, totalObjects * sizeof(NoteCatalogEntry));
sortedCatalogEntries = (NoteCatalogEntry **)realloc(sortedCatalogEntries, totalObjects * sizeof(NoteCatalogEntry*));

//clear unused memory to make filename and filenameChars null

size_t newSpace = (totalCatEntriesCount - oldCatEntriesCount) * sizeof(NoteCatalogEntry);
bzero(catalogEntries + oldCatEntriesCount, newSpace);
}

for (i = 0; i < dirObjectCount; i++) {
// Only read files, not directories
if (!(fsCatInfoArray[i].nodeFlags & kFSNodeIsDirectoryMask)) {
//filter these only for files that will be added
//that way we can catch changes in files whose format is still being lazily updated

NoteCatalogEntry *entry = &catalogEntries[catIndex];
HFSUniStr255 *filename = &HFSUniNameArray[i];

entry->fileType = ((FileInfo *)fsCatInfoArray[i].finderInfo)->fileType;
entry->logicalSize = (UInt32)(fsCatInfoArray[i].dataLogicalSize & 0xFFFFFFFF);
entry->nodeID = (UInt32)fsCatInfoArray[i].nodeID;
entry->lastModified = fsCatInfoArray[i].contentModDate;

if (filename->length > entry->filenameCharCount) {
entry->filenameCharCount = filename->length;
entry->filenameChars = (UniChar*)realloc(entry->filenameChars, entry->filenameCharCount * sizeof(UniChar));
}

memcpy(entry->filenameChars, filename->unicode, filename->length * sizeof(UniChar));

if (!entry->filename)
entry->filename = CFStringCreateMutableWithExternalCharactersNoCopy(NULL, entry->filenameChars, filename->length, entry->filenameCharCount, kCFAllocatorNull);
else
CFStringSetExternalCharactersNoCopy(entry->filename, entry->filenameChars, filename->length, entry->filenameCharCount);

catIndex++;
                    }
                }

catEntriesCount = catIndex;
            }
            
        } while (status == noErr);

FSCloseIterator(dirIterator);

for (i=0; i<catEntriesCount; i++) {
sortedCatalogEntries[i] = &catalogEntries[i];
}

return YES;
    }
    
    NSLog(@"Error opening FSIterator: %d", status);
    
    return NO;
}

- (BOOL)modifyNoteIfNecessary:(NoteObject*)aNoteObject usingCatalogEntry:(NoteCatalogEntry*)catEntry {
//check dates
UTCDateTime lastReadDate = fileModifiedDateOfNote(aNoteObject);
UTCDateTime fileModDate = catEntry->lastModified;

//should we always update the note's stored inode here regardless?

if (lastReadDate.lowSeconds != fileModDate.lowSeconds ||
lastReadDate.highSeconds != fileModDate.highSeconds ||
lastReadDate.fraction != fileModDate.fraction) {
//assume the file on disk was modified by someone other than us

//figure out whether there is a conflict; is this file on disk older than the one that we have in memory? do we merge?
//if ((UInt64*)&fileModDate > (UInt64*)&lastReadDate)

//check if this note has changes in memory that still need to be committed -- that we _know_ the other writer never had a chance to see
if (![unwrittenNotes containsObject:aNoteObject]) {

if (![aNoteObject updateFromCatalogEntry:catEntry]) {
NSLog(@"file %@ was modified but could not be updated", catEntry->filename);
//return NO;
}
//do not call makeNoteDirty because use of the WAL in this instance would cause redundant disk activity
//in the event of a crash this change could still be recovered;

[aNoteObject registerModificationWithOwnedServices];
[self schedulePushToAllSyncServicesForNote:aNoteObject];

[self note:aNoteObject attributeChanged:NotePreviewString]; //reverse delegate?

[delegate contentsUpdatedForNote:aNoteObject];

[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:NoteDateModifiedColumnString afterDelay:0.0];

notesChanged = YES;
NSLog(@"FILE WAS MODIFIED: %@", catEntry->filename);

return YES;
} else {
//it's a conflict! we win.
NSLog(@"%@ was modified with unsaved changes in NV! Deciding the conflict in favor of NV.", catEntry->filename);
}

}

return NO;
}

- (void)makeNotesMatchCatalogEntries:(NoteCatalogEntry**)catEntriesPtrs ofSize:(size_t)catCount {
    
    unsigned int aSize = [allNotes count];
    unsigned int bSize = catCount;
    
ResizeBuffer((void***)&allNotesBuffer, aSize, &allNotesBufferSize);

assert(allNotesBuffer != NULL);

    NoteObject **currentNotes = allNotesBuffer;
    [allNotes getObjects:(id*)currentNotes];

mergesort((void *)allNotesBuffer, (size_t)aSize, sizeof(id), (int (*)(const void *, const void *))compareFilename);
mergesort((void *)catEntriesPtrs, (size_t)bSize, sizeof(NoteCatalogEntry*), (int (*)(const void *, const void *))compareCatalogEntryName);

    NSMutableArray *addedEntries = [NSMutableArray arrayWithCapacity:5];
    NSMutableArray *removedEntries = [NSMutableArray arrayWithCapacity:5];

    //oldItems(a,i) = currentNotes
    //newItems(b,j) = catEntries;
    
    unsigned int i, j, lastInserted = 0;
    
    for (i=0; i<aSize; i++) {

BOOL exitedEarly = NO;
for (j=lastInserted; j<bSize; j++) {

CFComparisonResult order = CFStringCompare((CFStringRef)(catEntriesPtrs[j]->filename),
(CFStringRef)filenameOfNote(currentNotes[i]),
kCFCompareCaseInsensitive);
if (order == kCFCompareGreaterThan) { //if (A[i] < B[j])
lastInserted = j;
exitedEarly = YES;

//NSLog(@"FILE DELETED (during): %@", filenameOfNote(currentNotes[i]));
[removedEntries addObject:currentNotes[i]];
break;
} else if (order == kCFCompareEqualTo) { //if (A[i] == B[j])
//the name matches, so add this to changed iff its contents also changed
lastInserted = j + 1;
exitedEarly = YES;

[self modifyNoteIfNecessary:currentNotes[i] usingCatalogEntry:catEntriesPtrs[j]];

break;
}

//NSLog(@"FILE ADDED (during): %@", catEntriesPtrs[j]->filename);
if ([notationPrefs catalogEntryAllowed:catEntriesPtrs[j]])
[addedEntries addObject:[NSValue valueWithPointer:catEntriesPtrs[j]]];
}

if (!exitedEarly) {

//element A[i] "appended" to the end of list B
if (CFStringCompare((CFStringRef)filenameOfNote(currentNotes[i]),
(CFStringRef)(catEntriesPtrs[MIN(lastInserted, bSize-1)]->filename),
kCFCompareCaseInsensitive) == kCFCompareGreaterThan) {
lastInserted = bSize;

//NSLog(@"FILE DELETED (after): %@", filenameOfNote(currentNotes[i]));
[removedEntries addObject:currentNotes[i]];
}
}

    }
    
    for (j=lastInserted; j<bSize; j++) {

//NSLog(@"FILE ADDED (after): %@", catEntriesPtrs[j]->filename);
if ([notationPrefs catalogEntryAllowed:catEntriesPtrs[j]])
[addedEntries addObject:[NSValue valueWithPointer:catEntriesPtrs[j]]];
    }
    
if ([addedEntries count] && [removedEntries count]) {
[self processNotesAdded:addedEntries removed:removedEntries];
} else {

if (![removedEntries count]) {
for (i=0; i<[addedEntries count]; i++) {
[self addNoteFromCatalogEntry:(NoteCatalogEntry*)[[addedEntries objectAtIndex:i] pointerValue]];
}
}

if (![addedEntries count]) {
[[DeletionManager sharedManager] addDeletedNotes:removedEntries];
}
}

}

//find renamed notes through unique file IDs
//TODO: reconcile the "actually" added/deleted files into renames for files with identical content (sort by size)
- (void)processNotesAdded:(NSMutableArray*)addedEntries removed:(NSMutableArray*)removedEntries {
unsigned int aSize = [removedEntries count], bSize = [addedEntries count];
    
    //sort on nodeID here
[addedEntries sortUnstableUsingFunction:compareCatalogValueNodeID];
[removedEntries sortUnstableUsingFunction:compareNodeID];

    //oldItems(a,i) = currentNotes
    //newItems(b,j) = catEntries;
    
    unsigned int i, j, lastInserted = 0;
    
    for (i=0; i<aSize; i++) {
NoteObject *currentNote = [removedEntries objectAtIndex:i];

BOOL exitedEarly = NO;
for (j=lastInserted; j<bSize; j++) {

NoteCatalogEntry *catEntry = (NoteCatalogEntry *)[[addedEntries objectAtIndex:j] pointerValue];
int order = catEntry->nodeID - fileNodeIDOfNote(currentNote);

if (order > 0) { //if (A[i] < B[j])
lastInserted = j;
exitedEarly = YES;

NSLog(@"File _actually_ deleted: %@", filenameOfNote(currentNote));
[[DeletionManager sharedManager] addDeletedNote:currentNote];

break;
} else if (order == 0) { //if (A[i] == B[j])
lastInserted = j + 1;
exitedEarly = YES;


//note was renamed!
NSLog(@"File %@ was renamed to %@", filenameOfNote(currentNote), catEntry->filename);
if (![self modifyNoteIfNecessary:currentNote usingCatalogEntry:catEntry]) {
//at least update the file name, because we _know_ that changed

directoryChangesFound = YES;

[currentNote setFilename:(NSString*)catEntry->filename withExternalTrigger:YES];
}

notesChanged = YES;

break;
}

//a new file was found on the disk! read it into memory!

NSLog(@"File _actually_ added: %@", catEntry->filename);
[self addNoteFromCatalogEntry:catEntry];
}

if (!exitedEarly) {

//element A[i] "appended" to the end of list B

NoteCatalogEntry *appendedCatEntry = (NoteCatalogEntry *)[[addedEntries objectAtIndex:MIN(lastInserted, bSize-1)] pointerValue];
if (fileNodeIDOfNote(currentNote) - appendedCatEntry->nodeID > 0) {
lastInserted = bSize;

//file deleted from disk;
NSLog(@"File _actually_ deleted: %@", filenameOfNote(currentNote));
[[DeletionManager sharedManager] addDeletedNote:currentNote];
}
}
    }
    
    for (j=lastInserted; j<bSize; j++) {
NoteCatalogEntry *appendedCatEntry = (NoteCatalogEntry *)[[addedEntries objectAtIndex:j] pointerValue];
NSLog(@"File _actually_ added: %@", appendedCatEntry->filename);
[self addNoteFromCatalogEntry:appendedCatEntry];
    }
}

- (void)noteDidNotWrite:(NoteObject*)note errorCode:(OSStatus)error {
    [unwrittenNotes addObject:note];
    
    if (error != lastWriteError) {
NSRunAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Changed notes could not be saved because %@.",
@"alert title appearing when notes couldn't be written"),
[NSString reasonStringFromCarbonFSError:error]], @"", NSLocalizedString(@"OK",nil), NULL, NULL);

lastWriteError = error;
    }
}

- (void)synchronizeNoteChanges:(NSTimer*)timer {
    
    if ([unwrittenNotes count] > 0) {
lastWriteError = noErr;
if ([notationPrefs notesStorageFormat] != SingleDatabaseFormat) {
[unwrittenNotes makeObjectsPerformSelector:@selector(writeUsingCurrentFileFormatIfNecessary)];

//this always seems to call ourselves
FNNotify(&noteDirectoryRef, kFNDirectoryModifiedMessage, kFNNoImplicitAllSubscription);
}
if (walWriter) {
//append unwrittenNotes to journal, if one exists
[unwrittenNotes makeObjectsPerformSelector:@selector(writeUsingJournal:) withObject:walWriter];
}

//NSLog(@"wrote %d unwritten notes", [unwrittenNotes count]);

[unwrittenNotes removeAllObjects];

[self scheduleUpdateListForAttribute:NoteDateModifiedColumnString];

    }
    
    if (changeWritingTimer) {
[changeWritingTimer invalidate];
[changeWritingTimer release];
changeWritingTimer = nil;
    }
}

- (NSData*)aliasDataForNoteDirectory {
    NSData* theData = nil;
    
    FSRef userHomeFoundRef, *relativeRef = &userHomeFoundRef;
    
    if (aliasNeedsUpdating) {
OSErr err = FSFindFolder(kUserDomain, kCurrentUserFolderType, kCreateFolder, &userHomeFoundRef);
if (err != noErr) {
relativeRef = NULL;
NSLog(@"FSFindFolder error: %d", err);
}
    }

    //re-fill handle from fsref if necessary, storing path relative to user directory
    if (aliasNeedsUpdating && FSNewAlias(relativeRef, &noteDirectoryRef, &aliasHandle ) != noErr)
return nil;

    if (aliasHandle != NULL) {
aliasNeedsUpdating = NO;

HLock((Handle)aliasHandle);
theData = [NSData dataWithBytes:*aliasHandle length:GetHandleSize((Handle) aliasHandle)];
HUnlock((Handle)aliasHandle);

return theData;
    }
    
    return nil;
}

- (void)setAliasNeedsUpdating:(BOOL)needsUpdate {
aliasNeedsUpdating = needsUpdate;
}

- (BOOL)aliasNeedsUpdating {
return aliasNeedsUpdating;
}

- (void)checkIfNotationIsTrashed {
if ([self notesDirectoryIsTrashed]) {

NSString *trashLocation = [[NSString pathWithFSRef:&noteDirectoryRef] stringByAbbreviatingWithTildeInPath];
if (!trashLocation) trashLocation = @"unknown";
int result = NSRunCriticalAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Your notes directory (%@) appears to be in the Trash.",nil), trashLocation],
NSLocalizedString(@"If you empty the Trash now, you could lose your notes. Relocate the notes to a less volatile folder?",nil),
NSLocalizedString(@"Relocate Notes",nil), NSLocalizedString(@"Quit",nil), NULL);
if (result == NSAlertDefaultReturn)
[self relocateNotesDirectory];
else [NSApp terminate:nil];
}
}

- (void)trashRemainingNoteFilesInDirectory {
NSAssert([notationPrefs notesStorageFormat] == SingleDatabaseFormat, @"We shouldn't be removing files if the storage is not single-database");
[allNotes makeObjectsPerformSelector:@selector(moveFileToTrash)];
[self notifyOfChangedTrash];
}

- (void)updateLinksToNote:(NoteObject*)aNoteObject fromOldName:(NSString*)oldname {
    //O(n)
}

//for making notes that we don't already own
- (NoteObject*)addNote:(NSAttributedString*)attributedContents withTitle:(NSString*)title {
    if (!title || ![title length])
title = NSLocalizedString(@"Untitled Note", @"Title of a nameless note");
    
    if (!attributedContents)
attributedContents = [[[NSAttributedString alloc] initWithString:@"" attributes:[prefsController noteBodyAttributes]] autorelease];
    
    NoteObject *note = [[NoteObject alloc] initWithNoteBody:attributedContents title:title
uniqueFilename:[self uniqueFilenameForTitle:title fromNote:nil]
format:[self currentNoteStorageFormat]];
    
    [self addNewNote:note];
    
    //we are the the owner of this note
    [note release];
    
    return note;
}

- (void)addNewNote:(NoteObject*)note {
    [self _addNote:note];

//clear aNoteObject's syncServicesMD to facilitate sync recreation upon undoing of deletion
//new notes should not have any sync MD; if they do, they should be added using -addNotesFromSync:
//problem is that note could very likely still be in the process of syncing, in which case these dicts will be accessed
//for simplenote is is necessary only once the iPhone app has fully deleted the note off the server; otherwise a regular update will recreate it
//[note removeAllSyncServiceMD];
    
[note makeNoteDirtyUpdateTime:YES updateFile:YES];
//force immediate update
[self synchronizeNoteChanges:nil];

if ([[self undoManager] isUndoing]) {
//prohibit undoing of creation--only redoing of deletion
//NSLog(@"registering %s", _cmd);
[undoManager registerUndoWithTarget:self selector:@selector(removeNote:) object:note];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Create Note quotemark%@quotemark",@"undo action name for creating a single note"), titleOfNote(note)]];
}
    
[self resortAllNotes];
    [self refilterNotes];
    
    [delegate notation:self revealNote:note options:NVEditNoteToReveal | NVOrderFrontWindow];
}

//do not update the view here (why not?)
- (NoteObject*)addNoteFromCatalogEntry:(NoteCatalogEntry*)catEntry {
NoteObject *newNote = [[NoteObject alloc] initWithCatalogEntry:catEntry delegate:self];
[self _addNote:newNote];
[newNote release];

[self schedulePushToAllSyncServicesForNote:newNote];

directoryChangesFound = YES;

return newNote;
}

- (void)addNotesFromSync:(NSArray*)noteArray {

if (![noteArray count]) return;

unsigned int i;

if ([[self undoManager] isUndoing]) [undoManager beginUndoGrouping];
for (i=0; i<[noteArray count]; i++) {
NoteObject * note = [noteArray objectAtIndex:i];

[self _addNote:note];

[note makeNoteDirtyUpdateTime:NO updateFile:YES];

//absolutely ensure that this note is pushed to the rest of the services
[note registerModificationWithOwnedServices];
[self schedulePushToAllSyncServicesForNote:note];
}
if ([[self undoManager] isUndoing]) [undoManager endUndoGrouping];
//don't need to reverse-register undo because removeNote/s: will never use this method

[self synchronizeNoteChanges:nil];

[self resortAllNotes];
[self refilterNotes];
}

- (void)addNotes:(NSArray*)noteArray {

if (![noteArray count]) return;

unsigned int i;

if ([[self undoManager] isUndoing]) [undoManager beginUndoGrouping];
for (i=0; i<[noteArray count]; i++) {
NoteObject * note = [noteArray objectAtIndex:i];

[self _addNote:note];

[note makeNoteDirtyUpdateTime:YES updateFile:YES];
}
if ([[self undoManager] isUndoing]) [undoManager endUndoGrouping];

[self synchronizeNoteChanges:nil];

if ([[self undoManager] isUndoing]) {
//prohibit undoing of creation--only redoing of deletion
//NSLog(@"registering %s", _cmd);
[undoManager registerUndoWithTarget:self selector:@selector(removeNotes:) object:noteArray];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Add %d Notes", @"undo action name for creating multiple notes"), [noteArray count]]];
}
[self resortAllNotes];
[self refilterNotes];

if ([noteArray count] > 1)
[delegate notation:self revealNotes:noteArray];
else
[delegate notation:self revealNote:[noteArray lastObject] options:NVOrderFrontWindow];
}

- (void)note:(NoteObject*)note attributeChanged:(NSString*)attribute {

if ([attribute isEqualToString:NotePreviewString]) {
if ([prefsController tableColumnsShowPreview]) {
NSUInteger idx = [notesListDataSource indexOfObjectIdenticalTo:note];
if (NSNotFound != idx) {
[delegate rowShouldUpdate:idx];
}
}
//this attribute is not displayed as a column
return;
}

//[self scheduleUpdateListForAttribute:attribute];
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:0.0];

//special case for title requires this method, as app controller needs to know a few note-specific things
if ([attribute isEqualToString:NoteTitleColumnString])
[delegate titleUpdatedForNote:note];
}

- (void)scheduleUpdateListForAttribute:(NSString*)attribute {

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(scheduleUpdateListForAttribute:) object:attribute];

if ([[sortColumn identifier] isEqualToString:attribute]) {

if ([delegate notationListShouldChange:self]) {
[self sortAndRedisplayNotes];
} else {
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:1.5];
}
} else {
//catch col updates even if they aren't the sort key

NSEnumerator *enumerator = [[prefsController visibleTableColumns] objectEnumerator];
NSString *colIdentifier = nil;

//check to see if appropriate col is visible
while ((colIdentifier = [enumerator nextObject])) {
if ([colIdentifier isEqualToString:attribute]) {
if ([delegate notationListShouldChange:self]) {
[delegate notationListMightChange:self];
[delegate notationListDidChange:self];
} else {
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:1.5];
}
break;
}
}
}
}

- (void)scheduleWriteForNote:(NoteObject*)note {

BOOL immediately = NO;
notesChanged = YES;

[unwrittenNotes addObject:note];

//always synchronize absolutely no matter what 15 seconds after any change
if (!changeWritingTimer)
changeWritingTimer = [[NSTimer scheduledTimerWithTimeInterval:(immediately ? 0.0 : 15.0) target:self
selector:@selector(synchronizeNoteChanges:)
userInfo:nil repeats:NO] retain];

//next user change always invalidates queued write from performSelector, but not queued write from timer
//this avoids excessive writing and any potential and unnecessary disk access while user types
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synchronizeNoteChanges:) object:nil];

if (walWriter) {
//perhaps a more general user interface activity timer would be better for this? update process syncs every 30 secs, anyway...
[NSObject cancelPreviousPerformRequestsWithTarget:walWriter selector:@selector(synchronize) object:nil];
//fsyncing WAL to disk can cause noticeable interruption when run from main thread
[walWriter performSelector:@selector(synchronize) withObject:nil afterDelay:15.0];
}

if (!immediately) {
//timer is already scheduled if immediately is true
//queue to write 2.7 seconds after last user change;
[self performSelector:@selector(synchronizeNoteChanges:) withObject:nil afterDelay:2.7];
}
}

//the gatekeepers!
- (void)_addNote:(NoteObject*)aNoteObject {
    [aNoteObject setDelegate:self];

    [allNotes addObject:aNoteObject];
[deletedNotes removeObject:aNoteObject];
    
    notesChanged = YES;
}

//the gateway methods must always show warnings, or else flash overlay window if show-warnings-pref is off
- (void)removeNotes:(NSArray*)noteArray {
NSEnumerator *enumerator = [noteArray objectEnumerator];
NoteObject* note;

[undoManager beginUndoGrouping];
while ((note = [enumerator nextObject])) {
[self removeNote:note];
}
[undoManager endUndoGrouping];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Delete %d Notes",@"undo action name for deleting notes"), [noteArray count]]];

}

- (void)removeNote:(NoteObject*)aNoteObject {
    //reset linking labels and their notes
    
[aNoteObject retain];
    [allNotes removeObjectIdenticalTo:aNoteObject];
DeletedNoteObject *deletedNote = [self _addDeletedNote:aNoteObject];
    
    notesChanged = YES;

//force-write any cached note changes to make sure that their LSNs are smaller than this deleted note's LSN
[self synchronizeNoteChanges:nil];
    
    //we do this after removing it from the array to avoid re-discovering a removed file
    if ([notationPrefs notesStorageFormat] != SingleDatabaseFormat) {
[aNoteObject removeFileFromDirectory];
    }
//add journal removal event
if (walWriter && ![walWriter writeRemovalForNote:aNoteObject]) {
NSLog(@"Couldn't log note removal");
}

//a removal command will be sent to sync services if aNoteObject contains a matching syncServicesMD dict
//(e.g., already been synced at least once)
//make sure we use the same deleted note that was added to the list of deleted notes, to simplify record-keeping
//if the note didn't have metadata, try to sync it anyway so that the service knows this note shouldn't be created
[self schedulePushToAllSyncServicesForNote: deletedNote ? deletedNote : [DeletedNoteObject deletedNoteWithNote:aNoteObject]];
    
[self _registerDeletionUndoForNote:aNoteObject];

//delete note from bookmarks, too
[[prefsController bookmarksController] removeBookmarkForNote:aNoteObject];
    
    [aNoteObject release];
    
    [self refilterNotes];
}

- (void)_purgeAlreadyDistributedDeletedNotes {
//purge deletedNotes of objects without any more syncMD entries;
//once a note has been deleted from all services, there's no need to keep it around anymore

NSUInteger i = 0;
NSArray *dnArray = [deletedNotes allObjects];
for (i = 0; i<[dnArray count]; i++) {
DeletedNoteObject *dnObj = [dnArray objectAtIndex:i];
if (![[dnObj syncServicesMD] count]) {
[deletedNotes removeObject:dnObj];
notesChanged = YES;
}
}
//NSLog(@"%s: deleted notes left: %@", _cmd, deletedNotes);
}

- (DeletedNoteObject*)_addDeletedNote:(id<SynchronizedNote>)aNote {
//currently coupled to -[allNotes removeObjectIdenticalTo:]
//don't need to remember this deleted note unless it was already synced with some service
//furthermore, after that deleted note has been remotely-removed from all services with which it was previously synced,
//can it be purged from this database once and for all?
//e.g., each successful syncservice deletion would also remove that service's entry from syncServicesMD
//when syncServicesMD was empty, it would be removed from the set
//but what about synchronization systems without explicit delete APIs?

if ([[aNote syncServicesMD] count]) {
//it is important to use the actual deleted note if one is passed
DeletedNoteObject *deletedNote = [aNote isKindOfClass:[DeletedNoteObject class]] ? aNote : [DeletedNoteObject deletedNoteWithNote:aNote];
[deletedNotes addObject:deletedNote];
return deletedNote;
}
return nil;
}

- (void)removeSyncMDFromDeletedNotesInSet:(NSSet*)notesToOrphan forService:(NSString*)serviceName {
NSMutableSet *matchingNotes = [deletedNotes setIntersectedWithSet:notesToOrphan];
[matchingNotes makeObjectsPerformSelector:@selector(removeAllSyncMDForService:) withObject:serviceName];
}

- (void)_registerDeletionUndoForNote:(NoteObject*)aNote {
[undoManager registerUndoWithTarget:self selector:@selector(addNewNote:) object:aNote];
if (![undoManager isUndoing] && ![undoManager isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Delete quotemark%@quotemark",@"undo action name for deleting a single note"), titleOfNote(aNote)]];
}


- (void)setUndoManager:(NSUndoManager*)anUndoManager {
    [undoManager autorelease];
    undoManager = [anUndoManager retain];
}

- (NSUndoManager*)undoManager {
    return undoManager;
}

- (void)updateDateStringsIfNecessary {

unsigned int currentHours = hoursFromAbsoluteTime(CFAbsoluteTimeGetCurrent());

if (currentHours != lastCheckedDateInHours) {
lastCheckedDateInHours = currentHours;

[delegate notationListMightChange:self];
resetCurrentDayTime();
[allNotes makeObjectsPerformSelector:@selector(updateDateStrings)];
[delegate notationListDidChange:self];
}
}

- (void)restyleAllNotes {
NSFont *baseFont = [notationPrefs baseBodyFont];
NSAssert(baseFont != nil, @"base body font from notation prefs should ALWAYS be valid!");

[allNotes makeObjectsPerformSelector:@selector(updateUnstyledTextWithBaseFont:) withObject:baseFont];

[notationPrefs setBaseBodyFont:[prefsController noteBodyFont]];
}

//used by BookmarksController

- (NoteObject*)noteForUUIDBytes:(CFUUIDBytes*)bytes {
NSUInteger noteIndex = [allNotes indexOfNoteWithUUIDBytes:bytes];
if (noteIndex != NSNotFound) return [allNotes objectAtIndex:noteIndex];
return nil;
}

//re-searching for all notes each time a label is added or removed is unnecessary, I think
- (void)note:(NoteObject*)note didAddLabelSet:(NSSet*)labelSet {
[labelsListController addLabelSet:labelSet toNote:note];
        
    //this can only happen while the note is visible

//[self refilterNotes];
}

- (void)note:(NoteObject*)note didRemoveLabelSet:(NSSet*)labelSet {
[labelsListController removeLabelSet:labelSet fromNote:note];
        
//[self refilterNotes];
}

- (void)filterNotesFromLabelAtIndex:(int)labelIndex {
NSArray *notes = [[labelsListController notesAtFilteredIndex:labelIndex] allObjects];

[delegate notationListMightChange:self];
[notesListDataSource fillArrayFromArray:notes];

[delegate notationListDidChange:self];
}

- (void)filterNotesFromLabelIndexSet:(NSIndexSet*)indexSet {
NSArray *notes = [[labelsListController notesAtFilteredIndexes:indexSet] allObjects];

[delegate notationListMightChange:self];
[notesListDataSource fillArrayFromArray:notes];

[delegate notationListDidChange:self];
}

- (BOOL)filterNotesFromString:(NSString*)string {

[delegate notationListMightChange:self];
if ([self filterNotesFromUTF8String:[string lowercaseUTF8String] forceUncached:NO]) {
[delegate notationListDidChange:self];

return YES;
}

return NO;
}

- (void)refilterNotes {

    [delegate notationListMightChange:self];
    [self filterNotesFromUTF8String:(currentFilterStr ? currentFilterStr : "") forceUncached:YES];
    [delegate notationListDidChange:self];
}

- (BOOL)filterNotesFromUTF8String:(const char*)searchString forceUncached:(BOOL)forceUncached {
    BOOL stringHasExistingPrefix = YES;
    BOOL didFilterNotes = NO;
    size_t oldLen = 0, newLen = 0;
NSUInteger i, initialCount = [notesListDataSource count];
    
NSAssert(searchString != NULL, @"filterNotesFromUTF8String requires a non-NULL argument");

newLen = strlen(searchString);
    
//PHASE 1: determine whether notes can be searched from where they are--if not, start on all the notes
    if (!currentFilterStr || forceUncached || ((oldLen = strlen(currentFilterStr)) > newLen) ||
strncmp(currentFilterStr, searchString, oldLen)) {

//the search must be re-initialized; our strings don't have the same prefix

[notesListDataSource fillArrayFromArray:allNotes];
//[labelsListController unfilterLabels];

stringHasExistingPrefix = NO;
lastWordInFilterStr = 0;
didFilterNotes = YES;

// NSLog(@"filter: scanning all notes");
    }
    

//PHASE 2: actually search for notes
NoteFilterContext filterContext;

//if there is a quote character in the string, use that as a delimiter, as we will search by phrase
//perhaps we could add some additional delimiters like punctuation marks here
    char *token, *separators = (strchr(searchString, '"') ? "\"" : " :\t\r\n");
    manglingString = replaceString(manglingString, searchString);
    
    BOOL touchedNotes = NO;
    
    if (!didFilterNotes || newLen > 0) {
//only bother searching each note if we're actually searching for something
//otherwise, filtered notes already reflect all-notes-state

char *preMangler = manglingString + lastWordInFilterStr;
while ((token = strsep(&preMangler, separators))) {

if (*token != '\0') {
//if this is the same token that we had scanned previously
filterContext.useCachedPositions = stringHasExistingPrefix && (token == manglingString + lastWordInFilterStr);
filterContext.needle = token;

touchedNotes = YES;

if ([notesListDataSource filterArrayUsingFunction:(BOOL (*)(id, void*))noteContainsUTF8String context:&filterContext])
didFilterNotes = YES;

lastWordInFilterStr = token - manglingString;
}
}
    }
    
//PHASE 3: reset found pointers in case have been cleared
NSUInteger filteredNoteCount = [notesListDataSource count];
NoteObject **notesBuffer = [notesListDataSource immutableObjects];

    if (didFilterNotes) {

if (!touchedNotes) {
//I can't think of any situation where notes were filtered and not touched--EXCEPT WHEN REMOVING A NOTE (>= vs. ==)
assert(filteredNoteCount >= [allNotes count]);

//reset found-ptr values; the search string was effectively blank and so no notes were examined
for (i=0; i<filteredNoteCount; i++)
resetFoundPtrsForNote(notesBuffer[i]);
}

//we have to re-create the array at each iteration while searching notes, but not here, so we can wait until the end
//[labelsListController recomputeListFromFilteredSet];
    }
    
//PHASE 4: autocomplete based on results
//even if the controller didn't filter, the search string could have changed its representation wrt spacing
//which will still influence note title prefixes
selectedNoteIndex = NSNotFound;

    if (newLen && [prefsController autoCompleteSearches]) {
//TODO: this should match the note with the shortest title first
for (i=0; i<filteredNoteCount; i++) {
//because we already searched word-by-word up there, this is just way simpler
if (noteTitleHasPrefixOfUTF8String(notesBuffer[i], searchString, newLen)) {
selectedNoteIndex = i;
break;
}
}
    }
    
    currentFilterStr = replaceString(currentFilterStr, searchString);

if (!initialCount && initialCount == filteredNoteCount)
return NO;
    
    return didFilterNotes;
}

- (NSUInteger)preferredSelectedNoteIndex {
    return selectedNoteIndex;
}
- (BOOL)preferredSelectedNoteMatchesSearchString {
NoteObject *obj = [self noteObjectAtFilteredIndex:selectedNoteIndex];
if (obj) return noteTitleMatchesUTF8String(obj, currentFilterStr);
return NO;
}

- (NoteObject*)noteObjectAtFilteredIndex:(int)noteIndex {
unsigned int theIndex = (unsigned int)noteIndex;

if (theIndex < [notesListDataSource count])
return [notesListDataSource immutableObjects][theIndex];

return nil;
}

- (NSArray*)notesAtIndexes:(NSIndexSet*)indexSet {
return [notesListDataSource objectsAtFilteredIndexes:indexSet];
}

//O(n^2) at best, but at least we're dealing with C arrays

- (NSIndexSet*)indexesOfNotes:(NSArray*)noteArray {
NSMutableIndexSet *noteIndexes = [[NSMutableIndexSet alloc] init];

NSUInteger i, noteCount = [noteArray count];

id *notes = (id*)malloc(noteCount * sizeof(id));
[noteArray getObjects:notes];

for (i=0; i<noteCount; i++) {
NSUInteger noteIndex = [notesListDataSource indexOfObjectIdenticalTo:notes[i]];

if (noteIndex != NSNotFound)
[noteIndexes addIndex:noteIndex];
}

free(notes);

return [noteIndexes autorelease];
}

- (NSUInteger)indexInFilteredListForNoteIdenticalTo:(NoteObject*)note {
return [notesListDataSource indexOfObjectIdenticalTo:note];
}

- (NSUInteger)totalNoteCount {
return [allNotes count];
}

- (NoteAttributeColumn*)sortColumn {
return sortColumn;
}

- (void)setSortColumn:(NoteAttributeColumn*)col {

    [sortColumn release];
sortColumn = [col retain];

[self sortAndRedisplayNotes];
}

//re-sort without refiltering, to avoid removing notes currently being edited
- (void)sortAndRedisplayNotes {

[delegate notationListMightChange:self];

NoteAttributeColumn *col = sortColumn;
if (col) {
BOOL reversed = [prefsController tableIsReverseSorted];
NSInteger (*sortFunction) (id *, id *) = (reversed ? [col reverseSortFunction] : [col sortFunction]);
NSInteger (*stringSortFunction) (id*, id*) = (reversed ? compareTitleStringReverse : compareTitleString);

[allNotes sortStableUsingFunction:stringSortFunction usingBuffer:&allNotesBuffer ofSize:&allNotesBufferSize];
if (sortFunction != stringSortFunction)
[allNotes sortStableUsingFunction:sortFunction usingBuffer:&allNotesBuffer ofSize:&allNotesBufferSize];


if ([notesListDataSource count] != [allNotes count]) {

[notesListDataSource sortStableUsingFunction:stringSortFunction];
if (sortFunction != stringSortFunction)
[notesListDataSource sortStableUsingFunction:sortFunction];

} else {
//mirror from allNotes; notesListDataSource is not filtered
[notesListDataSource fillArrayFromArray:allNotes];
}

[delegate notationListDidChange:self];
}
}

- (void)resortAllNotes {

NoteAttributeColumn *col = sortColumn;

if (col) {
BOOL reversed = [prefsController tableIsReverseSorted];

NSInteger (*sortFunction) (id*, id*) = (reversed ? [col reverseSortFunction] : [col sortFunction]);
NSInteger (*stringSortFunction) (id*, id*) = (reversed ? compareTitleStringReverse : compareTitleString);

[allNotes sortStableUsingFunction:stringSortFunction usingBuffer:&allNotesBuffer ofSize:&allNotesBufferSize];
if (sortFunction != stringSortFunction)
[allNotes sortStableUsingFunction:sortFunction usingBuffer:&allNotesBuffer ofSize:&allNotesBufferSize];
}
}

- (float)titleColumnWidth {
return titleColumnWidth;
}

- (void)regeneratePreviewsForColumn:(NSTableColumn*)col visibleFilteredRows:(NSRange)rows forceUpdate:(BOOL)force {

float width = [col width] - [NSScroller scrollerWidthForControlSize:NSRegularControlSize];

if (force || roundf(width) != roundf(titleColumnWidth)) {
titleColumnWidth = width;

//regenerate previews for visible rows immediately and post a delayed message to regenerate previews for all rows
if (rows.length > 0) {
CFArrayRef visibleNotes = CFArrayCreate(NULL, (const void **)([notesListDataSource immutableObjects] + rows.location), rows.length, NULL);
[(NSArray*)visibleNotes makeObjectsPerformSelector:@selector(updateTablePreviewString)];
CFRelease(visibleNotes);
}

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(regenerateAllPreviews) object:nil];
[self performSelector:@selector(regenerateAllPreviews) withObject:nil afterDelay:0.0];
}
}

- (void)regenerateAllPreviews {
[allNotes makeObjectsPerformSelector:@selector(updateTablePreviewString)];
}

- (id)labelsListDataSource {
    return labelsListController;
}

- (id)notesListDataSource {
    return notesListDataSource;
}

- (SyncSessionController*)syncSessionController {
return syncSessionController;
}

- (void)dealloc {
    
    DisposeFNSubscriptionUPP(subscriptionCallback);
if (fsCatInfoArray)
free(fsCatInfoArray);
if (HFSUniNameArray)
free(HFSUniNameArray);
    if (catalogEntries)
free(catalogEntries);
    if (sortedCatalogEntries)
free(sortedCatalogEntries);
    if (allNotesBuffer)
free(allNotesBuffer);

    [undoManager release];
    [notesListDataSource release];
    [labelsListController release];
[syncSessionController release];
    [allNotes release];
[deletedNotes release];
[notationPrefs release];
[unwrittenNotes release];
    
    [super dealloc];
}

@end
Something went wrong with that request. Please try again.