home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / source code / Mac / macglue.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-12-17  |  16.9 KB  |  729 lines  |  [TEXT/R*ch]

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. #include "Python.h"
  26.  
  27. #include "macglue.h"
  28. #include "marshal.h"
  29. #include "import.h"
  30.  
  31. #include "pythonresources.h"
  32.  
  33. #include <OSUtils.h> /* for Set(Current)A5 */
  34. #include <Files.h>
  35. #include <StandardFile.h>
  36. #include <Resources.h>
  37. #include <Memory.h>
  38. #include <Events.h>
  39. #include <Windows.h>
  40. #include <Desk.h>
  41. #include <Traps.h>
  42. #include <Processes.h>
  43. #include <Fonts.h>
  44. #include <Menus.h>
  45. #include <TextUtils.h>
  46. #ifdef THINK_C
  47. #include <OSEvents.h> /* For EvQElPtr */
  48. #endif
  49. #ifdef __MWERKS__
  50. #include <SIOUX.h>
  51. #endif
  52.  
  53. #ifndef HAVE_UNIVERSAL_HEADERS
  54. #define GetResourceSizeOnDisk(x) SizeResource(x)
  55. typedef DlgHookYDProcPtr DlgHookYDUPP;
  56. #define NewDlgHookYDProc(userRoutine) ((DlgHookYDUPP) (userRoutine))
  57. typedef FileFilterYDProcPtr FileFilterYDUPP;
  58. #endif
  59.  
  60. #include <signal.h>
  61. #include <stdio.h>
  62.  
  63. /*
  64. ** We have to be careful, since we can't handle
  65. ** things like updates (and they'll keep coming back if we don't
  66. ** handle them). Note that we don't know who has windows open, so
  67. ** even handing updates off to SIOUX under MW isn't going to work.
  68. */
  69. #define MAINLOOP_EVENTMASK (mDownMask|keyDownMask|osMask)
  70.  
  71. #include <signal.h>
  72.  
  73. /* XXX We should include Errors.h here, but it has a name conflict
  74. ** with the python errors.h. */
  75. #define fnfErr -43
  76.  
  77. /* Declared in macfsmodule.c: */
  78. extern FSSpec *mfs_GetFSSpecFSSpec();
  79.  
  80. /* Interrupt code variables: */
  81. static int interrupted;            /* Set to true when cmd-. seen */
  82. static RETSIGTYPE intcatcher Py_PROTO((int));
  83.  
  84. /*
  85. ** We attempt to be a good citizen by giving up the CPU periodically.
  86. ** When in the foreground we do this less often and for shorter periods
  87. ** than when in the background. At this time we also check for events and
  88. ** pass them off to SIOUX, if compiling with mwerks.
  89. ** The counts here are in ticks of 1/60th second.
  90. ** XXXX The initial values here are not based on anything.
  91. ** FG-python gives up the cpu for 1/60th 5 times per second,
  92. ** BG-python for .2 second 10 times per second.
  93. */
  94. static long interval_fg = 12;
  95. static long interval_bg = 6;
  96. static long yield_fg = 1;
  97. static long yield_bg = 12;
  98. static long lastyield;
  99. static int in_foreground;
  100.  
  101. /* 
  102. ** When > 0, do full scanning for events (program is not event aware)
  103. ** when == 0, only scan for Command-period
  104. ** when < 0, don't do any event scanning 
  105. */
  106. int PyMac_DoYieldEnabled = 1;
  107.  
  108. /*
  109. ** Some stuff for our GetDirectory and PromptGetFile routines
  110. */
  111. struct hook_args {
  112.     int selectcur_hit;        /* Set to true when "select current" selected */
  113.     char *prompt;            /* The prompt */
  114. };
  115. static DlgHookYDUPP myhook_upp;
  116. static int upp_inited = 0;
  117.  
  118.  
  119. /* Convert C to Pascal string. Returns pointer to static buffer. */
  120. unsigned char *
  121. Pstring(char *str)
  122. {
  123.     static Str255 buf;
  124.     int len;
  125.  
  126.     len = strlen(str);
  127.     if (len > 255)
  128.         len = 255;
  129.     buf[0] = (unsigned char)len;
  130.     strncpy((char *)buf+1, str, len);
  131.     return buf;
  132. }
  133.  
  134. /* Like strerror() but for Mac OS error numbers */
  135. char *PyMac_StrError(int err)
  136. {
  137.     static char buf[256];
  138.     Handle h;
  139.     char *str;
  140.     
  141.     h = GetResource('Estr', err);
  142.     if ( h ) {
  143.         HLock(h);
  144.         str = (char *)*h;
  145.         memcpy(buf, str+1, (unsigned char)str[0]);
  146.         buf[(unsigned char)str[0]] = '\0';
  147.         HUnlock(h);
  148.         ReleaseResource(h);
  149.     } else {
  150.         sprintf(buf, "Mac OS error code %d", err);
  151.     }
  152.     return buf;
  153. }
  154.  
  155. /* Exception object shared by all Mac specific modules for Mac OS errors */
  156. PyObject *PyMac_OSErrException;
  157.  
  158. /* Initialize and return PyMac_OSErrException */
  159. PyObject *
  160. PyMac_GetOSErrException()
  161. {
  162.     if (PyMac_OSErrException == NULL)
  163.         PyMac_OSErrException = PyString_FromString("Mac OS Error");
  164.     return PyMac_OSErrException;
  165. }
  166.  
  167. /* Set a MAC-specific error from errno, and return NULL; return None if no error */
  168. PyObject * 
  169. PyErr_Mac(PyObject *eobj, int err)
  170. {
  171.     char *msg;
  172.     PyObject *v;
  173.     
  174.     if (err == 0 && !PyErr_Occurred()) {
  175.         Py_INCREF(Py_None);
  176.         return Py_None;
  177.     }
  178.     if (err == -1 && PyErr_Occurred())
  179.         return NULL;
  180.     msg = PyMac_StrError(err);
  181.     v = Py_BuildValue("(is)", err, msg);
  182.     PyErr_SetObject(eobj, v);
  183.     Py_DECREF(v);
  184.     return NULL;
  185. }
  186.  
  187. /* Call PyErr_Mac with PyMac_OSErrException */
  188. PyObject *
  189. PyMac_Error(OSErr err)
  190. {
  191.     return PyErr_Mac(PyMac_GetOSErrException(), err);
  192. }
  193.  
  194. /* The catcher routine (which may not be used for all compilers) */
  195. static RETSIGTYPE
  196. intcatcher(sig)
  197.     int sig;
  198. {
  199.     interrupted = 1;
  200.     signal(SIGINT, intcatcher);
  201. }
  202.  
  203. void
  204. PyOS_InitInterrupts()
  205. {
  206.     if (signal(SIGINT, SIG_IGN) != SIG_IGN)
  207.         signal(SIGINT, intcatcher);
  208. }
  209.  
  210. /*
  211. ** This routine scans the event queue looking for cmd-.
  212. ** This is the only way to get an interrupt under THINK (since it
  213. ** doesn't do SIGINT handling), but is also used under MW, when
  214. ** the full-fledged event loop is disabled. This way, we can at least
  215. ** interrupt a runaway python program.
  216. */
  217. static void
  218. scan_event_queue(flush)
  219.     int flush;
  220. {
  221. #if defined(__MWERKS__) && defined(__CFM68K__)
  222.     return; /* No GetEvQHdr yet */
  223. #else
  224.     register EvQElPtr q;
  225.     
  226.     q = (EvQElPtr) GetEvQHdr()->qHead;
  227.     
  228.     for (; q; q = (EvQElPtr)q->qLink) {
  229.         if (q->evtQWhat == keyDown &&
  230.                 (char)q->evtQMessage == '.' &&
  231.                 (q->evtQModifiers & cmdKey) != 0) {
  232.             if ( flush )
  233.                 FlushEvents(keyDownMask, 0);
  234.             interrupted = 1;
  235.             break;
  236.         }
  237.     }
  238. #endif
  239. }
  240.  
  241. int
  242. PyOS_InterruptOccurred()
  243. {
  244.     if (PyMac_DoYieldEnabled < 0)
  245.         return 0;
  246. #ifdef THINK_C
  247.     scan_event_queue(1);
  248. #endif
  249.     PyMac_Yield();
  250.     if (interrupted) {
  251.         interrupted = 0;
  252.         return 1;
  253.     }
  254.     return 0;
  255. }
  256.  
  257. /* intrpeek() is like intrcheck(), but it doesn't flush the events. The
  258. ** idea is that you call intrpeek() somewhere in a busy-wait loop, and return
  259. ** None as soon as it returns 1. The mainloop will then pick up the cmd-. soon
  260. ** thereafter.
  261. */
  262. static int
  263. intrpeek()
  264. {
  265. #ifdef THINK_C
  266.     scan_event_queue(0);
  267. #endif
  268.     return interrupted;
  269. }
  270.  
  271. /* Check whether we are in the foreground */
  272. int
  273. PyMac_InForeground()
  274. {
  275.     static ProcessSerialNumber ours;
  276.     static inited;
  277.     ProcessSerialNumber curfg;
  278.     Boolean eq;
  279.     
  280.     if ( inited == 0 )
  281.         (void)GetCurrentProcess(&ours);
  282.     inited = 1;
  283.     if ( GetFrontProcess(&curfg) < 0 )
  284.         eq = 1;
  285.     else if ( SameProcess(&ours, &curfg, &eq) < 0 )
  286.         eq = 1;
  287.     return (int)eq;
  288.  
  289. }
  290.  
  291. /*
  292. ** Set yield timeouts
  293. */
  294. void
  295. PyMac_SetYield(long fgi, long fgy, long bgi, long bgy)
  296. {
  297.     interval_fg = fgi;
  298.     yield_fg = fgy;
  299.     interval_bg = bgi;
  300.     yield_bg = bgy;
  301. }
  302.  
  303. /*
  304. ** Handle an event, either one found in the mainloop eventhandler or
  305. ** one passed back from the python program.
  306. */
  307. void
  308. PyMac_HandleEvent(evp)
  309.     EventRecord *evp;
  310. {
  311.             
  312. #ifdef __MWERKS__
  313.     /* If SIOUX wants it we're done */
  314.     (void)SIOUXHandleOneEvent(evp);
  315. #else
  316.     /* Other compilers are just unlucky: we only weed out clicks in other applications */
  317.     if ( evp->what == mouseDown ) {
  318.         WindowPtr wp;
  319.         
  320.         if ( FindWindow(evp->where, &wp) == inSysWindow )
  321.             SystemClick(evp, wp);
  322.     }
  323. #endif /* !__MWERKS__ */
  324. }
  325.  
  326. /*
  327. ** Yield the CPU to other tasks.
  328. */
  329. static
  330. PyMac_DoYield()
  331. {
  332.     EventRecord ev;
  333.     long yield;
  334.     static int no_waitnextevent = -1;
  335.     int gotone;
  336.     
  337.     if ( no_waitnextevent < 0 ) {
  338.         no_waitnextevent = (NGetTrapAddress(_WaitNextEvent, ToolTrap) ==
  339.                             NGetTrapAddress(_Unimplemented, ToolTrap));
  340.     }
  341.  
  342.     if ( !PyMac_DoYieldEnabled ) {
  343. #ifndef THINK_C
  344.         /* Under think this has been done before in intrcheck() or intrpeek() */
  345.         scan_event_queue(0);
  346. #endif
  347.         return;
  348.     }
  349.         
  350.     in_foreground = PyMac_InForeground();
  351.     if ( in_foreground )
  352.         yield = yield_fg;
  353.     else
  354.         yield = yield_bg;
  355.     while ( 1 ) {
  356.         if ( no_waitnextevent ) {
  357.             SystemTask();
  358.             gotone = GetNextEvent(MAINLOOP_EVENTMASK, &ev);
  359.         } else {
  360.             gotone = WaitNextEvent(MAINLOOP_EVENTMASK, &ev, yield, NULL);
  361.         }    
  362.         /* Get out quickly if nothing interesting is happening */
  363.         if ( !gotone || ev.what == nullEvent )
  364.             break;
  365.         PyMac_HandleEvent(&ev);
  366.     }
  367.     lastyield = TickCount();
  368. }
  369.  
  370. /*
  371. ** Yield the CPU to other tasks if opportune
  372. */
  373. void
  374. PyMac_Yield() {
  375.     long iv;
  376.     
  377.     if ( in_foreground )
  378.         iv = interval_fg;
  379.     else
  380.         iv = interval_bg;
  381.     if ( TickCount() > lastyield + iv )
  382.         PyMac_DoYield();
  383. }
  384.  
  385. /*
  386. ** Idle routine for busy-wait loops.
  387. ** Gives up CPU, handles events and returns true if an interrupt is pending
  388. ** (but not actually handled yet).
  389. */
  390. int
  391. PyMac_Idle()
  392. {
  393.     PyMac_DoYield();
  394.     return intrpeek();
  395. }
  396. /*
  397. ** Returns true if the argument has a resource fork, and it contains
  398. ** a 'PYC ' resource of the correct name
  399. */
  400. int
  401. PyMac_FindResourceModule(module, filename)
  402. char *module;
  403. char *filename;
  404. {
  405.     FSSpec fss;
  406.     FInfo finfo;
  407.     short oldrh, filerh;
  408.     int ok;
  409.     Handle h;
  410.     
  411.     if ( FSMakeFSSpec(0, 0, Pstring(filename), &fss) != noErr )
  412.         return 0;            /* It doesn't exist */
  413.     if ( FSpGetFInfo(&fss, &finfo) != noErr )
  414.         return 0;            /* shouldn't happen, I guess */
  415.     oldrh = CurResFile();
  416.     filerh = FSpOpenResFile(&fss, fsRdPerm);
  417.     if ( filerh == -1 )
  418.         return 0;
  419.     UseResFile(filerh);
  420.     SetResLoad(0);
  421.     h = Get1NamedResource('PYC ', Pstring(module));
  422.     SetResLoad(1);
  423.     ok = (h != NULL);
  424.     CloseResFile(filerh);
  425.     UseResFile(oldrh);
  426.     return ok;
  427. }
  428.  
  429. /*
  430. ** Load the specified module from a resource
  431. */
  432. PyObject *
  433. PyMac_LoadResourceModule(module, filename)
  434. char *module;
  435. char *filename;
  436. {
  437.     FSSpec fss;
  438.     FInfo finfo;
  439.     short oldrh, filerh;
  440.     Handle h;
  441.     OSErr err;
  442.     PyObject *m, *co;
  443.     long num, size;
  444.     
  445.     if ( (err=FSMakeFSSpec(0, 0, Pstring(filename), &fss)) != noErr )
  446.         goto error;
  447.     if ( (err=FSpGetFInfo(&fss, &finfo)) != noErr )
  448.         goto error;
  449.     oldrh = CurResFile();
  450.     filerh = FSpOpenResFile(&fss, fsRdPerm);
  451.     if ( filerh == -1 ) {
  452.         err = ResError();
  453.         goto error;
  454.     }
  455.     UseResFile(filerh);
  456.     h = Get1NamedResource('PYC ', Pstring(module));
  457.     if ( h == NULL ) {
  458.         err = ResError();
  459.         goto error;
  460.     }
  461.     HLock(h);
  462.     /*
  463.     ** XXXX The next few lines are intimately tied to the format of pyc
  464.     ** files. I'm not sure whether this code should be here or in import.c -- Jack
  465.     */
  466.     size = GetHandleSize(h);
  467.     if ( size < 8 ) {
  468.         PyErr_SetString(PyExc_ImportError, "Resource too small");
  469.         co = NULL;
  470.     } else {
  471.         num = (*h)[0] & 0xff;
  472.         num = num | (((*h)[1] & 0xff) << 8);
  473.         num = num | (((*h)[2] & 0xff) << 16);
  474.         num = num | (((*h)[3] & 0xff) << 24);
  475.         if ( num != PyImport_GetMagicNumber() ) {
  476.             PyErr_SetString(PyExc_ImportError, "Bad MAGIC in resource");
  477.             co = NULL;
  478.         } else {
  479.             co = PyMarshal_ReadObjectFromString((*h)+8, size-8);
  480.         }
  481.     }
  482.     HUnlock(h);
  483.     CloseResFile(filerh);
  484.     UseResFile(oldrh);
  485.     if ( co ) {
  486.         m = PyImport_ExecCodeModule(module, co);
  487.         Py_DECREF(co);
  488.     } else {
  489.         m = NULL;
  490.     }
  491.     return m;
  492. error:
  493.     {
  494.         char buf[512];
  495.         
  496.         sprintf(buf, "%s: %s", filename, PyMac_StrError(err));
  497.         PyErr_SetString(PyExc_ImportError, buf);
  498.         return NULL;
  499.     }
  500. }
  501.  
  502. /*
  503. ** Helper routine for GetDirectory
  504. */
  505. static pascal short
  506. myhook_proc(short item, DialogPtr theDialog, struct hook_args *dataptr)
  507. {
  508.     if ( item == sfHookFirstCall && dataptr->prompt) {
  509.         Handle prompth;
  510.         short type;
  511.         Rect rect;
  512.         
  513.         GetDialogItem(theDialog, PROMPT_ITEM, &type, &prompth, &rect);
  514.         if ( prompth )
  515.             SetDialogItemText(prompth, (unsigned char *)dataptr->prompt);
  516.     } else
  517.     if ( item == SELECTCUR_ITEM ) {
  518.         item = sfItemCancelButton;
  519.         dataptr->selectcur_hit = 1;
  520.     }
  521.     return item;
  522. }    
  523.  
  524. /*
  525. ** Ask the user for a directory. I still can't understand
  526. ** why Apple doesn't provide a standard solution for this...
  527. */
  528. int
  529. PyMac_GetDirectory(dirfss, prompt)
  530.     FSSpec *dirfss;
  531.     char *prompt;
  532. {
  533.     static SFTypeList list = {'fldr', 0, 0, 0};
  534.     static Point where = {-1, -1};
  535.     StandardFileReply reply;
  536.     struct hook_args hook_args;
  537.     
  538.     if ( !upp_inited ) {
  539.         myhook_upp = NewDlgHookYDProc(myhook_proc);
  540.         upp_inited = 1;
  541.     }
  542.     if ( prompt && *prompt )
  543.         hook_args.prompt = (char *)Pstring(prompt);
  544.     else
  545.         hook_args.prompt = NULL;
  546.     hook_args.selectcur_hit = 0;
  547.     CustomGetFile((FileFilterYDUPP)0, 1, list, &reply, GETDIR_ID, where, myhook_upp,
  548.                 NULL, NULL, NULL, (void *)&hook_args);
  549.                 
  550.     reply.sfFile.name[0] = 0;
  551.     if( FSMakeFSSpec(reply.sfFile.vRefNum, reply.sfFile.parID, reply.sfFile.name, dirfss) )
  552.         return 0;
  553.     return hook_args.selectcur_hit;
  554. }
  555.  
  556. /*
  557. ** Slightly extended StandardGetFile: accepts a prompt */
  558. void PyMac_PromptGetFile(short numTypes, ConstSFTypeListPtr typeList, 
  559.         StandardFileReply *reply, char *prompt)
  560. {
  561.     static Point where = {-1, -1};
  562.     struct hook_args hook_args;
  563.     
  564.     if ( !upp_inited ) {
  565.         myhook_upp = NewDlgHookYDProc(myhook_proc);
  566.         upp_inited = 1;
  567.     }
  568.     if ( prompt && *prompt )
  569.         hook_args.prompt = (char *)Pstring(prompt);
  570.     else
  571.         hook_args.prompt = NULL;
  572.     hook_args.selectcur_hit = 0;
  573.     CustomGetFile((FileFilterYDUPP)0, numTypes, typeList, reply, GETFILEPROMPT_ID, where,
  574.                 myhook_upp, NULL, NULL, NULL, (void *)&hook_args);
  575. }
  576.  
  577. /* Convert a 4-char string object argument to an OSType value */
  578. int
  579. PyMac_GetOSType(PyObject *v, OSType *pr)
  580. {
  581.     if (!PyString_Check(v) || PyString_Size(v) != 4) {
  582.         PyErr_SetString(PyExc_TypeError,
  583.             "OSType arg must be string of 4 chars");
  584.         return 0;
  585.     }
  586.     memcpy((char *)pr, PyString_AsString(v), 4);
  587.     return 1;
  588. }
  589.  
  590. /* Convert an OSType value to a 4-char string object */
  591. PyObject *
  592. PyMac_BuildOSType(OSType t)
  593. {
  594.     return PyString_FromStringAndSize((char *)&t, 4);
  595. }
  596.  
  597.  
  598. /* Convert a Python string object to a Str255 */
  599. int
  600. PyMac_GetStr255(PyObject *v, Str255 pbuf)
  601. {
  602.     int len;
  603.     if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
  604.         PyErr_SetString(PyExc_TypeError,
  605.             "Str255 arg must be string of at most 255 chars");
  606.         return 0;
  607.     }
  608.     pbuf[0] = len;
  609.     memcpy((char *)(pbuf+1), PyString_AsString(v), len);
  610.     return 1;
  611. }
  612.  
  613. /* Convert a Str255 to a Python string object */
  614. PyObject *
  615. PyMac_BuildStr255(Str255 s)
  616. {
  617.     return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
  618. }
  619.  
  620.  
  621. /*
  622. ** Convert a Python object to an FSSpec.
  623. ** The object may either be a full pathname or a triple
  624. ** (vrefnum, dirid, path).
  625. ** NOTE: This routine will fail on pre-sys7 machines. 
  626. ** The caller is responsible for not calling this routine
  627. ** in those cases (which is fine, since everyone calling
  628. ** this is probably sys7 dependent anyway).
  629. */
  630. int
  631. PyMac_GetFSSpec(PyObject *v, FSSpec *fs)
  632. {
  633.     Str255 path;
  634.     short refnum;
  635.     long parid;
  636.     OSErr err;
  637.     FSSpec *fs2;
  638.  
  639.     /* first check whether it already is an FSSpec */
  640.     fs2 = mfs_GetFSSpecFSSpec(v);
  641.     if ( fs2 ) {
  642.         (void)FSMakeFSSpec(fs2->vRefNum, fs2->parID, fs2->name, fs);
  643.         return 1;
  644.     }
  645.     if ( PyString_Check(v) ) {
  646.         /* It's a pathname */
  647.         if( !PyArg_Parse(v, "O&", PyMac_GetStr255, &path) )
  648.             return 0;
  649.         refnum = 0; /* XXXX Should get CurWD here... */
  650.         parid = 0;
  651.     } else {
  652.         if( !PyArg_Parse(v, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
  653.                             &refnum, &parid, PyMac_GetStr255, &path)) {
  654.             return 0;
  655.         }
  656.     }
  657.     err = FSMakeFSSpec(refnum, parid, path, fs);
  658.     if ( err && err != fnfErr ) {
  659.         PyErr_Mac(PyExc_ValueError, err);
  660.         return 0;
  661.     }
  662.     return 1;
  663. }
  664.  
  665.  
  666.  
  667. /* Convert a Python object to a Rect.
  668.    The object must be a (left, top, right, bottom) tuple.
  669.    (This differs from the order in the struct but is consistent with
  670.    the arguments to SetRect(), and also with STDWIN). */
  671. int
  672. PyMac_GetRect(PyObject *v, Rect *r)
  673. {
  674.     return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
  675. }
  676.  
  677. /* Convert a Rect to a Python object */
  678. PyObject *
  679. PyMac_BuildRect(Rect *r)
  680. {
  681.     return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
  682. }
  683.  
  684.  
  685. /* Convert a Python object to a Point.
  686.    The object must be a (h, v) tuple.
  687.    (This differs from the order in the struct but is consistent with
  688.    the arguments to SetPoint(), and also with STDWIN). */
  689. int
  690. PyMac_GetPoint(PyObject *v, Point *p)
  691. {
  692.     return PyArg_Parse(v, "(hh)", &p->h, &p->v);
  693. }
  694.  
  695. /* Convert a Point to a Python object */
  696. PyObject *
  697. PyMac_BuildPoint(Point p)
  698. {
  699.     return Py_BuildValue("(hh)", p.h, p.v);
  700. }
  701.  
  702.  
  703. /* Convert a Python object to an EventRecord.
  704.    The object must be a (what, message, when, (v, h), modifiers) tuple. */
  705. int
  706. PyMac_GetEventRecord(PyObject *v, EventRecord *e)
  707. {
  708.     return PyArg_Parse(v, "(hll(hh)h)",
  709.                        &e->what,
  710.                        &e->message,
  711.                        &e->when,
  712.                        &e->where.h,
  713.                        &e->where.v,                   
  714.                        &e->modifiers);
  715. }
  716.  
  717. /* Convert a Rect to an EventRecord object */
  718. PyObject *
  719. PyMac_BuildEventRecord(EventRecord *e)
  720. {
  721.     return Py_BuildValue("(hll(hh)h)",
  722.                          e->what,
  723.                          e->message,
  724.                          e->when,
  725.                          e->where.h,
  726.                          e->where.v,
  727.                          e->modifiers);
  728. }
  729.