summaryrefslogtreecommitdiffstats
path: root/Python/pystate.c
blob: 65c244e6f736173e21a12f220f3c743a5d960695 (plain)
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

/* Thread and interpreter state structures and their interfaces */

#include "Python.h"

#define GET_TSTATE() \
    ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
#define SET_TSTATE(value) \
    _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
#define GET_INTERP_STATE() \
    (GET_TSTATE()->interp)


/* --------------------------------------------------------------------------
CAUTION

Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file.  A
number of these functions are advertised as safe to call when the GIL isn't
held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
debugging obmalloc functions.  Those aren't thread-safe (they rely on the GIL
to avoid the expense of doing their own locking).
-------------------------------------------------------------------------- */

#ifdef HAVE_DLOPEN
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif
#if !HAVE_DECL_RTLD_LAZY
#define RTLD_LAZY 1
#endif
#endif

#ifdef __cplusplus
extern "C" {
#endif

int _PyGILState_check_enabled = 1;

#ifdef WITH_THREAD
#include "pythread.h"
static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)

/* The single PyInterpreterState used by this process'
   GILState implementation
*/
static PyInterpreterState *autoInterpreterState = NULL;
static int autoTLSkey = -1;
#else
#define HEAD_INIT() /* Nothing */
#define HEAD_LOCK() /* Nothing */
#define HEAD_UNLOCK() /* Nothing */
#endif

static PyInterpreterState *interp_head = NULL;

/* Assuming the current thread holds the GIL, this is the
   PyThreadState for the current thread. */
_Py_atomic_address _PyThreadState_Current = {0};
PyThreadFrameGetter _PyThreadState_GetFrame = NULL;

#ifdef WITH_THREAD
static void _PyGILState_NoteThreadState(PyThreadState* tstate);
#endif


PyInterpreterState *
PyInterpreterState_New(void)
{
    PyInterpreterState *interp = (PyInterpreterState *)
                                 PyMem_RawMalloc(sizeof(PyInterpreterState));

    if (interp != NULL) {
        HEAD_INIT();
#ifdef WITH_THREAD
        if (head_mutex == NULL)
            Py_FatalError("Can't initialize threads for interpreter");
#endif
        interp->modules = NULL;
        interp->modules_by_index = NULL;
        interp->sysdict = NULL;
        interp->builtins = NULL;
        interp->builtins_copy = NULL;
        interp->tstate_head = NULL;
        interp->codec_search_path = NULL;
        interp->codec_search_cache = NULL;
        interp->codec_error_registry = NULL;
        interp->codecs_initialized = 0;
        interp->fscodec_initialized = 0;
        interp->importlib = NULL;
        interp->import_func = NULL;
        interp->eval_frame = _PyEval_EvalFrameDefault;
#ifdef HAVE_DLOPEN
#if HAVE_DECL_RTLD_NOW
        interp->dlopenflags = RTLD_NOW;
#else
        interp->dlopenflags = RTLD_LAZY;
#endif
#endif

        HEAD_LOCK();
        interp->next = interp_head;
        interp_head = interp;
        HEAD_UNLOCK();
    }

    return interp;
}


void
PyInterpreterState_Clear(PyInterpreterState *interp)
{
    PyThreadState *p;
    HEAD_LOCK();
    for (p = interp->tstate_head; p != NULL; p = p->next)
        PyThreadState_Clear(p);
    HEAD_UNLOCK();
    Py_CLEAR(interp->codec_search_path);
    Py_CLEAR(interp->codec_search_cache);
    Py_CLEAR(interp->codec_error_registry);
    Py_CLEAR(interp->modules);
    Py_CLEAR(interp->modules_by_index);
    Py_CLEAR(interp->sysdict);
    Py_CLEAR(interp->builtins);
    Py_CLEAR(interp->builtins_copy);
    Py_CLEAR(interp->importlib);
    Py_CLEAR(interp->import_func);
}


static void
zapthreads(PyInterpreterState *interp)
{
    PyThreadState *p;
    /* No need to lock the mutex here because this should only happen
       when the threads are all really dead (XXX famous last words). */
    while ((p = interp->tstate_head) != NULL) {
        PyThreadState_Delete(p);
    }
}


void
PyInterpreterState_Delete(PyInterpreterState *interp)
{
    PyInterpreterState **p;
    zapthreads(interp);
    HEAD_LOCK();
    for (p = &interp_head; ; p = &(*p)->next) {
        if (*p == NULL)
            Py_FatalError(
                "PyInterpreterState_Delete: invalid interp");
        if (*p == interp)
            break;
    }
    if (interp->tstate_head != NULL)
        Py_FatalError("PyInterpreterState_Delete: remaining threads");
    *p = interp->next;
    HEAD_UNLOCK();
    PyMem_RawFree(interp);
#ifdef WITH_THREAD
    if (interp_head == NULL && head_mutex != NULL) {
        PyThread_free_lock(head_mutex);
        head_mutex = NULL;
    }
#endif
}


/* Default implementation for _PyThreadState_GetFrame */
static struct _frame *
threadstate_getframe(PyThreadState *self)
{
    return self->frame;
}

static PyThreadState *
new_threadstate(PyInterpreterState *interp, int init)
{
    PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));

    if (_PyThreadState_GetFrame == NULL)
        _PyThreadState_GetFrame = threadstate_getframe;

    if (tstate != NULL) {
        tstate->interp = interp;

        tstate->frame = NULL;
        tstate->recursion_depth = 0;
        tstate->overflowed = 0;
        tstate->recursion_critical = 0;
        tstate->tracing = 0;
        tstate->use_tracing = 0;
        tstate->gilstate_counter = 0;
        tstate->async_exc = NULL;
#ifdef WITH_THREAD
        tstate->thread_id = PyThread_get_thread_ident();
#else
        tstate->thread_id = 0;
#endif

        tstate->dict = NULL;

        tstate->curexc_type = NULL;
        tstate->curexc_value = NULL;
        tstate->curexc_traceback = NULL;

        tstate->exc_type = NULL;
        tstate->exc_value = NULL;
        tstate->exc_traceback = NULL;

        tstate->c_profilefunc = NULL;
        tstate->c_tracefunc = NULL;
        tstate->c_profileobj = NULL;
        tstate->c_traceobj = NULL;

        tstate->trash_delete_nesting = 0;
        tstate->trash_delete_later = NULL;
        tstate->on_delete = NULL;
        tstate->on_delete_data = NULL;

        tstate->coroutine_wrapper = NULL;
        tstate->in_coroutine_wrapper = 0;
        tstate->co_extra_user_count = 0;

        tstate->async_gen_firstiter = NULL;
        tstate->async_gen_finalizer = NULL;

        if (init)
            _PyThreadState_Init(tstate);

        HEAD_LOCK();
        tstate->prev = NULL;
        tstate->next = interp->tstate_head;
        if (tstate->next)
            tstate->next->prev = tstate;
        interp->tstate_head = tstate;
        HEAD_UNLOCK();
    }

    return tstate;
}

PyThreadState *
PyThreadState_New(PyInterpreterState *interp)
{
    return new_threadstate(interp, 1);
}

PyThreadState *
_PyThreadState_Prealloc(PyInterpreterState *interp)
{
    return new_threadstate(interp, 0);
}

void
_PyThreadState_Init(PyThreadState *tstate)
{
#ifdef WITH_THREAD
    _PyGILState_NoteThreadState(tstate);
#endif
}

PyObject*
PyState_FindModule(struct PyModuleDef* module)
{
    Py_ssize_t index = module->m_base.m_index;
    PyInterpreterState *state = GET_INTERP_STATE();
    PyObject *res;
    if (module->m_slots) {
        return NULL;
    }
    if (index == 0)
        return NULL;
    if (state->modules_by_index == NULL)
        return NULL;
    if (index >= PyList_GET_SIZE(state->modules_by_index))
        return NULL;
    res = PyList_GET_ITEM(state->modules_by_index, index);
    return res==Py_None ? NULL : res;
}

int
_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
{
    PyInterpreterState *state;
    if (!def) {
        assert(PyErr_Occurred());
        return -1;
    }
    if (def->m_slots) {
        PyErr_SetString(PyExc_SystemError,
                        "PyState_AddModule called on module with slots");
        return -1;
    }
    state = GET_INTERP_STATE();
    if (!state->modules_by_index) {
        state->modules_by_index = PyList_New(0);
        if (!state->modules_by_index)
            return -1;
    }
    while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
        if (PyList_Append(state->modules_by_index, Py_None) < 0)
            return -1;
    Py_INCREF(module);
    return PyList_SetItem(state->modules_by_index,
                          def->m_base.m_index, module);
}

int
PyState_AddModule(PyObject* module, struct PyModuleDef* def)
{
    Py_ssize_t index;
    PyInterpreterState *state = GET_INTERP_STATE();
    if (!def) {
        Py_FatalError("PyState_AddModule: Module Definition is NULL");
        return -1;
    }
    index = def->m_base.m_index;
    if (state->modules_by_index) {
        if(PyList_GET_SIZE(state->modules_by_index) >= index) {
            if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
                Py_FatalError("PyState_AddModule: Module already added!");
                return -1;
            }
        }
    }
    return _PyState_AddModule(module, def);
}

int
PyState_RemoveModule(struct PyModuleDef* def)
{
    PyInterpreterState *state;
    Py_ssize_t index = def->m_base.m_index;
    if (def->m_slots) {
        PyErr_SetString(PyExc_SystemError,
                        "PyState_RemoveModule called on module with slots");
        return -1;
    }
    state = GET_INTERP_STATE();
    if (index == 0) {
        Py_FatalError("PyState_RemoveModule: Module index invalid.");
        return -1;
    }
    if (state->modules_by_index == NULL) {
        Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
        return -1;
    }
    if (index > PyList_GET_SIZE(state->modules_by_index)) {
        Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
        return -1;
    }
    return PyList_SetItem(state->modules_by_index, index, Py_None);
}

/* used by import.c:PyImport_Cleanup */
void
_PyState_ClearModules(void)
{
    PyInterpreterState *state = GET_INTERP_STATE();
    if (state->modules_by_index) {
        Py_ssize_t i;
        for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
            PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
            if (PyModule_Check(m)) {
                /* cleanup the saved copy of module dicts */
                PyModuleDef *md = PyModule_GetDef(m);
                if (md)
                    Py_CLEAR(md->m_base.m_copy);
            }
        }
        /* Setting modules_by_index to NULL could be dangerous, so we
           clear the list instead. */
        if (PyList_SetSlice(state->modules_by_index,
                            0, PyList_GET_SIZE(state->modules_by_index),
                            NULL))
            PyErr_WriteUnraisable(state->modules_by_index);
    }
}

void
PyThreadState_Clear(PyThreadState *tstate)
{
    if (Py_VerboseFlag && tstate->frame != NULL)
        fprintf(stderr,
          "PyThreadState_Clear: warning: thread still has a frame\n");

    Py_CLEAR(tstate->frame);

    Py_CLEAR(tstate->dict);
    Py_CLEAR(tstate->async_exc);

    Py_CLEAR(tstate->curexc_type);
    Py_CLEAR(tstate->curexc_value);
    Py_CLEAR(tstate->curexc_traceback);

    Py_CLEAR(tstate->exc_type);
    Py_CLEAR(tstate->exc_value);
    Py_CLEAR(tstate->exc_traceback);

    tstate->c_profilefunc = NULL;
    tstate->c_tracefunc = NULL;
    Py_CLEAR(tstate->c_profileobj);
    Py_CLEAR(tstate->c_traceobj);

    Py_CLEAR(tstate->coroutine_wrapper);
    Py_CLEAR(tstate->async_gen_firstiter);
    Py_CLEAR(tstate->async_gen_finalizer);
}


/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
static void
tstate_delete_common(PyThreadState *tstate)
{
    PyInterpreterState *interp;
    if (tstate == NULL)
        Py_FatalError("PyThreadState_Delete: NULL tstate");
    interp = tstate->interp;
    if (interp == NULL)
        Py_FatalError("PyThreadState_Delete: NULL interp");
    HEAD_LOCK();
    if (tstate->prev)
        tstate->prev->next = tstate->next;
    else
        interp->tstate_head = tstate->next;
    if (tstate->next)
        tstate->next->prev = tstate->prev;
    HEAD_UNLOCK();
    if (tstate->on_delete != NULL) {
        tstate->on_delete(tstate->on_delete_data);
    }
    PyMem_RawFree(tstate);
}


void
PyThreadState_Delete(PyThreadState *tstate)
{
    if (tstate == GET_TSTATE())
        Py_FatalError("PyThreadState_Delete: tstate is still current");
#ifdef WITH_THREAD
    if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
        PyThread_delete_key_value(autoTLSkey);
#endif /* WITH_THREAD */
    tstate_delete_common(tstate);
}


#ifdef WITH_THREAD
void
PyThreadState_DeleteCurrent()
{
    PyThreadState *tstate = GET_TSTATE();
    if (tstate == NULL)
        Py_FatalError(
            "PyThreadState_DeleteCurrent: no current tstate");
    tstate_delete_common(tstate);
    if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
        PyThread_delete_key_value(autoTLSkey);
    SET_TSTATE(NULL);
    PyEval_ReleaseLock();
}
#endif /* WITH_THREAD */


/*
 * Delete all thread states except the one passed as argument.
 * Note that, if there is a current thread state, it *must* be the one
 * passed as argument.  Also, this won't touch any other interpreters
 * than the current one, since we don't know which thread state should
 * be kept in those other interpreteres.
 */
void
_PyThreadState_DeleteExcept(PyThreadState *tstate)
{
    PyInterpreterState *interp = tstate->interp;
    PyThreadState *p, *next, *garbage;
    HEAD_LOCK();
    /* Remove all thread states, except tstate, from the linked list of
       thread states.  This will allow calling PyThreadState_Clear()
       without holding the lock. */
    garbage = interp->tstate_head;
    if (garbage == tstate)
        garbage = tstate->next;
    if (tstate->prev)
        tstate->prev->next = tstate->next;
    if (tstate->next)
        tstate->next->prev = tstate->prev;
    tstate->prev = tstate->next = NULL;
    interp->tstate_head = tstate;
    HEAD_UNLOCK();
    /* Clear and deallocate all stale thread states.  Even if this
       executes Python code, we should be safe since it executes
       in the current thread, not one of the stale threads. */
    for (p = garbage; p; p = next) {
        next = p->next;
        PyThreadState_Clear(p);
        PyMem_RawFree(p);
    }
}


PyThreadState *
_PyThreadState_UncheckedGet(void)
{
    return GET_TSTATE();
}


PyThreadState *
PyThreadState_Get(void)
{
    PyThreadState *tstate = GET_TSTATE();
    if (tstate == NULL)
        Py_FatalError("PyThreadState_Get: no current thread");

    return tstate;
}


PyThreadState *
PyThreadState_Swap(PyThreadState *newts)
{
    PyThreadState *oldts = GET_TSTATE();

    SET_TSTATE(newts);
    /* It should not be possible for more than one thread state
       to be used for a thread.  Check this the best we can in debug
       builds.
    */
#if defined(Py_DEBUG) && defined(WITH_THREAD)
    if (newts) {
        /* This can be called from PyEval_RestoreThread(). Similar
           to it, we need to ensure errno doesn't change.
        */
        int err = errno;
        PyThreadState *check = PyGILState_GetThisThreadState();
        if (check && check->interp == newts->interp && check != newts)
            Py_FatalError("Invalid thread state for this thread");
        errno = err;
    }
#endif
    return oldts;
}

/* An extension mechanism to store arbitrary additional per-thread state.
   PyThreadState_GetDict() returns a dictionary that can be used to hold such
   state; the caller should pick a unique key and store its state there.  If
   PyThreadState_GetDict() returns NULL, an exception has *not* been raised
   and the caller should assume no per-thread state is available. */

PyObject *
PyThreadState_GetDict(void)
{
    PyThreadState *tstate = GET_TSTATE();
    if (tstate == NULL)
        return NULL;

    if (tstate->dict == NULL) {
        PyObject *d;
        tstate->dict = d = PyDict_New();
        if (d == NULL)
            PyErr_Clear();
    }
    return tstate->dict;
}


/* Asynchronously raise an exception in a thread.
   Requested by Just van Rossum and Alex Martelli.
   To prevent naive misuse, you must write your own extension
   to call this, or use ctypes.  Must be called with the GIL held.
   Returns the number of tstates modified (normally 1, but 0 if `id` didn't
   match any known thread id).  Can be called with exc=NULL to clear an
   existing async exception.  This raises no exceptions. */

int
PyThreadState_SetAsyncExc(long id, PyObject *exc) {
    PyInterpreterState *interp = GET_INTERP_STATE();
    PyThreadState *p;

    /* Although the GIL is held, a few C API functions can be called
     * without the GIL held, and in particular some that create and
     * destroy thread and interpreter states.  Those can mutate the
     * list of thread states we're traversing, so to prevent that we lock
     * head_mutex for the duration.
     */
    HEAD_LOCK();
    for (p = interp->tstate_head; p != NULL; p = p->next) {
        if (p->thread_id == id) {
            /* Tricky:  we need to decref the current value
             * (if any) in p->async_exc, but that can in turn
             * allow arbitrary Python code to run, including
             * perhaps calls to this function.  To prevent
             * deadlock, we need to release head_mutex before
             * the decref.
             */
            PyObject *old_exc = p->async_exc;
            Py_XINCREF(exc);
            p->async_exc = exc;
            HEAD_UNLOCK();
            Py_XDECREF(old_exc);
            _PyEval_SignalAsyncExc();
            return 1;
        }
    }
    HEAD_UNLOCK();
    return 0;
}


/* Routines for advanced debuggers, requested by David Beazley.
   Don't use unless you know what you are doing! */

PyInterpreterState *
PyInterpreterState_Head(void)
{
    return interp_head;
}

PyInterpreterState *
PyInterpreterState_Next(PyInterpreterState *interp) {
    return interp->next;
}

PyThreadState *
PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
    return interp->tstate_head;
}

PyThreadState *
PyThreadState_Next(PyThreadState *tstate) {
    return tstate->next;
}

/* The implementation of sys._current_frames().  This is intended to be
   called with the GIL held, as it will be when called via
   sys._current_frames().  It's possible it would work fine even without
   the GIL held, but haven't thought enough about that.
*/
PyObject *
_PyThread_CurrentFrames(void)
{
    PyObject *result;
    PyInterpreterState *i;

    result = PyDict_New();
    if (result == NULL)
        return NULL;

    /* for i in all interpreters:
     *     for t in all of i's thread states:
     *          if t's frame isn't NULL, map t's id to its frame
     * Because these lists can mutate even when the GIL is held, we
     * need to grab head_mutex for the duration.
     */
    HEAD_LOCK();
    for (i = interp_head; i != NULL; i = i->next) {
        PyThreadState *t;
        for (t = i->tstate_head; t != NULL; t = t->next) {
            PyObject *id;
            int stat;
            struct _frame *frame = t->frame;
            if (frame == NULL)
                continue;
            id = PyLong_FromLong(t->thread_id);
            if (id == NULL)
                goto Fail;
            stat = PyDict_SetItem(result, id, (PyObject *)frame);
            Py_DECREF(id);
            if (stat < 0)
                goto Fail;
        }
    }
    HEAD_UNLOCK();
    return result;

 Fail:
    HEAD_UNLOCK();
    Py_DECREF(result);
    return NULL;
}

/* Python "auto thread state" API. */
#ifdef WITH_THREAD

/* Keep this as a static, as it is not reliable!  It can only
   ever be compared to the state for the *current* thread.
   * If not equal, then it doesn't matter that the actual
     value may change immediately after comparison, as it can't
     possibly change to the current thread's state.
   * If equal, then the current thread holds the lock, so the value can't
     change until we yield the lock.
*/
static int
PyThreadState_IsCurrent(PyThreadState *tstate)
{
    /* Must be the tstate for this thread */
    assert(PyGILState_GetThisThreadState()==tstate);
    return tstate == GET_TSTATE();
}

/* Internal initialization/finalization functions called by
   Py_Initialize/Py_FinalizeEx
*/
void
_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
{
    assert(i && t); /* must init with valid states */
    autoTLSkey = PyThread_create_key();
    if (autoTLSkey == -1)
        Py_FatalError("Could not allocate TLS entry");
    autoInterpreterState = i;
    assert(PyThread_get_key_value(autoTLSkey) == NULL);
    assert(t->gilstate_counter == 0);

    _PyGILState_NoteThreadState(t);
}

PyInterpreterState *
_PyGILState_GetInterpreterStateUnsafe(void)
{
    return autoInterpreterState;
}

void
_PyGILState_Fini(void)
{
    PyThread_delete_key(autoTLSkey);
    autoTLSkey = -1;
    autoInterpreterState = NULL;
}

/* Reset the TLS key - called by PyOS_AfterFork().
 * This should not be necessary, but some - buggy - pthread implementations
 * don't reset TLS upon fork(), see issue #10517.
 */
void
_PyGILState_Reinit(void)
{
    PyThreadState *tstate = PyGILState_GetThisThreadState();
    PyThread_delete_key(autoTLSkey);
    if ((autoTLSkey = PyThread_create_key()) == -1)
        Py_FatalError("Could not allocate TLS entry");

    /* If the thread had an associated auto thread state, reassociate it with
     * the new key. */
    if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
        Py_FatalError("Couldn't create autoTLSkey mapping");
}

/* When a thread state is created for a thread by some mechanism other than
   PyGILState_Ensure, it's important that the GILState machinery knows about
   it so it doesn't try to create another thread state for the thread (this is
   a better fix for SF bug #1010677 than the first one attempted).
*/
static void
_PyGILState_NoteThreadState(PyThreadState* tstate)
{
    /* If autoTLSkey isn't initialized, this must be the very first
       threadstate created in Py_Initialize().  Don't do anything for now
       (we'll be back here when _PyGILState_Init is called). */
    if (!autoInterpreterState)
        return;

    /* Stick the thread state for this thread in thread local storage.

       The only situation where you can legitimately have more than one
       thread state for an OS level thread is when there are multiple
       interpreters.

       You shouldn't really be using the PyGILState_ APIs anyway (see issues
       #10915 and #15751).

       The first thread state created for that given OS level thread will
       "win", which seems reasonable behaviour.
    */
    if (PyThread_get_key_value(autoTLSkey) == NULL) {
        if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
            Py_FatalError("Couldn't create autoTLSkey mapping");
    }

    /* PyGILState_Release must not try to delete this thread state. */
    tstate->gilstate_counter = 1;
}

/* The public functions */
PyThreadState *
PyGILState_GetThisThreadState(void)
{
    if (autoInterpreterState == NULL)
        return NULL;
    return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
}

int
PyGILState_Check(void)
{
    PyThreadState *tstate;

    if (!_PyGILState_check_enabled)
        return 1;

    if (autoTLSkey == -1)
        return 1;

    tstate = GET_TSTATE();
    if (tstate == NULL)
        return 0;

    return (tstate == PyGILState_GetThisThreadState());
}

PyGILState_STATE
PyGILState_Ensure(void)
{
    int current;
    PyThreadState *tcur;
    /* Note that we do not auto-init Python here - apart from
       potential races with 2 threads auto-initializing, pep-311
       spells out other issues.  Embedders are expected to have
       called Py_Initialize() and usually PyEval_InitThreads().
    */
    assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
    tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
    if (tcur == NULL) {
        /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
           called from a new thread for the first time, we need the create the
           GIL. */
        PyEval_InitThreads();

        /* Create a new thread state for this thread */
        tcur = PyThreadState_New(autoInterpreterState);
        if (tcur == NULL)
            Py_FatalError("Couldn't create thread-state for new thread");
        /* This is our thread state!  We'll need to delete it in the
           matching call to PyGILState_Release(). */
        tcur->gilstate_counter = 0;
        current = 0; /* new thread state is never current */
    }
    else
        current = PyThreadState_IsCurrent(tcur);
    if (current == 0)
        PyEval_RestoreThread(tcur);
    /* Update our counter in the thread-state - no need for locks:
       - tcur will remain valid as we hold the GIL.
       - the counter is safe as we are the only thread "allowed"
         to modify this value
    */
    ++tcur->gilstate_counter;
    return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
}

void
PyGILState_Release(PyGILState_STATE oldstate)
{
    PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
                                                            autoTLSkey);
    if (tcur == NULL)
        Py_FatalError("auto-releasing thread-state, "
                      "but no thread-state for this thread");
    /* We must hold the GIL and have our thread state current */
    /* XXX - remove the check - the assert should be fine,
       but while this is very new (April 2003), the extra check
       by release-only users can't hurt.
    */
    if (! PyThreadState_IsCurrent(tcur))
        Py_FatalError("This thread state must be current when releasing");
    assert(PyThreadState_IsCurrent(tcur));
    --tcur->gilstate_counter;
    assert(tcur->gilstate_counter >= 0); /* illegal counter value */

    /* If we're going to destroy this thread-state, we must
     * clear it while the GIL is held, as destructors may run.
     */
    if (tcur->gilstate_counter == 0) {
        /* can't have been locked when we created it */
        assert(oldstate == PyGILState_UNLOCKED);
        PyThreadState_Clear(tcur);
        /* Delete the thread-state.  Note this releases the GIL too!
         * It's vital that the GIL be held here, to avoid shutdown
         * races; see bugs 225673 and 1061968 (that nasty bug has a
         * habit of coming back).
         */
        PyThreadState_DeleteCurrent();
    }
    /* Release the lock if necessary */
    else if (oldstate == PyGILState_UNLOCKED)
        PyEval_SaveThread();
}

#endif /* WITH_THREAD */

#ifdef __cplusplus
}
#endif


s="hl slc"># # Define tab-specific behavior. font_sample_text = ( '<ASCII/Latin1>\n' 'AaBbCcDdEeFfGgHhIiJj\n1234567890#:+=(){}[]\n' '\u00a2\u00a3\u00a5\u00a7\u00a9\u00ab\u00ae\u00b6\u00bd\u011e' '\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c7\u00d0\u00d8\u00df\n' '\n<IPA,Greek,Cyrillic>\n' '\u0250\u0255\u0258\u025e\u025f\u0264\u026b\u026e\u0270\u0277' '\u027b\u0281\u0283\u0286\u028e\u029e\u02a2\u02ab\u02ad\u02af\n' '\u0391\u03b1\u0392\u03b2\u0393\u03b3\u0394\u03b4\u0395\u03b5' '\u0396\u03b6\u0397\u03b7\u0398\u03b8\u0399\u03b9\u039a\u03ba\n' '\u0411\u0431\u0414\u0434\u0416\u0436\u041f\u043f\u0424\u0444' '\u0427\u0447\u042a\u044a\u042d\u044d\u0460\u0464\u046c\u04dc\n' '\n<Hebrew, Arabic>\n' '\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7\u05d8\u05d9' '\u05da\u05db\u05dc\u05dd\u05de\u05df\u05e0\u05e1\u05e2\u05e3\n' '\u0627\u0628\u062c\u062f\u0647\u0648\u0632\u062d\u0637\u064a' '\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\n' '\n<Devanagari, Tamil>\n' '\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f' '\u0905\u0906\u0907\u0908\u0909\u090a\u090f\u0910\u0913\u0914\n' '\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef' '\u0b85\u0b87\u0b89\u0b8e\n' '\n<East Asian>\n' '\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\n' '\u6c49\u5b57\u6f22\u5b57\u4eba\u6728\u706b\u571f\u91d1\u6c34\n' '\uac00\ub0d0\ub354\ub824\ubaa8\ubd64\uc218\uc720\uc988\uce58\n' '\u3042\u3044\u3046\u3048\u304a\u30a2\u30a4\u30a6\u30a8\u30aa\n' ) class FontPage(Frame): def __init__(self, master, highpage): super().__init__(master) self.highlight_sample = highpage.highlight_sample self.create_page_font() self.load_font_cfg() def create_page_font(self): """Return frame of widgets for Font tab. Fonts: Enable users to provisionally change font face, size, or boldness and to see the consequence of proposed choices. Each action set 3 options in changes structuree and changes the corresponding aspect of the font sample on this page and highlight sample on highlight page. Function load_font_cfg initializes font vars and widgets from idleConf entries and tk. Fontlist: mouse button 1 click or up or down key invoke on_fontlist_select(), which sets var font_name. Sizelist: clicking the menubutton opens the dropdown menu. A mouse button 1 click or return key sets var font_size. Bold_toggle: clicking the box toggles var font_bold. Changing any of the font vars invokes var_changed_font, which adds all 3 font options to changes and calls set_samples. Set_samples applies a new font constructed from the font vars to font_sample and to highlight_sample on the highlight page. Widgets for FontPage(Frame): (*) widgets bound to self frame_font: LabelFrame frame_font_name: Frame font_name_title: Label (*)fontlist: ListBox - font_name scroll_font: Scrollbar frame_font_param: Frame font_size_title: Label (*)sizelist: DynOptionMenu - font_size (*)bold_toggle: Checkbutton - font_bold frame_sample: LabelFrame (*)font_sample: Label """ self.font_name = tracers.add(StringVar(self), self.var_changed_font) self.font_size = tracers.add(StringVar(self), self.var_changed_font) self.font_bold = tracers.add(BooleanVar(self), self.var_changed_font) # Define frames and widgets. frame_font = LabelFrame(self, borderwidth=2, relief=GROOVE, text=' Shell/Editor Font ') frame_sample = LabelFrame(self, borderwidth=2, relief=GROOVE, text=' Font Sample (Editable) ') # frame_font. frame_font_name = Frame(frame_font) frame_font_param = Frame(frame_font) font_name_title = Label( frame_font_name, justify=LEFT, text='Font Face :') self.fontlist = Listbox(frame_font_name, height=15, takefocus=True, exportselection=FALSE) self.fontlist.bind('<ButtonRelease-1>', self.on_fontlist_select) self.fontlist.bind('<KeyRelease-Up>', self.on_fontlist_select) self.fontlist.bind('<KeyRelease-Down>', self.on_fontlist_select) scroll_font = Scrollbar(frame_font_name) scroll_font.config(command=self.fontlist.yview) self.fontlist.config(yscrollcommand=scroll_font.set) font_size_title = Label(frame_font_param, text='Size :') self.sizelist = DynOptionMenu(frame_font_param, self.font_size, None) self.bold_toggle = Checkbutton( frame_font_param, variable=self.font_bold, onvalue=1, offvalue=0, text='Bold') # frame_sample. font_sample_frame = ScrollableTextFrame(frame_sample) self.font_sample = font_sample_frame.text self.font_sample.config(wrap=NONE, width=1, height=1) self.font_sample.insert(END, font_sample_text) # Grid and pack widgets: self.columnconfigure(1, weight=1) self.rowconfigure(2, weight=1) frame_font.grid(row=0, column=0, padx=5, pady=5) frame_sample.grid(row=0, column=1, rowspan=3, padx=5, pady=5, sticky='nsew') # frame_font. frame_font_name.pack(side=TOP, padx=5, pady=5, fill=X) frame_font_param.pack(side=TOP, padx=5, pady=5, fill=X) font_name_title.pack(side=TOP, anchor=W) self.fontlist.pack(side=LEFT, expand=TRUE, fill=X) scroll_font.pack(side=LEFT, fill=Y) font_size_title.pack(side=LEFT, anchor=W) self.sizelist.pack(side=LEFT, anchor=W) self.bold_toggle.pack(side=LEFT, anchor=W, padx=20) # frame_sample. font_sample_frame.pack(expand=TRUE, fill=BOTH) def load_font_cfg(self): """Load current configuration settings for the font options. Retrieve current font with idleConf.GetFont and font families from tk. Setup fontlist and set font_name. Setup sizelist, which sets font_size. Set font_bold. Call set_samples. """ configured_font = idleConf.GetFont(self, 'main', 'EditorWindow') font_name = configured_font[0].lower() font_size = configured_font[1] font_bold = configured_font[2]=='bold' # Set sorted no-duplicate editor font selection list and font_name. fonts = sorted(set(tkfont.families(self))) for font in fonts: self.fontlist.insert(END, font) self.font_name.set(font_name) lc_fonts = [s.lower() for s in fonts] try: current_font_index = lc_fonts.index(font_name) self.fontlist.see(current_font_index) self.fontlist.select_set(current_font_index) self.fontlist.select_anchor(current_font_index) self.fontlist.activate(current_font_index) except ValueError: pass # Set font size dropdown. self.sizelist.SetMenu(('7', '8', '9', '10', '11', '12', '13', '14', '16', '18', '20', '22', '25', '29', '34', '40'), font_size) # Set font weight. self.font_bold.set(font_bold) self.set_samples() def var_changed_font(self, *params): """Store changes to font attributes. When one font attribute changes, save them all, as they are not independent from each other. In particular, when we are overriding the default font, we need to write out everything. """ value = self.font_name.get() changes.add_option('main', 'EditorWindow', 'font', value) value = self.font_size.get() changes.add_option('main', 'EditorWindow', 'font-size', value) value = self.font_bold.get() changes.add_option('main', 'EditorWindow', 'font-bold', value) self.set_samples() def on_fontlist_select(self, event): """Handle selecting a font from the list. Event can result from either mouse click or Up or Down key. Set font_name and example displays to selection. """ font = self.fontlist.get( ACTIVE if event.type.name == 'KeyRelease' else ANCHOR) self.font_name.set(font.lower()) def set_samples(self, event=None): """Update update both screen samples with the font settings. Called on font initialization and change events. Accesses font_name, font_size, and font_bold Variables. Updates font_sample and highlight page highlight_sample. """ font_name = self.font_name.get() font_weight = tkfont.BOLD if self.font_bold.get() else tkfont.NORMAL new_font = (font_name, self.font_size.get(), font_weight) self.font_sample['font'] = new_font self.highlight_sample['font'] = new_font class HighPage(Frame): def __init__(self, master, extpage): super().__init__(master) self.extpage = extpage self.cd = master.winfo_toplevel() self.style = Style(master) self.create_page_highlight() self.load_theme_cfg() def create_page_highlight(self): """Return frame of widgets for Highlights tab. Enable users to provisionally change foreground and background colors applied to textual tags. Color mappings are stored in complete listings called themes. Built-in themes in idlelib/config-highlight.def are fixed as far as the dialog is concerned. Any theme can be used as the base for a new custom theme, stored in .idlerc/config-highlight.cfg. Function load_theme_cfg() initializes tk variables and theme lists and calls paint_theme_sample() and set_highlight_target() for the current theme. Radiobuttons builtin_theme_on and custom_theme_on toggle var theme_source, which controls if the current set of colors are from a builtin or custom theme. DynOptionMenus builtinlist and customlist contain lists of the builtin and custom themes, respectively, and the current item from each list is stored in vars builtin_name and custom_name. Function paint_theme_sample() applies the colors from the theme to the tags in text widget highlight_sample and then invokes set_color_sample(). Function set_highlight_target() sets the state of the radiobuttons fg_on and bg_on based on the tag and it also invokes set_color_sample(). Function set_color_sample() sets the background color for the frame holding the color selector. This provides a larger visual of the color for the current tag and plane (foreground/background). Note: set_color_sample() is called from many places and is often called more than once when a change is made. It is invoked when foreground or background is selected (radiobuttons), from paint_theme_sample() (theme is changed or load_cfg is called), and from set_highlight_target() (target tag is changed or load_cfg called). Button delete_custom invokes delete_custom() to delete a custom theme from idleConf.userCfg['highlight'] and changes. Button save_custom invokes save_as_new_theme() which calls get_new_theme_name() and create_new() to save a custom theme and its colors to idleConf.userCfg['highlight']. Radiobuttons fg_on and bg_on toggle var fg_bg_toggle to control if the current selected color for a tag is for the foreground or background. DynOptionMenu targetlist contains a readable description of the tags applied to Python source within IDLE. Selecting one of the tags from this list populates highlight_target, which has a callback function set_highlight_target(). Text widget highlight_sample displays a block of text (which is mock Python code) in which is embedded the defined tags and reflects the color attributes of the current theme and changes for those tags. Mouse button 1 allows for selection of a tag and updates highlight_target with that tag value. Note: The font in highlight_sample is set through the config in the fonts tab. In other words, a tag can be selected either from targetlist or by clicking on the sample text within highlight_sample. The plane (foreground/background) is selected via the radiobutton. Together, these two (tag and plane) control what color is shown in set_color_sample() for the current theme. Button set_color invokes get_color() which displays a ColorChooser to change the color for the selected tag/plane. If a new color is picked, it will be saved to changes and the highlight_sample and frame background will be updated. Tk Variables: color: Color of selected target. builtin_name: Menu variable for built-in theme. custom_name: Menu variable for custom theme. fg_bg_toggle: Toggle for foreground/background color. Note: this has no callback. theme_source: Selector for built-in or custom theme. highlight_target: Menu variable for the highlight tag target. Instance Data Attributes: theme_elements: Dictionary of tags for text highlighting. The key is the display name and the value is a tuple of (tag name, display sort order). Methods [attachment]: load_theme_cfg: Load current highlight colors. get_color: Invoke colorchooser [button_set_color]. set_color_sample_binding: Call set_color_sample [fg_bg_toggle]. set_highlight_target: set fg_bg_toggle, set_color_sample(). set_color_sample: Set frame background to target. on_new_color_set: Set new color and add option. paint_theme_sample: Recolor sample. get_new_theme_name: Get from popup. create_new: Combine theme with changes and save. save_as_new_theme: Save [button_save_custom]. set_theme_type: Command for [theme_source]. delete_custom: Activate default [button_delete_custom]. save_new: Save to userCfg['theme'] (is function). Widgets of highlights page frame: (*) widgets bound to self frame_custom: LabelFrame (*)highlight_sample: Text (*)frame_color_set: Frame (*)button_set_color: Button (*)targetlist: DynOptionMenu - highlight_target frame_fg_bg_toggle: Frame (*)fg_on: Radiobutton - fg_bg_toggle (*)bg_on: Radiobutton - fg_bg_toggle (*)button_save_custom: Button frame_theme: LabelFrame theme_type_title: Label (*)builtin_theme_on: Radiobutton - theme_source (*)custom_theme_on: Radiobutton - theme_source (*)builtinlist: DynOptionMenu - builtin_name (*)customlist: DynOptionMenu - custom_name (*)button_delete_custom: Button (*)theme_message: Label """ self.theme_elements = { 'Normal Code or Text': ('normal', '00'), 'Code Context': ('context', '01'), 'Python Keywords': ('keyword', '02'), 'Python Definitions': ('definition', '03'), 'Python Builtins': ('builtin', '04'), 'Python Comments': ('comment', '05'), 'Python Strings': ('string', '06'), 'Selected Text': ('hilite', '07'), 'Found Text': ('hit', '08'), 'Cursor': ('cursor', '09'), 'Editor Breakpoint': ('break', '10'), 'Shell Prompt': ('console', '11'), 'Error Text': ('error', '12'), 'Shell User Output': ('stdout', '13'), 'Shell User Exception': ('stderr', '14'), 'Line Number': ('linenumber', '16'), } self.builtin_name = tracers.add( StringVar(self), self.var_changed_builtin_name) self.custom_name = tracers.add( StringVar(self), self.var_changed_custom_name) self.fg_bg_toggle = BooleanVar(self) self.color = tracers.add( StringVar(self), self.var_changed_color) self.theme_source = tracers.add( BooleanVar(self), self.var_changed_theme_source) self.highlight_target = tracers.add( StringVar(self), self.var_changed_highlight_target) # Create widgets: # body frame and section frames. frame_custom = LabelFrame(self, borderwidth=2, relief=GROOVE, text=' Custom Highlighting ') frame_theme = LabelFrame(self, borderwidth=2, relief=GROOVE, text=' Highlighting Theme ') # frame_custom. sample_frame = ScrollableTextFrame( frame_custom, relief=SOLID, borderwidth=1) text = self.highlight_sample = sample_frame.text text.configure( font=('courier', 12, ''), cursor='hand2', width=1, height=1, takefocus=FALSE, highlightthickness=0, wrap=NONE) # Prevent perhaps invisible selection of word or slice. text.bind('<Double-Button-1>', lambda e: 'break') text.bind('<B1-Motion>', lambda e: 'break') string_tags=( ('# Click selects item.', 'comment'), ('\n', 'normal'), ('code context section', 'context'), ('\n', 'normal'), ('| cursor', 'cursor'), ('\n', 'normal'), ('def', 'keyword'), (' ', 'normal'), ('func', 'definition'), ('(param):\n ', 'normal'), ('"Return None."', 'string'), ('\n var0 = ', 'normal'), ("'string'", 'string'), ('\n var1 = ', 'normal'), ("'selected'", 'hilite'), ('\n var2 = ', 'normal'), ("'found'", 'hit'), ('\n var3 = ', 'normal'), ('list', 'builtin'), ('(', 'normal'), ('None', 'keyword'), (')\n', 'normal'), (' breakpoint("line")', 'break'), ('\n\n', 'normal'), ('>>>', 'console'), (' 3.14**2\n', 'normal'), ('9.8596', 'stdout'), ('\n', 'normal'), ('>>>', 'console'), (' pri ', 'normal'), ('n', 'error'), ('t(\n', 'normal'), ('SyntaxError', 'stderr'), ('\n', 'normal')) for string, tag in string_tags: text.insert(END, string, tag) n_lines = len(text.get('1.0', END).splitlines()) for lineno in range(1, n_lines): text.insert(f'{lineno}.0', f'{lineno:{len(str(n_lines))}d} ', 'linenumber') for element in self.theme_elements: def tem(event, elem=element): # event.widget.winfo_top_level().highlight_target.set(elem) self.highlight_target.set(elem) text.tag_bind( self.theme_elements[element][0], '<ButtonPress-1>', tem) text['state'] = 'disabled' self.style.configure('frame_color_set.TFrame', borderwidth=1, relief='solid') self.frame_color_set = Frame(frame_custom, style='frame_color_set.TFrame') frame_fg_bg_toggle = Frame(frame_custom) self.button_set_color = Button( self.frame_color_set, text='Choose Color for :', command=self.get_color) self.targetlist = DynOptionMenu( self.frame_color_set, self.highlight_target, None, highlightthickness=0) #, command=self.set_highlight_targetBinding self.fg_on = Radiobutton( frame_fg_bg_toggle, variable=self.fg_bg_toggle, value=1, text='Foreground', command=self.set_color_sample_binding) self.bg_on = Radiobutton( frame_fg_bg_toggle, variable=self.fg_bg_toggle, value=0, text='Background', command=self.set_color_sample_binding) self.fg_bg_toggle.set(1) self.button_save_custom = Button( frame_custom, text='Save as New Custom Theme', command=self.save_as_new_theme) # frame_theme. theme_type_title = Label(frame_theme, text='Select : ') self.builtin_theme_on = Radiobutton( frame_theme, variable=self.theme_source, value=1, command=self.set_theme_type, text='a Built-in Theme') self.custom_theme_on = Radiobutton( frame_theme, variable=self.theme_source, value=0, command=self.set_theme_type, text='a Custom Theme') self.builtinlist = DynOptionMenu( frame_theme, self.builtin_name, None, command=None) self.customlist = DynOptionMenu( frame_theme, self.custom_name, None, command=None) self.button_delete_custom = Button( frame_theme, text='Delete Custom Theme', command=self.delete_custom) self.theme_message = Label(frame_theme, borderwidth=2) # Pack widgets: # body. frame_custom.pack(side=LEFT, padx=5, pady=5, expand=TRUE, fill=BOTH) frame_theme.pack(side=TOP, padx=5, pady=5, fill=X) # frame_custom. self.frame_color_set.pack(side=TOP, padx=5, pady=5, fill=X) frame_fg_bg_toggle.pack(side=TOP, padx=5, pady=0) sample_frame.pack( side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH) self.button_set_color.pack(side=TOP, expand=TRUE, fill=X, padx=8, pady=4) self.targetlist.pack(side=TOP, expand=TRUE, fill=X, padx=8, pady=3) self.fg_on.pack(side=LEFT, anchor=E) self.bg_on.pack(side=RIGHT, anchor=W) self.button_save_custom.pack(side=BOTTOM, fill=X, padx=5, pady=5) # frame_theme. theme_type_title.pack(side=TOP, anchor=W, padx=5, pady=5) self.builtin_theme_on.pack(side=TOP, anchor=W, padx=5) self.custom_theme_on.pack(side=TOP, anchor=W, padx=5, pady=2) self.builtinlist.pack(side=TOP, fill=X, padx=5, pady=5) self.customlist.pack(side=TOP, fill=X, anchor=W, padx=5, pady=5) self.button_delete_custom.pack(side=TOP, fill=X, padx=5, pady=5) self.theme_message.pack(side=TOP, fill=X, pady=5) def load_theme_cfg(self): """Load current configuration settings for the theme options. Based on the theme_source toggle, the theme is set as either builtin or custom and the initial widget values reflect the current settings from idleConf. Attributes updated: theme_source: Set from idleConf. builtinlist: List of default themes from idleConf. customlist: List of custom themes from idleConf. custom_theme_on: Disabled if there are no custom themes. custom_theme: Message with additional information. targetlist: Create menu from self.theme_elements. Methods: set_theme_type paint_theme_sample set_highlight_target """ # Set current theme type radiobutton. self.theme_source.set(idleConf.GetOption( 'main', 'Theme', 'default', type='bool', default=1)) # Set current theme. current_option = idleConf.CurrentTheme() # Load available theme option menus. if self.theme_source.get(): # Default theme selected. item_list = idleConf.GetSectionList('default', 'highlight') item_list.sort() self.builtinlist.SetMenu(item_list, current_option) item_list = idleConf.GetSectionList('user', 'highlight') item_list.sort() if not item_list: self.custom_theme_on.state(('disabled',)) self.custom_name.set('- no custom themes -') else: self.customlist.SetMenu(item_list, item_list[0]) else: # User theme selected. item_list = idleConf.GetSectionList('user', 'highlight') item_list.sort() self.customlist.SetMenu(item_list, current_option) item_list = idleConf.GetSectionList('default', 'highlight') item_list.sort() self.builtinlist.SetMenu(item_list, item_list[0]) self.set_theme_type() # Load theme element option menu. theme_names = list(self.theme_elements.keys()) theme_names.sort(key=lambda x: self.theme_elements[x][1]) self.targetlist.SetMenu(theme_names, theme_names[0]) self.paint_theme_sample() self.set_highlight_target() def var_changed_builtin_name(self, *params): """Process new builtin theme selection. Add the changed theme's name to the changed_items and recreate the sample with the values from the selected theme. """ old_themes = ('IDLE Classic', 'IDLE New') value = self.builtin_name.get() if value not in old_themes: if idleConf.GetOption('main', 'Theme', 'name') not in old_themes: changes.add_option('main', 'Theme', 'name', old_themes[0]) changes.add_option('main', 'Theme', 'name2', value) self.theme_message['text'] = 'New theme, see Help' else: changes.add_option('main', 'Theme', 'name', value) changes.add_option('main', 'Theme', 'name2', '') self.theme_message['text'] = '' self.paint_theme_sample() def var_changed_custom_name(self, *params): """Process new custom theme selection. If a new custom theme is selected, add the name to the changed_items and apply the theme to the sample. """ value = self.custom_name.get() if value != '- no custom themes -': changes.add_option('main', 'Theme', 'name', value) self.paint_theme_sample() def var_changed_theme_source(self, *params): """Process toggle between builtin and custom theme. Update the default toggle value and apply the newly selected theme type. """ value = self.theme_source.get() changes.add_option('main', 'Theme', 'default', value) if value: self.var_changed_builtin_name() else: self.var_changed_custom_name() def var_changed_color(self, *params): "Process change to color choice." self.on_new_color_set() def var_changed_highlight_target(self, *params): "Process selection of new target tag for highlighting." self.set_highlight_target() def set_theme_type(self): """Set available screen options based on builtin or custom theme. Attributes accessed: theme_source Attributes updated: builtinlist customlist button_delete_custom custom_theme_on Called from: handler for builtin_theme_on and custom_theme_on delete_custom create_new load_theme_cfg """ if self.theme_source.get(): self.builtinlist['state'] = 'normal' self.customlist['state'] = 'disabled' self.button_delete_custom.state(('disabled',)) else: self.builtinlist['state'] = 'disabled' self.custom_theme_on.state(('!disabled',)) self.customlist['state'] = 'normal' self.button_delete_custom.state(('!disabled',)) def get_color(self): """Handle button to select a new color for the target tag. If a new color is selected while using a builtin theme, a name must be supplied to create a custom theme. Attributes accessed: highlight_target frame_color_set theme_source Attributes updated: color Methods: get_new_theme_name create_new """ target = self.highlight_target.get() prev_color = self.style.lookup(self.frame_color_set['style'], 'background') rgbTuplet, color_string = colorchooser.askcolor( parent=self, title='Pick new color for : '+target, initialcolor=prev_color) if color_string and (color_string != prev_color): # User didn't cancel and they chose a new color. if self.theme_source.get(): # Current theme is a built-in. message = ('Your changes will be saved as a new Custom Theme. ' 'Enter a name for your new Custom Theme below.') new_theme = self.get_new_theme_name(message) if not new_theme: # User cancelled custom theme creation. return else: # Create new custom theme based on previously active theme. self.create_new(new_theme) self.color.set(color_string) else: # Current theme is user defined. self.color.set(color_string) def on_new_color_set(self): "Display sample of new color selection on the dialog." new_color = self.color.get() self.style.configure('frame_color_set.TFrame', background=new_color) plane = 'foreground' if self.fg_bg_toggle.get() else 'background' sample_element = self.theme_elements[self.highlight_target.get()][0] self.highlight_sample.tag_config(sample_element, **{plane: new_color}) theme = self.custom_name.get() theme_element = sample_element + '-' + plane changes.add_option('highlight', theme, theme_element, new_color) def get_new_theme_name(self, message): "Return name of new theme from query popup." used_names = (idleConf.GetSectionList('user', 'highlight') + idleConf.GetSectionList('default', 'highlight')) new_theme = SectionName( self, 'New Custom Theme', message, used_names).result return new_theme def save_as_new_theme(self): """Prompt for new theme name and create the theme. Methods: get_new_theme_name create_new """ new_theme_name = self.get_new_theme_name('New Theme Name:') if new_theme_name: self.create_new(new_theme_name) def create_new(self, new_theme_name): """Create a new custom theme with the given name. Create the new theme based on the previously active theme with the current changes applied. Once it is saved, then activate the new theme. Attributes accessed: builtin_name custom_name Attributes updated: customlist theme_source Method: save_new set_theme_type """ if self.theme_source.get(): theme_type = 'default' theme_name = self.builtin_name.get() else: theme_type = 'user' theme_name = self.custom_name.get() new_theme = idleConf.GetThemeDict(theme_type, theme_name) # Apply any of the old theme's unsaved changes to the new theme. if theme_name in changes['highlight']: theme_changes = changes['highlight'][theme_name] for element in theme_changes: new_theme[element] = theme_changes[element] # Save the new theme. self.save_new(new_theme_name, new_theme) # Change GUI over to the new theme. custom_theme_list = idleConf.GetSectionList('user', 'highlight') custom_theme_list.sort() self.customlist.SetMenu(custom_theme_list, new_theme_name) self.theme_source.set(0) self.set_theme_type() def set_highlight_target(self): """Set fg/bg toggle and color based on highlight tag target. Instance variables accessed: highlight_target Attributes updated: fg_on bg_on fg_bg_toggle Methods: set_color_sample Called from: var_changed_highlight_target load_theme_cfg """ if self.highlight_target.get() == 'Cursor': # bg not possible self.fg_on.state(('disabled',)) self.bg_on.state(('disabled',)) self.fg_bg_toggle.set(1) else: # Both fg and bg can be set. self.fg_on.state(('!disabled',)) self.bg_on.state(('!disabled',)) self.fg_bg_toggle.set(1) self.set_color_sample() def set_color_sample_binding(self, *args): """Change color sample based on foreground/background toggle. Methods: set_color_sample """ self.set_color_sample() def set_color_sample(self): """Set the color of the frame background to reflect the selected target. Instance variables accessed: theme_elements highlight_target fg_bg_toggle highlight_sample Attributes updated: frame_color_set """ # Set the color sample area. tag = self.theme_elements[self.highlight_target.get()][0] plane = 'foreground' if self.fg_bg_toggle.get() else 'background' color = self.highlight_sample.tag_cget(tag, plane) self.style.configure('frame_color_set.TFrame', background=color) def paint_theme_sample(self): """Apply the theme colors to each element tag in the sample text. Instance attributes accessed: theme_elements theme_source builtin_name custom_name Attributes updated: highlight_sample: Set the tag elements to the theme. Methods: set_color_sample Called from: var_changed_builtin_name var_changed_custom_name load_theme_cfg """ if self.theme_source.get(): # Default theme theme = self.builtin_name.get() else: # User theme theme = self.custom_name.get() for element_title in self.theme_elements: element = self.theme_elements[element_title][0] colors = idleConf.GetHighlight(theme, element) if element == 'cursor': # Cursor sample needs special painting. colors['background'] = idleConf.GetHighlight( theme, 'normal')['background'] # Handle any unsaved changes to this theme. if theme in changes['highlight']: theme_dict = changes['highlight'][theme] if element + '-foreground' in theme_dict: colors['foreground'] = theme_dict[element + '-foreground'] if element + '-background' in theme_dict: colors['background'] = theme_dict[element + '-background'] self.highlight_sample.tag_config(element, **colors) self.set_color_sample() def save_new(self, theme_name, theme): """Save a newly created theme to idleConf. theme_name - string, the name of the new theme theme - dictionary containing the new theme """ idleConf.userCfg['highlight'].AddSection(theme_name) for element in theme: value = theme[element] idleConf.userCfg['highlight'].SetOption(theme_name, element, value) def askyesno(self, *args, **kwargs): # Make testing easier. Could change implementation. return messagebox.askyesno(*args, **kwargs) def delete_custom(self): """Handle event to delete custom theme. The current theme is deactivated and the default theme is activated. The custom theme is permanently removed from the config file. Attributes accessed: custom_name Attributes updated: custom_theme_on customlist theme_source builtin_name Methods: deactivate_current_config save_all_changed_extensions activate_config_changes set_theme_type """ theme_name = self.custom_name.get() delmsg = 'Are you sure you wish to delete the theme %r ?' if not self.askyesno( 'Delete Theme', delmsg % theme_name, parent=self): return self.cd.deactivate_current_config() # Remove theme from changes, config, and file. changes.delete_section('highlight', theme_name) # Reload user theme list. item_list = idleConf.GetSectionList('user', 'highlight') item_list.sort() if not item_list: self.custom_theme_on.state(('disabled',)) self.customlist.SetMenu(item_list, '- no custom themes -') else: self.customlist.SetMenu(item_list, item_list[0]) # Revert to default theme. self.theme_source.set(idleConf.defaultCfg['main'].Get('Theme', 'default')) self.builtin_name.set(idleConf.defaultCfg['main'].Get('Theme', 'name')) # User can't back out of these changes, they must be applied now. changes.save_all() self.extpage.save_all_changed_extensions() self.cd.activate_config_changes() self.set_theme_type() class KeysPage(Frame): def __init__(self, master, extpage): super().__init__(master) self.extpage = extpage self.cd = master.winfo_toplevel() self.create_page_keys() self.load_key_cfg() def create_page_keys(self): """Return frame of widgets for Keys tab. Enable users to provisionally change both individual and sets of keybindings (shortcut keys). Except for features implemented as extensions, keybindings are stored in complete sets called keysets. Built-in keysets in idlelib/config-keys.def are fixed as far as the dialog is concerned. Any keyset can be used as the base for a new custom keyset, stored in .idlerc/config-keys.cfg. Function load_key_cfg() initializes tk variables and keyset lists and calls load_keys_list for the current keyset. Radiobuttons builtin_keyset_on and custom_keyset_on toggle var keyset_source, which controls if the current set of keybindings are from a builtin or custom keyset. DynOptionMenus builtinlist and customlist contain lists of the builtin and custom keysets, respectively, and the current item from each list is stored in vars builtin_name and custom_name. Button delete_custom_keys invokes delete_custom_keys() to delete a custom keyset from idleConf.userCfg['keys'] and changes. Button save_custom_keys invokes save_as_new_key_set() which calls get_new_keys_name() and create_new_key_set() to save a custom keyset and its keybindings to idleConf.userCfg['keys']. Listbox bindingslist contains all of the keybindings for the selected keyset. The keybindings are loaded in load_keys_list() and are pairs of (event, [keys]) where keys can be a list of one or more key combinations to bind to the same event. Mouse button 1 click invokes on_bindingslist_select(), which allows button_new_keys to be clicked. So, an item is selected in listbindings, which activates button_new_keys, and clicking button_new_keys calls function get_new_keys(). Function get_new_keys() gets the key mappings from the current keyset for the binding event item that was selected. The function then displays another dialog, GetKeysDialog, with the selected binding event and current keys and allows new key sequences to be entered for that binding event. If the keys aren't changed, nothing happens. If the keys are changed and the keyset is a builtin, function get_new_keys_name() will be called for input of a custom keyset name. If no name is given, then the change to the keybinding will abort and no updates will be made. If a custom name is entered in the prompt or if the current keyset was already custom (and thus didn't require a prompt), then idleConf.userCfg['keys'] is updated in function create_new_key_set() with the change to the event binding. The item listing in bindingslist is updated with the new keys. Var keybinding is also set which invokes the callback function, var_changed_keybinding, to add the change to the 'keys' or 'extensions' changes tracker based on the binding type. Tk Variables: keybinding: Action/key bindings. Methods: load_keys_list: Reload active set. create_new_key_set: Combine active keyset and changes. set_keys_type: Command for keyset_source. save_new_key_set: Save to idleConf.userCfg['keys'] (is function). deactivate_current_config: Remove keys bindings in editors. Widgets for KeysPage(frame): (*) widgets bound to self frame_key_sets: LabelFrame frames[0]: Frame (*)builtin_keyset_on: Radiobutton - var keyset_source (*)custom_keyset_on: Radiobutton - var keyset_source (*)builtinlist: DynOptionMenu - var builtin_name, func keybinding_selected (*)customlist: DynOptionMenu - var custom_name, func keybinding_selected (*)keys_message: Label frames[1]: Frame (*)button_delete_custom_keys: Button - delete_custom_keys (*)button_save_custom_keys: Button - save_as_new_key_set frame_custom: LabelFrame frame_target: Frame target_title: Label scroll_target_y: Scrollbar scroll_target_x: Scrollbar (*)bindingslist: ListBox - on_bindingslist_select (*)button_new_keys: Button - get_new_keys & ..._name """ self.builtin_name = tracers.add( StringVar(self), self.var_changed_builtin_name) self.custom_name = tracers.add( StringVar(self), self.var_changed_custom_name) self.keyset_source = tracers.add( BooleanVar(self), self.var_changed_keyset_source) self.keybinding = tracers.add( StringVar(self), self.var_changed_keybinding) # Create widgets: # body and section frames. frame_custom = LabelFrame( self, borderwidth=2, relief=GROOVE, text=' Custom Key Bindings ') frame_key_sets = LabelFrame( self, borderwidth=2, relief=GROOVE, text=' Key Set ') # frame_custom. frame_target = Frame(frame_custom) target_title = Label(frame_target, text='Action - Key(s)') scroll_target_y = Scrollbar(frame_target) scroll_target_x = Scrollbar(frame_target, orient=HORIZONTAL) self.bindingslist = Listbox( frame_target, takefocus=FALSE, exportselection=FALSE) self.bindingslist.bind('<ButtonRelease-1>', self.on_bindingslist_select) scroll_target_y['command'] = self.bindingslist.yview scroll_target_x['command'] = self.bindingslist.xview self.bindingslist['yscrollcommand'] = scroll_target_y.set self.bindingslist['xscrollcommand'] = scroll_target_x.set self.button_new_keys = Button( frame_custom, text='Get New Keys for Selection', command=self.get_new_keys, state='disabled') # frame_key_sets. frames = [Frame(frame_key_sets, padding=2, borderwidth=0) for i in range(2)] self.builtin_keyset_on = Radiobutton( frames[0], variable=self.keyset_source, value=1, command=self.set_keys_type, text='Use a Built-in Key Set') self.custom_keyset_on = Radiobutton( frames[0], variable=self.keyset_source, value=0, command=self.set_keys_type, text='Use a Custom Key Set') self.builtinlist = DynOptionMenu( frames[0], self.builtin_name, None, command=None) self.customlist = DynOptionMenu( frames[0], self.custom_name, None, command=None) self.button_delete_custom_keys = Button( frames[1], text='Delete Custom Key Set', command=self.delete_custom_keys) self.button_save_custom_keys = Button( frames[1], text='Save as New Custom Key Set', command=self.save_as_new_key_set) self.keys_message = Label(frames[0], borderwidth=2) # Pack widgets: # body. frame_custom.pack(side=BOTTOM, padx=5, pady=5, expand=TRUE, fill=BOTH) frame_key_sets.pack(side=BOTTOM, padx=5, pady=5, fill=BOTH) # frame_custom. self.button_new_keys.pack(side=BOTTOM, fill=X, padx=5, pady=5)