Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: abc26d9f6d
Fetching contributors…

Cannot retrieve contributors at this time

file 571 lines (503 sloc) 17.531 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
#import <Cocoa/Cocoa.h>
#import <getopt.h>
#import <fcntl.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
#import <unistd.h>
#import <errno.h>
#import <vector>
#import <string>
#import <sys/stat.h>

#import "TMDSemaphore.h"
#include "TMDSemaphore.mm" // TODO we should really export this from the plugin instead and link against the plugin
#import "Dialog.h"

static char const* const AppName = "tm_dialog";
static double const AppVersion = 1.0;
static size_t const AppRevision = APP_REVISION;

id read_property_list_from_data (NSData* data)
{
if([data length] == 0)
return nil;

NSString* error = nil;
id plist = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:&error];

if(error || !plist)
{
fprintf(stderr, "%s: %s\n", AppName, [error UTF8String] ?: "unknown error parsing property list");
fwrite([data bytes], [data length], 1, stderr);
fprintf(stderr, "\n");
}

return plist;
}

id read_property_list_from_string (char const* str)
{
return read_property_list_from_data([NSData dataWithBytes:str length:str ? strlen(str) : 0]);
}

id read_property_list_from_file (int fd)
{
NSMutableData* data = [NSMutableData data];

char buf[1024];
while(size_t len = read(fd, buf, sizeof(buf)))
[data appendBytes:buf length:len];

return read_property_list_from_data(data);
}

bool output_property_list (id plist)
{
bool res = false;
NSString* error = nil;
if(NSData* data = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:&error])
{
if(NSFileHandle* fh = [NSFileHandle fileHandleWithStandardOutput])
{
[fh writeData:data];
res = true;
}
}
else
{
fprintf(stderr, "%s: %s\n", AppName, [error UTF8String] ?: "unknown error serializing returned property list");
fprintf(stderr, "%s\n", [[plist description] UTF8String]);
}
return res;
}

// validate_proxy: return an instance of the TM dialog server proxy object. Return false (and write details to stderr)
// if the TM dialog server is unavailable or the protocol version doesn't match.
bool validate_proxy (id & outProxy)
{
static bool proxyValid = false;
static id proxy = nil;

// One shot validate -- if it isn't valid now, presumably it won't be ever
// (during the very short life of an instance of this tool)
if(not proxyValid)
{
NSString* portName = @"TextMate dialog server";
if(char const* var = getenv("DIALOG_1_PORT_NAME"))
portName = [NSString stringWithUTF8String:var];

proxy = [NSConnection rootProxyForConnectionWithRegisteredName:portName host:nil];
[proxy setProtocolForProxy:@protocol(TextMateDialogServerProtocol)];

if([proxy textMateDialogServerProtocolVersion] == TextMateDialogServerProtocolVersion)
{
proxyValid = true;
}
else
{
if(proxy)
{
int pluginVersion = [proxy textMateDialogServerProtocolVersion];
int toolVersion = TextMateDialogServerProtocolVersion;
if(pluginVersion < toolVersion)
{
fprintf(stderr, "%s: you have updated the tm_dialog tool to v%d but the Dialog plug-in running is still at v%d.\n", AppName, toolVersion, pluginVersion);
fprintf(stderr, "%s: either checkout the PlugIns folder from the repository or remove your checkout of the Support folder.\n", AppName);
fprintf(stderr, "%s: if you did checkout the PlugIns folder, you need to relaunch TextMate to load the new plug-in.\n", AppName);
}
else
{
fprintf(stderr, "%s: you have updated the Dialog plug-in to v%d but the tm_dialog tool is still at v%d\n", AppName, pluginVersion, toolVersion);
}
}
else
{
fprintf(stderr, "%s: failed to establish connection with TextMate.\n", AppName);
if(!getenv("DIALOG_1_PORT_NAME"))
{
fprintf(stderr, "%s:\n", AppName);
fprintf(stderr, "%s: When running outside TextMate you need to set the DIALOG_1_PORT_NAME environment variable.\n", AppName);
fprintf(stderr, "%s: In a new TextMate document press ^C on a line containing just: echo $DIALOG_1_PORT_NAME\n", AppName);
fprintf(stderr, "%s: Then in Terminal run: export DIALOG_1_PORT_NAME=«value»\n", AppName);
fprintf(stderr, "%s: Here «value» is the value you got from TextMate, e.g. ‘com.macromates.dialog_1.45850’.\n", AppName);
}
}
}
}

outProxy = proxy;
return proxyValid;
}

// contact_server_async_update: update (a subset of) the binding values.
int contact_server_async_update (const char* token, NSMutableDictionary* someParameters)
{
id proxy;
int returnCode = -1;

if(someParameters == nil)
{
fprintf(stderr, "%s: no property list given, skipping update\n", AppName);
}
else if(validate_proxy(proxy))
{
id result = [proxy updateNib:[NSString stringWithUTF8String:token] withParameters:someParameters];
returnCode = [[result objectForKey:@"returnCode"] intValue];

if(returnCode == -43)
{
fprintf(stderr, "%s (async_update): Window '%s' doesn't exist\n", AppName, token);
}
}
return returnCode;
}

// contact_server_async_close: close the window
int contact_server_async_close (const char* token, bool ignoreFailure)
{
id proxy;
int returnCode = -1;

if(validate_proxy(proxy))
{
id result = [proxy closeNib:[NSString stringWithUTF8String:token]];
returnCode = [[result objectForKey:@"returnCode"] intValue];

if(ignoreFailure)
{
returnCode = 0;
}
else
{
if(returnCode == -43)
{
fprintf(stderr, "%s (async_close): Window '%s' doesn't exist\n", AppName, token);
}
}
}

return returnCode;
}

// contact_server_async_wait: block until returnArgument:, performButtonClick:, or the window is closed,
// then output the resulting plist returned by the dialog server.
int contact_server_async_wait (const char* token)
{
id proxy;
int returnCode = -1;

if(validate_proxy(proxy))
{
id result;
TMDSemaphore * semaphore = [TMDSemaphore semaphoreForTokenString:token];

// Validate the window (throw away this result other than the returnCode)
result = [proxy retrieveNibResults:[NSString stringWithUTF8String:token]];
returnCode = [[result objectForKey:@"returnCode"] intValue];

if(returnCode == 0)
{
[semaphore wait];

result = [proxy retrieveNibResults:[NSString stringWithUTF8String:token]];
output_property_list(result);
}
else if(returnCode == -43)
{
fprintf(stderr, "%s (async_wait): Window '%s' doesn't exist\n", AppName, token);
}
else
{
fprintf(stderr, "%s (async_wait): Window '%s' error %d\n", AppName, token, returnCode);
}
}

return returnCode;
}


// contact_server_async_list: print a list of windows to stdout
int contact_server_async_list ()
{
id proxy;
int returnCode = -1;

if(validate_proxy(proxy))
{
id result = [proxy listNibTokens];
returnCode = [[result objectForKey:@"returnCode"] intValue];

if(returnCode != 0)
{
fprintf(stderr, "%s: Unknown error code '%d'\n", AppName, returnCode);
}
else
{
NSArray* nibs = [result objectForKey:@"nibs"];
enumerate(nibs, NSDictionary * nib)
{
NSString* windowTitleString = [nib objectForKey:@"windowTitle"];
const char* windowTitleC = "<no title>";
int windowToken = [[nib objectForKey:@"token"] intValue];

if(windowTitleString != nil
&& not [windowTitleString isEqualToString:@""])
{
windowTitleC = [windowTitleString UTF8String];
}
fprintf(stdout, "%d (%s)\n", windowToken, windowTitleC);
}
}
}

return returnCode;
}

// contact_server_show_nib: instantiate the nib inside TM
int contact_server_show_nib (std::string nibName, NSMutableDictionary* someParameters, NSDictionary* initialValues, NSDictionary* dynamicClasses, bool center, bool modal, bool quiet, bool async)
{
int res = -1;
id proxy;

if(validate_proxy(proxy))
{
NSString* aNibPath = [NSString stringWithUTF8String:nibName.c_str()];
NSDictionary* parameters = (NSDictionary*)[proxy showNib:aNibPath withParameters:(someParameters ?: [NSMutableDictionary dictionary]) andInitialValues:initialValues dynamicClasses:dynamicClasses modal:modal center:center async:async];

const char* token = [[NSString stringWithFormat:@"%@", [parameters objectForKey:@"token"]] UTF8String];

res = [[parameters objectForKey:@"returnCode"] intValue];

// Async mode: print just the token for the new window
if(res != 0)
{
fprintf(stderr, "Error %d creating window\n", res);
}
else
{
if(async)
{
fprintf(stdout, "%d\n", [[parameters objectForKey:@"token"] intValue]);
}
else if(modal)
{
// Modal: the window has already been ordered out; retrieve the results and close it.
if(validate_proxy(proxy) && not quiet)
{
id result = [proxy retrieveNibResults:[NSString stringWithUTF8String:token]];
output_property_list(result);

res = [[result objectForKey:@"returnCode"] intValue];
}
contact_server_async_close(token, false); // false -> log errors
}
else
{
// Not async, not modal. The task had better be detached from TM, or TM will hang
// until the task is killed. Wait until something happens.
res = contact_server_async_wait(token);
if(not quiet)
{
output_property_list(parameters);
}
contact_server_async_close(token, false); // false -> log errors
}
}
}
return res;
}

void usage ()
{
fprintf(stderr,
"%1$s %2$.1f (" COMPILE_DATE " revision %3$zu)\n"
"Usage (dialog): %1$s [-cdnmqp] nib_file\n"
"Usage (window): %1$s [-cdnpaxts] nib_file\n"
"Usage (alert): %1$s [-p] -e [-i|-c|-w]\n"
// "Usage (sheet): %1$s [-p] -e\n"
"Usage (menu): %1$s [-p] -u\n"
"\n"
"Dialog Options:\n"
      " -c, --center Center the window on screen.\n"
      " -d, --defaults <plist> Register initial values for user defaults.\n"
      " -n, --new-items <plist> A key/value list of classes (the key) which should dynamically be created at run-time for use as the NSArrayController’s object class. The value (a dictionary) is how instances of this class should be initialized (the actual instance will be an NSMutableDictionary with these values).\n"
      " -m, --modal Show window as modal (other windows will be inaccessible).\n"
      " -p, --parameters <plist> Provide parameters as a plist.\n"
      " -q, --quiet Do not write result to stdout.\n"
// " -s, --target-path <path> Attempt to display the window as a sheet on the window containing\n"
// " the given path. Applies to alerts and async windows only.\n"
      "\nAlert Options:\n"
      " -e, --alert Show alert. Parameters: 'title', 'message', 'buttons'\n"
" 'alertStyle' -- can be 'warning,' 'informational',\n"
" 'critical'. Returns the button index.\n"
      "Menu Options:\n"
      " -u, --menu Treat parameters as a menu structure.\n"
      "\nAsync Window Options:\n"
      " -a, --async-window Displays the window and returns a reference token for it\n"
      " in the output property list.\n"
      " -l, --list-windows List async window tokens.\n"
      " -t, --update-window <token> Update an async window with new parameter values.\n"
" Use the --parameters argument (or stdin) to specify the\n"
" updated parameters.\n"
      " -x, --close-window <token> Close and release an async window.\n"
      " -w, --wait-for-input <token> Wait for user input from the given async window.\n"
"\nNote:\n"
"If you DO NOT use the -m/--modal option,\n"
"OR you create an async window and then use the wait-for-input subcommand,\n"
"you must run tm_dialog in a detached/backgrounded process (`mycommand 2&>1 &` in bash).\n"
"Otherwise, TextMate's UI thread will hang, waiting for your command to complete.\n"
"You can recover from such a hang by killing the tm_dialog process in Terminal.\n"
"\n"
"", AppName, AppVersion, AppRevision);
}

std::string find_nib (std::string nibName)
{
std::vector<std::string> candidates;

if(nibName.find(".nib") == std::string::npos)
nibName += ".nib";

if(nibName.size() && nibName[0] != '/') // relative path
{
if(char const* currentPath = getcwd(NULL, 0))
candidates.push_back(currentPath + std::string("/") + nibName);

if(char const* bundleSupport = getenv("TM_BUNDLE_SUPPORT"))
candidates.push_back(bundleSupport + std::string("/nibs/") + nibName);

if(char const* supportPath = getenv("TM_SUPPORT_PATH"))
candidates.push_back(supportPath + std::string("/nibs/") + nibName);
}
else
{
candidates.push_back(nibName);
}

for(decltype(candidates.begin()) it = candidates.begin(); it != candidates.end(); ++it)
{
struct stat sb;
if(stat(it->c_str(), &sb) == 0)
return *it;
}

fprintf(stderr, "nib could not be loaded: %s (does not exist)\n", nibName.c_str());
abort();
return NULL;
}

id read_property_list_argument(const char* parameters)
{
id plist = nil;
if(parameters)
{
plist = read_property_list_from_string(parameters);
}
else
{
if(isatty(STDIN_FILENO) != 0)
fprintf(stderr, "%s: Reading parameters from stdin... (press CTRL-D to proceed)\n", AppName);
plist = read_property_list_from_file(STDIN_FILENO);
}

return plist;
}

int main (int argc, char* argv[])
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];

extern int optind;
extern char* optarg;

enum DialogAction
{
kShowDialog,
kShowMenu,
kShowAlert,
kAsyncCreate,
kAsyncClose,
kAsyncUpdate,
kAsyncList,
kAsyncWait,
};

static struct option const longopts[] = {
{ "alert", no_argument, 0, 'e' },
{ "center", no_argument, 0, 'c' },
{ "defaults", required_argument, 0, 'd' },
{ "new-items", required_argument, 0, 'n' },
{ "modal", no_argument, 0, 'm' },
{ "parameters", required_argument, 0, 'p' },
{ "quiet", no_argument, 0, 'q' },
{ "menu", no_argument, 0, 'u' },
{ "async-window", no_argument, 0, 'a' },
{ "close-window", required_argument, 0, 'x' },
{ "update-window", required_argument, 0, 't' },
{ "wait-for-input", required_argument, 0, 'w' },
{ "list-windows", no_argument, 0, 'l' },
{ 0, 0, 0, 0 }
};

bool center = false, modal = false, quiet = false;
char const* parameters = NULL;
char const* defaults = NULL;
char const* dynamicClassesPlist = NULL;
char const* token = NULL;
int ch;
DialogAction dialogAction = kShowDialog;

setprogname(AppName); // when called from tm_dialog2 (via execv()) our getprogname is wrong, which is used by getopt_long().
while((ch = getopt_long(argc, argv, "eacd:mn:p:quax:t:w:l", longopts, NULL)) != -1)
{
switch(ch)
{
case 'e': dialogAction = kShowAlert; break;
case 'c': center = true; break;
case 'd': defaults = optarg; break;
case 'm': modal = true; break;
case 'n': dynamicClassesPlist = optarg; break;
case 'p': parameters = optarg; break;
case 'q': quiet = true; break;
case 'u': dialogAction = kShowMenu; break;

case 'a': dialogAction = kAsyncCreate; break;
case 'x': dialogAction = kAsyncClose; token = optarg; break;
case 't': dialogAction = kAsyncUpdate; token = optarg; break;
case 'w': dialogAction = kAsyncWait; token = optarg; break;
case 'l': dialogAction = kAsyncList; break;

default: usage(); return 1;
}
}

argc -= optind;
argv += optind;

int res = -1;

if(dialogAction != kShowDialog)
{
if(modal)
fprintf(stderr, "%s: warning: Ignoring 'modal' option\n", AppName);

if(quiet)
fprintf(stderr, "%s: warning: Ignoring 'quiet' option.\n", AppName);
}

@try {

switch(dialogAction)
{
case kShowMenu:
if(argc == 0)
{
id proxy;
if(validate_proxy(proxy))
{
if(id plist = read_property_list_argument(parameters))
{
output_property_list([proxy showMenuWithOptions:plist]);
}
else
{
fprintf(stderr, "%s: no property list given\n", AppName);
}
}
}
else
{
usage();
}
break;
case kShowAlert:
if(argc == 0)
{
id proxy;
if(validate_proxy(proxy))
{
id plist = read_property_list_argument(parameters);
NSDictionary* output = [proxy showAlertForPath:nil withParameters:plist modal:YES];
printf("%d\n", [[output objectForKey:@"buttonClicked"] intValue]);
}
}
else
{
usage();
}
break;
case kShowDialog:
case kAsyncCreate:
{
id initialValues = read_property_list_from_string(defaults);
id dynamicClasses = read_property_list_from_string(dynamicClassesPlist);

if(argc == 1)
{
id plist = read_property_list_argument(parameters);
res = contact_server_show_nib(find_nib(argv[0]), plist, initialValues, dynamicClasses, center, modal, quiet, (dialogAction == kAsyncCreate));
}
else
{
usage();
}
} break;
case kAsyncUpdate:
{
id plist = read_property_list_argument(parameters);
res = contact_server_async_update(token, plist);
} break;
case kAsyncClose:
res = contact_server_async_close(token, false); // false -> generate errors
break;
case kAsyncWait:
res = contact_server_async_wait(token);
break;
case kAsyncList:
res = contact_server_async_list();
break;
default:
usage();
break;
}

} @catch(NSException* e) {
fprintf(stderr, "%s: %s\n", AppName, [[e reason] UTF8String]);
}

[pool release];
return res;
}
Something went wrong with that request. Please try again.