/Mac/Modules/MacOS.c

http://unladen-swallow.googlecode.com/ · C · 730 lines · 536 code · 120 blank · 74 comment · 90 complexity · ede3df0108238092016359eb41122189 MD5 · raw file

  1. /***********************************************************
  2. Copyright 1991-1997 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4. All Rights Reserved
  5. Permission to use, copy, modify, and distribute this software and its
  6. documentation for any purpose and without fee is hereby granted,
  7. provided that the above copyright notice appear in all copies and that
  8. both that copyright notice and this permission notice appear in
  9. supporting documentation, and that the names of Stichting Mathematisch
  10. Centrum or CWI not be used in advertising or publicity pertaining to
  11. distribution of the software without specific, written prior permission.
  12. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  13. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  14. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  15. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  16. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  17. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  18. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  19. ******************************************************************/
  20. /* Macintosh OS-specific interface */
  21. #include "Python.h"
  22. #include "pymactoolbox.h"
  23. #include <Carbon/Carbon.h>
  24. #include <ApplicationServices/ApplicationServices.h>
  25. #ifndef HAVE_OSX105_SDK
  26. typedef SInt16 FSIORefNum;
  27. #endif
  28. static PyObject *MacOS_Error; /* Exception MacOS.Error */
  29. #define PATHNAMELEN 1024
  30. /* ----------------------------------------------------- */
  31. /* Declarations for objects of type Resource fork */
  32. typedef struct {
  33. PyObject_HEAD
  34. FSIORefNum fRefNum;
  35. int isclosed;
  36. } rfobject;
  37. static PyTypeObject Rftype;
  38. /* ---------------------------------------------------------------- */
  39. static void
  40. do_close(rfobject *self)
  41. {
  42. if (self->isclosed ) return;
  43. (void)FSCloseFork(self->fRefNum);
  44. self->isclosed = 1;
  45. }
  46. static char rf_read__doc__[] =
  47. "Read data from resource fork"
  48. ;
  49. static PyObject *
  50. rf_read(rfobject *self, PyObject *args)
  51. {
  52. long n;
  53. PyObject *v;
  54. OSErr err;
  55. ByteCount n2;
  56. if (self->isclosed) {
  57. PyErr_SetString(PyExc_ValueError, "Operation on closed file");
  58. return NULL;
  59. }
  60. if (!PyArg_ParseTuple(args, "l", &n))
  61. return NULL;
  62. v = PyBytes_FromStringAndSize((char *)NULL, n);
  63. if (v == NULL)
  64. return NULL;
  65. err = FSReadFork(self->fRefNum, fsAtMark, 0, n, PyString_AsString(v), &n2);
  66. if (err && err != eofErr) {
  67. PyMac_Error(err);
  68. Py_DECREF(v);
  69. return NULL;
  70. }
  71. _PyString_Resize(&v, n2);
  72. return v;
  73. }
  74. static char rf_write__doc__[] =
  75. "Write to resource fork"
  76. ;
  77. static PyObject *
  78. rf_write(rfobject *self, PyObject *args)
  79. {
  80. char *buffer;
  81. long size;
  82. OSErr err;
  83. if (self->isclosed) {
  84. PyErr_SetString(PyExc_ValueError, "Operation on closed file");
  85. return NULL;
  86. }
  87. if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
  88. return NULL;
  89. err = FSWriteFork(self->fRefNum, fsAtMark, 0, size, buffer, NULL);
  90. if (err) {
  91. PyMac_Error(err);
  92. return NULL;
  93. }
  94. Py_INCREF(Py_None);
  95. return Py_None;
  96. }
  97. static char rf_seek__doc__[] =
  98. "Set file position"
  99. ;
  100. static PyObject *
  101. rf_seek(rfobject *self, PyObject *args)
  102. {
  103. long amount;
  104. int whence = SEEK_SET;
  105. int mode;
  106. OSErr err;
  107. if (self->isclosed) {
  108. PyErr_SetString(PyExc_ValueError, "Operation on closed file");
  109. return NULL;
  110. }
  111. if (!PyArg_ParseTuple(args, "l|i", &amount, &whence)) {
  112. return NULL;
  113. }
  114. switch (whence) {
  115. case SEEK_CUR:
  116. mode = fsFromMark;
  117. break;
  118. case SEEK_END:
  119. mode = fsFromLEOF;
  120. break;
  121. case SEEK_SET:
  122. mode = fsFromStart;
  123. break;
  124. default:
  125. PyErr_BadArgument();
  126. return NULL;
  127. }
  128. err = FSSetForkPosition(self->fRefNum, mode, amount);
  129. if (err != noErr) {
  130. PyMac_Error(err);
  131. return NULL;
  132. }
  133. Py_INCREF(Py_None);
  134. return Py_None;
  135. }
  136. static char rf_tell__doc__[] =
  137. "Get file position"
  138. ;
  139. static PyObject *
  140. rf_tell(rfobject *self, PyObject *args)
  141. {
  142. long long where;
  143. OSErr err;
  144. if (self->isclosed) {
  145. PyErr_SetString(PyExc_ValueError, "Operation on closed file");
  146. return NULL;
  147. }
  148. if (!PyArg_ParseTuple(args, ""))
  149. return NULL;
  150. err = FSGetForkPosition(self->fRefNum, &where);
  151. if (err != noErr) {
  152. PyMac_Error(err);
  153. return NULL;
  154. }
  155. return PyLong_FromLongLong(where);
  156. }
  157. static char rf_close__doc__[] =
  158. "Close resource fork"
  159. ;
  160. static PyObject *
  161. rf_close(rfobject *self, PyObject *args)
  162. {
  163. if (!PyArg_ParseTuple(args, ""))
  164. return NULL;
  165. do_close(self);
  166. Py_INCREF(Py_None);
  167. return Py_None;
  168. }
  169. static struct PyMethodDef rf_methods[] = {
  170. {"read", (PyCFunction)rf_read, 1, rf_read__doc__},
  171. {"write", (PyCFunction)rf_write, 1, rf_write__doc__},
  172. {"seek", (PyCFunction)rf_seek, 1, rf_seek__doc__},
  173. {"tell", (PyCFunction)rf_tell, 1, rf_tell__doc__},
  174. {"close", (PyCFunction)rf_close, 1, rf_close__doc__},
  175. {NULL, NULL} /* sentinel */
  176. };
  177. /* ---------- */
  178. static rfobject *
  179. newrfobject(void)
  180. {
  181. rfobject *self;
  182. self = PyObject_NEW(rfobject, &Rftype);
  183. if (self == NULL)
  184. return NULL;
  185. self->isclosed = 1;
  186. return self;
  187. }
  188. static void
  189. rf_dealloc(rfobject *self)
  190. {
  191. do_close(self);
  192. PyObject_DEL(self);
  193. }
  194. static PyObject *
  195. rf_getattr(rfobject *self, char *name)
  196. {
  197. return Py_FindMethod(rf_methods, (PyObject *)self, name);
  198. }
  199. static char Rftype__doc__[] =
  200. "Resource fork file object"
  201. ;
  202. static PyTypeObject Rftype = {
  203. PyObject_HEAD_INIT(&PyType_Type)
  204. 0, /*ob_size*/
  205. "MacOS.ResourceFork", /*tp_name*/
  206. sizeof(rfobject), /*tp_basicsize*/
  207. 0, /*tp_itemsize*/
  208. /* methods */
  209. (destructor)rf_dealloc, /*tp_dealloc*/
  210. (printfunc)0, /*tp_print*/
  211. (getattrfunc)rf_getattr, /*tp_getattr*/
  212. (setattrfunc)0, /*tp_setattr*/
  213. (cmpfunc)0, /*tp_compare*/
  214. (reprfunc)0, /*tp_repr*/
  215. 0, /*tp_as_number*/
  216. 0, /*tp_as_sequence*/
  217. 0, /*tp_as_mapping*/
  218. (hashfunc)0, /*tp_hash*/
  219. (ternaryfunc)0, /*tp_call*/
  220. (reprfunc)0, /*tp_str*/
  221. /* Space for future expansion */
  222. 0L,0L,0L,0L,
  223. Rftype__doc__ /* Documentation string */
  224. };
  225. /* End of code for Resource fork objects */
  226. /* -------------------------------------------------------- */
  227. /*----------------------------------------------------------------------*/
  228. /* Miscellaneous File System Operations */
  229. static char getcrtp_doc[] = "Get MacOS 4-char creator and type for a file";
  230. static PyObject *
  231. MacOS_GetCreatorAndType(PyObject *self, PyObject *args)
  232. {
  233. PyObject *creator, *type, *res;
  234. OSErr err;
  235. FSRef ref;
  236. FSCatalogInfo cataloginfo;
  237. FileInfo* finfo;
  238. if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSRef, &ref)) {
  239. #ifndef __LP64__
  240. /* This function is documented to take an FSSpec as well,
  241. * which only works in 32-bit mode.
  242. */
  243. PyErr_Clear();
  244. FSSpec fss;
  245. FInfo info;
  246. if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSSpec, &fss))
  247. return NULL;
  248. if ((err = FSpGetFInfo(&fss, &info)) != noErr) {
  249. return PyErr_Mac(MacOS_Error, err);
  250. }
  251. creator = PyString_FromStringAndSize(
  252. (char *)&info.fdCreator, 4);
  253. type = PyString_FromStringAndSize((char *)&info.fdType, 4);
  254. res = Py_BuildValue("OO", creator, type);
  255. Py_DECREF(creator);
  256. Py_DECREF(type);
  257. return res;
  258. #else /* __LP64__ */
  259. return NULL;
  260. #endif /* __LP64__ */
  261. }
  262. err = FSGetCatalogInfo(&ref,
  263. kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
  264. NULL, NULL, NULL);
  265. if (err != noErr) {
  266. PyErr_Mac(MacOS_Error, err);
  267. return NULL;
  268. }
  269. if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
  270. /* Directory: doesn't have type/creator info.
  271. *
  272. * The specific error code is for backward compatibility with
  273. * earlier versions.
  274. */
  275. PyErr_Mac(MacOS_Error, fnfErr);
  276. return NULL;
  277. }
  278. finfo = (FileInfo*)&(cataloginfo.finderInfo);
  279. creator = PyString_FromStringAndSize((char*)&(finfo->fileCreator), 4);
  280. type = PyString_FromStringAndSize((char*)&(finfo->fileType), 4);
  281. res = Py_BuildValue("OO", creator, type);
  282. Py_DECREF(creator);
  283. Py_DECREF(type);
  284. return res;
  285. }
  286. static char setcrtp_doc[] = "Set MacOS 4-char creator and type for a file";
  287. static PyObject *
  288. MacOS_SetCreatorAndType(PyObject *self, PyObject *args)
  289. {
  290. ResType creator, type;
  291. FSRef ref;
  292. FileInfo* finfo;
  293. OSErr err;
  294. FSCatalogInfo cataloginfo;
  295. if (!PyArg_ParseTuple(args, "O&O&O&",
  296. PyMac_GetFSRef, &ref, PyMac_GetOSType, &creator, PyMac_GetOSType, &type)) {
  297. #ifndef __LP64__
  298. /* Try to handle FSSpec arguments, for backward compatibility */
  299. FSSpec fss;
  300. FInfo info;
  301. if (!PyArg_ParseTuple(args, "O&O&O&",
  302. PyMac_GetFSSpec, &fss, PyMac_GetOSType, &creator, PyMac_GetOSType, &type))
  303. return NULL;
  304. if ((err = FSpGetFInfo(&fss, &info)) != noErr)
  305. return PyErr_Mac(MacOS_Error, err);
  306. info.fdCreator = creator;
  307. info.fdType = type;
  308. if ((err = FSpSetFInfo(&fss, &info)) != noErr)
  309. return PyErr_Mac(MacOS_Error, err);
  310. Py_INCREF(Py_None);
  311. return Py_None;
  312. #else /* __LP64__ */
  313. return NULL;
  314. #endif /* __LP64__ */
  315. }
  316. err = FSGetCatalogInfo(&ref,
  317. kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
  318. NULL, NULL, NULL);
  319. if (err != noErr) {
  320. PyErr_Mac(MacOS_Error, err);
  321. return NULL;
  322. }
  323. if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
  324. /* Directory: doesn't have type/creator info.
  325. *
  326. * The specific error code is for backward compatibility with
  327. * earlier versions.
  328. */
  329. PyErr_Mac(MacOS_Error, fnfErr);
  330. return NULL;
  331. }
  332. finfo = (FileInfo*)&(cataloginfo.finderInfo);
  333. finfo->fileCreator = creator;
  334. finfo->fileType = type;
  335. err = FSSetCatalogInfo(&ref, kFSCatInfoFinderInfo, &cataloginfo);
  336. if (err != noErr) {
  337. PyErr_Mac(MacOS_Error, fnfErr);
  338. return NULL;
  339. }
  340. Py_INCREF(Py_None);
  341. return Py_None;
  342. }
  343. static char geterr_doc[] = "Convert OSErr number to string";
  344. static PyObject *
  345. MacOS_GetErrorString(PyObject *self, PyObject *args)
  346. {
  347. int err;
  348. char buf[256];
  349. Handle h;
  350. char *str;
  351. static int errors_loaded;
  352. if (!PyArg_ParseTuple(args, "i", &err))
  353. return NULL;
  354. h = GetResource('Estr', err);
  355. if (!h && !errors_loaded) {
  356. /*
  357. ** Attempt to open the resource file containing the
  358. ** Estr resources. We ignore all errors. We also try
  359. ** this only once.
  360. */
  361. PyObject *m, *rv;
  362. errors_loaded = 1;
  363. m = PyImport_ImportModuleNoBlock("macresource");
  364. if (!m) {
  365. if (Py_VerboseFlag)
  366. PyErr_Print();
  367. PyErr_Clear();
  368. }
  369. else {
  370. rv = PyObject_CallMethod(m, "open_error_resource", "");
  371. if (!rv) {
  372. if (Py_VerboseFlag)
  373. PyErr_Print();
  374. PyErr_Clear();
  375. }
  376. else {
  377. Py_DECREF(rv);
  378. /* And try again... */
  379. h = GetResource('Estr', err);
  380. }
  381. Py_DECREF(m);
  382. }
  383. }
  384. /*
  385. ** Whether the code above succeeded or not, we won't try
  386. ** again.
  387. */
  388. errors_loaded = 1;
  389. if (h) {
  390. HLock(h);
  391. str = (char *)*h;
  392. memcpy(buf, str+1, (unsigned char)str[0]);
  393. buf[(unsigned char)str[0]] = '\0';
  394. HUnlock(h);
  395. ReleaseResource(h);
  396. }
  397. else {
  398. PyOS_snprintf(buf, sizeof(buf), "Mac OS error code %d", err);
  399. }
  400. return Py_BuildValue("s", buf);
  401. }
  402. #ifndef __LP64__
  403. static char splash_doc[] = "Open a splash-screen dialog by resource-id (0=close)";
  404. static PyObject *
  405. MacOS_splash(PyObject *self, PyObject *args)
  406. {
  407. int resid = -1;
  408. static DialogPtr curdialog = NULL;
  409. DialogPtr olddialog;
  410. WindowRef theWindow;
  411. CGrafPtr thePort;
  412. #if 0
  413. short xpos, ypos, width, height, swidth, sheight;
  414. #endif
  415. if (!PyArg_ParseTuple(args, "|i", &resid))
  416. return NULL;
  417. olddialog = curdialog;
  418. curdialog = NULL;
  419. if ( resid != -1 ) {
  420. curdialog = GetNewDialog(resid, NULL, (WindowPtr)-1);
  421. if ( curdialog ) {
  422. theWindow = GetDialogWindow(curdialog);
  423. thePort = GetWindowPort(theWindow);
  424. #if 0
  425. width = thePort->portRect.right - thePort->portRect.left;
  426. height = thePort->portRect.bottom - thePort->portRect.top;
  427. swidth = qd.screenBits.bounds.right - qd.screenBits.bounds.left;
  428. sheight = qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - LMGetMBarHeight();
  429. xpos = (swidth-width)/2;
  430. ypos = (sheight-height)/5 + LMGetMBarHeight();
  431. MoveWindow(theWindow, xpos, ypos, 0);
  432. ShowWindow(theWindow);
  433. #endif
  434. DrawDialog(curdialog);
  435. }
  436. }
  437. if (olddialog)
  438. DisposeDialog(olddialog);
  439. Py_INCREF(Py_None);
  440. return Py_None;
  441. }
  442. static char DebugStr_doc[] = "Switch to low-level debugger with a message";
  443. static PyObject *
  444. MacOS_DebugStr(PyObject *self, PyObject *args)
  445. {
  446. Str255 message;
  447. PyObject *object = 0;
  448. if (!PyArg_ParseTuple(args, "O&|O", PyMac_GetStr255, message, &object))
  449. return NULL;
  450. DebugStr(message);
  451. Py_INCREF(Py_None);
  452. return Py_None;
  453. }
  454. static char SysBeep_doc[] = "BEEEEEP!!!";
  455. static PyObject *
  456. MacOS_SysBeep(PyObject *self, PyObject *args)
  457. {
  458. int duration = 6;
  459. if (!PyArg_ParseTuple(args, "|i", &duration))
  460. return NULL;
  461. SysBeep(duration);
  462. Py_INCREF(Py_None);
  463. return Py_None;
  464. }
  465. #endif /* __LP64__ */
  466. static char WMAvailable_doc[] =
  467. "True if this process can interact with the display."
  468. "Will foreground the application on the first call as a side-effect."
  469. ;
  470. static PyObject *
  471. MacOS_WMAvailable(PyObject *self, PyObject *args)
  472. {
  473. static PyObject *rv = NULL;
  474. if (!PyArg_ParseTuple(args, ""))
  475. return NULL;
  476. if (!rv) {
  477. ProcessSerialNumber psn;
  478. /*
  479. ** This is a fairly innocuous call to make if we don't have a window
  480. ** manager, or if we have no permission to talk to it. It will print
  481. ** a message on stderr, but at least it won't abort the process.
  482. ** It appears the function caches the result itself, and it's cheap, so
  483. ** no need for us to cache.
  484. */
  485. #ifdef kCGNullDirectDisplay
  486. /* On 10.1 CGMainDisplayID() isn't available, and
  487. ** kCGNullDirectDisplay isn't defined.
  488. */
  489. if (CGMainDisplayID() == 0) {
  490. rv = Py_False;
  491. } else {
  492. #else
  493. {
  494. #endif
  495. if (GetCurrentProcess(&psn) < 0 ||
  496. SetFrontProcess(&psn) < 0) {
  497. rv = Py_False;
  498. } else {
  499. rv = Py_True;
  500. }
  501. }
  502. }
  503. Py_INCREF(rv);
  504. return rv;
  505. }
  506. static char GetTicks_doc[] = "Return number of ticks since bootup";
  507. static PyObject *
  508. MacOS_GetTicks(PyObject *self, PyObject *args)
  509. {
  510. return Py_BuildValue("i", (int)TickCount());
  511. }
  512. static char openrf_doc[] = "Open resource fork of a file";
  513. static PyObject *
  514. MacOS_openrf(PyObject *self, PyObject *args)
  515. {
  516. OSErr err;
  517. char *mode = "r";
  518. FSRef ref;
  519. SInt8 permission = fsRdPerm;
  520. rfobject *fp;
  521. HFSUniStr255 name;
  522. if (!PyArg_ParseTuple(args, "O&|s", PyMac_GetFSRef, &ref, &mode))
  523. return NULL;
  524. while (*mode) {
  525. switch (*mode++) {
  526. case '*': break;
  527. case 'r': permission = fsRdPerm; break;
  528. case 'w': permission = fsWrPerm; break;
  529. case 'b': break;
  530. default:
  531. PyErr_BadArgument();
  532. return NULL;
  533. }
  534. }
  535. err = FSGetResourceForkName(&name);
  536. if (err != noErr) {
  537. PyMac_Error(err);
  538. return NULL;
  539. }
  540. if ( (fp = newrfobject()) == NULL )
  541. return NULL;
  542. err = FSOpenFork(&ref, name.length, name.unicode, permission, &fp->fRefNum);
  543. if (err != noErr) {
  544. Py_DECREF(fp);
  545. PyMac_Error(err);
  546. return NULL;
  547. }
  548. fp->isclosed = 0;
  549. return (PyObject *)fp;
  550. }
  551. static PyMethodDef MacOS_Methods[] = {
  552. {"GetCreatorAndType", MacOS_GetCreatorAndType, 1, getcrtp_doc},
  553. {"SetCreatorAndType", MacOS_SetCreatorAndType, 1, setcrtp_doc},
  554. {"GetErrorString", MacOS_GetErrorString, 1, geterr_doc},
  555. {"openrf", MacOS_openrf, 1, openrf_doc},
  556. #ifndef __LP64__
  557. {"splash", MacOS_splash, 1, splash_doc},
  558. {"DebugStr", MacOS_DebugStr, 1, DebugStr_doc},
  559. {"SysBeep", MacOS_SysBeep, 1, SysBeep_doc},
  560. #endif /* __LP64__ */
  561. {"GetTicks", MacOS_GetTicks, 1, GetTicks_doc},
  562. {"WMAvailable", MacOS_WMAvailable, 1, WMAvailable_doc},
  563. {NULL, NULL} /* Sentinel */
  564. };
  565. void
  566. initMacOS(void)
  567. {
  568. PyObject *m, *d;
  569. if (PyErr_WarnPy3k("In 3.x, MacOS is removed.", 1))
  570. return;
  571. m = Py_InitModule("MacOS", MacOS_Methods);
  572. d = PyModule_GetDict(m);
  573. /* Initialize MacOS.Error exception */
  574. MacOS_Error = PyMac_GetOSErrException();
  575. if (MacOS_Error == NULL || PyDict_SetItemString(d, "Error", MacOS_Error) != 0)
  576. return;
  577. Rftype.ob_type = &PyType_Type;
  578. Py_INCREF(&Rftype);
  579. if (PyDict_SetItemString(d, "ResourceForkType", (PyObject *)&Rftype) != 0)
  580. return;
  581. /*
  582. ** This is a hack: the following constant added to the id() of a string
  583. ** object gives you the address of the data. Unfortunately, it is needed for
  584. ** some of the image and sound processing interfaces on the mac:-(
  585. */
  586. {
  587. PyStringObject *p = 0;
  588. long off = (long)&(p->ob_sval[0]);
  589. if( PyDict_SetItemString(d, "string_id_to_buffer", Py_BuildValue("i", off)) != 0)
  590. return;
  591. }
  592. #define PY_RUNTIMEMODEL "macho"
  593. if (PyDict_SetItemString(d, "runtimemodel",
  594. Py_BuildValue("s", PY_RUNTIMEMODEL)) != 0)
  595. return;
  596. #if defined(WITH_NEXT_FRAMEWORK)
  597. #define PY_LINKMODEL "framework"
  598. #elif defined(Py_ENABLE_SHARED)
  599. #define PY_LINKMODEL "shared"
  600. #else
  601. #define PY_LINKMODEL "static"
  602. #endif
  603. if (PyDict_SetItemString(d, "linkmodel",
  604. Py_BuildValue("s", PY_LINKMODEL)) != 0)
  605. return;
  606. }