summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel/qstandardgestures.cpp
blob: 6b0441bd8dc5a77c54255cc6f68cea033c1d626b (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qstandardgestures_p.h"
#include "qgesture.h"
#include "qgesture_p.h"
#include "qevent.h"
#include "qwidget.h"
#include "qabstractscrollarea.h"
#include "qdebug.h"

QT_BEGIN_NAMESPACE

QPanGestureRecognizer::QPanGestureRecognizer()
{
}

QGesture *QPanGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
#if defined(Q_OS_WIN) && !defined(QT_NO_NATIVE_GESTURES)
        // for scroll areas on Windows we want to use native gestures instead
        if (!qobject_cast<QAbstractScrollArea *>(target->parent()))
            static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
#else
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
#endif
    }
    return new QPanGesture;
}

QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
                                                            QObject *,
                                                            QEvent *event)
{
    QPanGesture *q = static_cast<QPanGesture *>(state);
    QPanGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;
    switch (event->type()) {
    case QEvent::TouchBegin: {
        result = QGestureRecognizer::MayBeGesture;
        QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
        d->lastOffset = d->offset = QPointF();
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            if (ev->touchPoints().size() == 2) {
                QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
                QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
                d->lastOffset = d->offset;
                d->offset =
                        QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
                              p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
            }
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        if (ev->touchPoints().size() >= 2) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
            d->lastOffset = d->offset;
            d->offset =
                    QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
                          p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
            if (d->offset.x() > 10  || d->offset.y() > 10 ||
                d->offset.x() < -10 || d->offset.y() < -10) {
                result = QGestureRecognizer::TriggerGesture;
            } else {
                result = QGestureRecognizer::MayBeGesture;
            }
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QPanGestureRecognizer::reset(QGesture *state)
{
    QPanGesture *pan = static_cast<QPanGesture*>(state);
    QPanGesturePrivate *d = pan->d_func();

    d->lastOffset = d->offset = QPointF();
    d->acceleration = 0;

    QGestureRecognizer::reset(state);
}


//
// QPinchGestureRecognizer
//

QPinchGestureRecognizer::QPinchGestureRecognizer()
{
}

QGesture *QPinchGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QPinchGesture;
}

QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
                                                              QObject *,
                                                              QEvent *event)
{
    QPinchGesture *q = static_cast<QPinchGesture *>(state);
    QPinchGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        result = QGestureRecognizer::MayBeGesture;
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        d->changeFlags = 0;
        if (ev->touchPoints().size() == 2) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);

            d->hotSpot = p1.screenPos();
            d->isHotSpotSet = true;

            if (d->isNewSequence) {
                d->startPosition[0] = p1.screenPos();
                d->startPosition[1] = p2.screenPos();
            }
            QLineF line(p1.screenPos(), p2.screenPos());
            QLineF tmp(line);
            tmp.setLength(line.length() / 2.);
            QPointF centerPoint = tmp.p2();

            d->lastCenterPoint = d->centerPoint;
            d->centerPoint = centerPoint;
            d->changeFlags |= QPinchGesture::CenterPointChanged;

            const qreal scaleFactor =
                    QLineF(p1.screenPos(), p2.screenPos()).length()
                    / QLineF(d->startPosition[0],  d->startPosition[1]).length();
            if (d->isNewSequence) {
                d->lastScaleFactor = scaleFactor;
            } else {
                d->lastScaleFactor = d->scaleFactor;
            }
            d->scaleFactor = scaleFactor;
            d->totalScaleFactor += d->scaleFactor - d->lastScaleFactor;
            d->changeFlags |= QPinchGesture::ScaleFactorChanged;

            qreal angle = QLineF(p1.screenPos(), p2.screenPos()).angle();
            if (angle > 180)
                angle -= 360;
            qreal startAngle = QLineF(p1.startScreenPos(), p2.startScreenPos()).angle();
            if (startAngle > 180)
                startAngle -= 360;
            const qreal rotationAngle = startAngle - angle;
            if (d->isNewSequence)
                d->lastRotationAngle = rotationAngle;
            else
                d->lastRotationAngle = d->rotationAngle;
            d->rotationAngle = rotationAngle;
            d->totalRotationAngle += d->rotationAngle - d->lastRotationAngle;
            d->changeFlags |= QPinchGesture::RotationAngleChanged;

            d->totalChangeFlags |= d->changeFlags;
            d->isNewSequence = false;
            result = QGestureRecognizer::TriggerGesture;
        } else {
            d->isNewSequence = true;
            if (q->state() == Qt::NoGesture)
                result = QGestureRecognizer::Ignore;
            else
                result = QGestureRecognizer::FinishGesture;
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QPinchGestureRecognizer::reset(QGesture *state)
{
    QPinchGesture *pinch = static_cast<QPinchGesture *>(state);
    QPinchGesturePrivate *d = pinch->d_func();

    d->totalChangeFlags = d->changeFlags = 0;

    d->startCenterPoint = d->lastCenterPoint = d->centerPoint = QPointF();
    d->totalScaleFactor = d->lastScaleFactor = d->scaleFactor = 0;
    d->totalRotationAngle = d->lastRotationAngle = d->rotationAngle = 0;

    d->isNewSequence = true;
    d->startPosition[0] = d->startPosition[1] = QPointF();

    QGestureRecognizer::reset(state);
}

//
// QSwipeGestureRecognizer
//

QSwipeGestureRecognizer::QSwipeGestureRecognizer()
{
}

QGesture *QSwipeGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QSwipeGesture;
}

QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
                                                              QObject *,
                                                              QEvent *event)
{
    QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
    QSwipeGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        d->speed = 1;
        d->time = QTime::currentTime();
        d->started = true;
        result = QGestureRecognizer::MayBeGesture;
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        if (!d->started)
            result = QGestureRecognizer::CancelGesture;
        else if (ev->touchPoints().size() == 3) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
            QTouchEvent::TouchPoint p3 = ev->touchPoints().at(2);

            if (d->lastPositions[0].isNull()) {
                d->lastPositions[0] = p1.startScreenPos().toPoint();
                d->lastPositions[1] = p2.startScreenPos().toPoint();
                d->lastPositions[2] = p3.startScreenPos().toPoint();
            }
            d->hotSpot = p1.screenPos();
            d->isHotSpotSet = true;

            int xDistance = (p1.screenPos().x() - d->lastPositions[0].x() +
                             p2.screenPos().x() - d->lastPositions[1].x() +
                             p3.screenPos().x() - d->lastPositions[2].x()) / 3;
            int yDistance = (p1.screenPos().y() - d->lastPositions[0].y() +
                             p2.screenPos().y() - d->lastPositions[1].y() +
                             p3.screenPos().y() - d->lastPositions[2].y()) / 3;

            const int distance = xDistance >= yDistance ? xDistance : yDistance;
            int elapsedTime = d->time.msecsTo(QTime::currentTime());
            if (!elapsedTime)
                elapsedTime = 1;
            d->speed = 0.9 * d->speed + distance / elapsedTime;
            d->time = QTime::currentTime();
            d->swipeAngle = QLineF(p1.startScreenPos(), p1.screenPos()).angle();

            static const int MoveThreshold = 50;
            if (xDistance > MoveThreshold || yDistance > MoveThreshold) {
                // measure the distance to check if the direction changed
                d->lastPositions[0] = p1.screenPos().toPoint();
                d->lastPositions[1] = p2.screenPos().toPoint();
                d->lastPositions[2] = p3.screenPos().toPoint();
                QSwipeGesture::SwipeDirection horizontal =
                        xDistance > 0 ? QSwipeGesture::Right : QSwipeGesture::Left;
                QSwipeGesture::SwipeDirection vertical =
                        yDistance > 0 ? QSwipeGesture::Down : QSwipeGesture::Up;
                if (d->verticalDirection == QSwipeGesture::NoDirection)
                    d->verticalDirection = vertical;
                if (d->horizontalDirection == QSwipeGesture::NoDirection)
                    d->horizontalDirection = horizontal;
                if (d->verticalDirection != vertical || d->horizontalDirection != horizontal) {
                    // the user has changed the direction!
                    result = QGestureRecognizer::CancelGesture;
                }
                result = QGestureRecognizer::TriggerGesture;
            } else {
                if (q->state() != Qt::NoGesture)
                    result = QGestureRecognizer::TriggerGesture;
                else
                    result = QGestureRecognizer::MayBeGesture;
            }
        } else if (ev->touchPoints().size() > 3) {
            result = QGestureRecognizer::CancelGesture;
        } else { // less than 3 touch points
            if (d->started && (ev->touchPointStates() & Qt::TouchPointPressed))
                result = QGestureRecognizer::CancelGesture;
            else if (d->started)
                result = QGestureRecognizer::Ignore;
            else
                result = QGestureRecognizer::MayBeGesture;
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QSwipeGestureRecognizer::reset(QGesture *state)
{
    QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
    QSwipeGesturePrivate *d = q->d_func();

    d->verticalDirection = d->horizontalDirection = QSwipeGesture::NoDirection;
    d->swipeAngle = 0;

    d->lastPositions[0] = d->lastPositions[1] = d->lastPositions[2] = QPoint();
    d->started = false;
    d->speed = 0;
    d->time = QTime();

    QGestureRecognizer::reset(state);
}

//
// QTapGestureRecognizer
//

QTapGestureRecognizer::QTapGestureRecognizer()
{
}

QGesture *QTapGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QTapGesture;
}

QGestureRecognizer::Result QTapGestureRecognizer::recognize(QGesture *state,
                                                            QObject *,
                                                            QEvent *event)
{
    QTapGesture *q = static_cast<QTapGesture *>(state);
    QTapGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result = QGestureRecognizer::CancelGesture;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        d->position = ev->touchPoints().at(0).pos();
        result = QGestureRecognizer::TriggerGesture;
        break;
    }
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture && ev->touchPoints().size() == 1) {
            QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
            QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
            enum { TapRadius = 40 };
            if (delta.manhattanLength() <= TapRadius) {
                if (event->type() == QEvent::TouchEnd)
                    result = QGestureRecognizer::FinishGesture;
                else
                    result = QGestureRecognizer::TriggerGesture;
            }
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QTapGestureRecognizer::reset(QGesture *state)
{
    QTapGesture *q = static_cast<QTapGesture *>(state);
    QTapGesturePrivate *d = q->d_func();

    d->position = QPointF();

    QGestureRecognizer::reset(state);
}

//
// QTapAndHoldGestureRecognizer
//

QTapAndHoldGestureRecognizer::QTapAndHoldGestureRecognizer()
{
}

QGesture *QTapAndHoldGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QTapAndHoldGesture;
}

QGestureRecognizer::Result
QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
                                        QEvent *event)
{
    QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
    QTapAndHoldGesturePrivate *d = q->d_func();

    if (object == state && event->type() == QEvent::Timer) {
        q->killTimer(d->timerId);
        d->timerId = 0;
        return QGestureRecognizer::Ignore | QGestureRecognizer::ConsumeEventHint;
    }

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result = QGestureRecognizer::CancelGesture;

    enum { TimerInterval = 2000 };
    enum { TapRadius = 40 };

    switch (event->type()) {
    case QEvent::TouchBegin:
        d->position = ev->touchPoints().at(0).pos();
        if (d->timerId)
            q->killTimer(d->timerId);
        d->timerId = q->startTimer(TimerInterval);
        result = QGestureRecognizer::TriggerGesture;
        break;
    case QEvent::TouchEnd:
        if (d->timerId)
            result = QGestureRecognizer::CancelGesture;
        else
            result = QGestureRecognizer::FinishGesture;
        break;
    case QEvent::TouchUpdate:
        if (q->state() != Qt::NoGesture && ev->touchPoints().size() == 1) {
            QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
            QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
            if (delta.manhattanLength() <= TapRadius)
                result = QGestureRecognizer::TriggerGesture;
        }
        break;
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QTapAndHoldGestureRecognizer::reset(QGesture *state)
{
    QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
    QTapAndHoldGesturePrivate *d = q->d_func();

    d->position = QPointF();
    if (d->timerId)
        q->killTimer(d->timerId);
    d->timerId = 0;

    QGestureRecognizer::reset(state);
}

QT_END_NAMESPACE
an>optionTable, (objc == 5) ? objv[4] : NULL, textPtr->tkwin); if (objPtr == NULL) { return TCL_ERROR; } Tcl_SetObjResult(interp, objPtr); return TCL_OK; } else { TkTextChanged(textPtr->sharedTextPtr, NULL, &index, &index); /* * It's probably not true that all window configuration can change * the line height, so we could be more efficient here and only * call this when necessary. */ TkTextInvalidateLineMetrics(textPtr->sharedTextPtr, NULL, index.linePtr, 0, TK_TEXT_INVALIDATE_ONLY); return EmbWinConfigure(textPtr, ewPtr, objc-4, objv+4); } } case WIND_CREATE: { TkTextIndex index; int lineIndex; TkTextEmbWindowClient *client; int res; /* * Add a new window. Find where to put the new window, and mark that * position for redisplay. */ if (objc < 4) { Tcl_WrongNumArgs(interp, 3, objv, "index ?-option value ...?"); return TCL_ERROR; } if (TkTextGetObjIndex(interp, textPtr, objv[3], &index) != TCL_OK) { return TCL_ERROR; } /* * Don't allow insertions on the last (dummy) line of the text. */ lineIndex = TkBTreeLinesTo(textPtr, index.linePtr); if (lineIndex == TkBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr)) { lineIndex--; TkTextMakeByteIndex(textPtr->sharedTextPtr->tree, textPtr, lineIndex, 1000000, &index); } /* * Create the new window segment and initialize it. */ ewPtr = ckalloc(EW_SEG_SIZE); ewPtr->typePtr = &tkTextEmbWindowType; ewPtr->size = 1; ewPtr->body.ew.sharedTextPtr = textPtr->sharedTextPtr; ewPtr->body.ew.linePtr = NULL; ewPtr->body.ew.tkwin = NULL; ewPtr->body.ew.create = NULL; ewPtr->body.ew.align = ALIGN_CENTER; ewPtr->body.ew.padX = ewPtr->body.ew.padY = 0; ewPtr->body.ew.stretch = 0; ewPtr->body.ew.optionTable = Tk_CreateOptionTable(interp, optionSpecs); client = ckalloc(sizeof(TkTextEmbWindowClient)); client->next = NULL; client->textPtr = textPtr; client->tkwin = NULL; client->chunkCount = 0; client->displayed = 0; client->parent = ewPtr; ewPtr->body.ew.clients = client; /* * Link the segment into the text widget, then configure it (delete it * again if the configuration fails). */ TkTextChanged(textPtr->sharedTextPtr, NULL, &index, &index); TkBTreeLinkSegment(ewPtr, &index); res = EmbWinConfigure(textPtr, ewPtr, objc-4, objv+4); client->tkwin = ewPtr->body.ew.tkwin; if (res != TCL_OK) { TkTextIndex index2; TkTextIndexForwChars(NULL, &index, 1, &index2, COUNT_INDICES); TkBTreeDeleteIndexRange(textPtr->sharedTextPtr->tree, &index, &index2); return TCL_ERROR; } TkTextInvalidateLineMetrics(textPtr->sharedTextPtr, NULL, index.linePtr, 0, TK_TEXT_INVALIDATE_ONLY); break; } case WIND_NAMES: { Tcl_HashSearch search; Tcl_HashEntry *hPtr; Tcl_Obj *resultObj; if (objc != 3) { Tcl_WrongNumArgs(interp, 3, objv, NULL); return TCL_ERROR; } resultObj = Tcl_NewObj(); for (hPtr = Tcl_FirstHashEntry(&textPtr->sharedTextPtr->windowTable, &search); hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj( Tcl_GetHashKey(&textPtr->sharedTextPtr->markTable, hPtr), -1)); } Tcl_SetObjResult(interp, resultObj); break; } } return TCL_OK; } /* *-------------------------------------------------------------- * * EmbWinConfigure -- * * This function is called to handle configuration options for an * embedded window, using an objc/objv list. * * Results: * The return value is a standard Tcl result. If TCL_ERROR is returned, * then the interp's result contains an error message.. * * Side effects: * Configuration information for the embedded window changes, such as * alignment, stretching, or name of the embedded window. * * Note that this function may leave widget specific client information * with a NULL tkwin attached to ewPtr. While we could choose to clean up * the client data structure here, there is no need to do so, and it is * likely that the user is going to adjust the tkwin again soon. * *-------------------------------------------------------------- */ static int EmbWinConfigure( TkText *textPtr, /* Information about text widget that contains * embedded window. */ TkTextSegment *ewPtr, /* Embedded window to be configured. */ int objc, /* Number of strings in objv. */ Tcl_Obj *const objv[]) /* Array of objects describing configuration * options. */ { Tk_Window oldWindow; TkTextEmbWindowClient *client; /* * Copy over client specific value before querying or setting. */ client = EmbWinGetClient(textPtr, ewPtr); if (client != NULL) { ewPtr->body.ew.tkwin = client->tkwin; } else { ewPtr->body.ew.tkwin = NULL; } oldWindow = ewPtr->body.ew.tkwin; if (Tk_SetOptions(textPtr->interp, (char *) &ewPtr->body.ew, ewPtr->body.ew.optionTable, objc, objv, textPtr->tkwin, NULL, NULL) != TCL_OK) { return TCL_ERROR; } if (oldWindow != ewPtr->body.ew.tkwin) { if (oldWindow != NULL) { Tcl_DeleteHashEntry(Tcl_FindHashEntry( &textPtr->sharedTextPtr->windowTable, Tk_PathName(oldWindow))); Tk_DeleteEventHandler(oldWindow, StructureNotifyMask, EmbWinStructureProc, client); Tk_ManageGeometry(oldWindow, NULL, NULL); if (textPtr->tkwin != Tk_Parent(oldWindow)) { Tk_UnmaintainGeometry(oldWindow, textPtr->tkwin); } else { Tk_UnmapWindow(oldWindow); } } if (client != NULL) { client->tkwin = NULL; } if (ewPtr->body.ew.tkwin != NULL) { Tk_Window ancestor, parent; Tcl_HashEntry *hPtr; int isNew; /* * Make sure that the text is either the parent of the embedded * window or a descendant of that parent. Also, don't allow a * top-level window to be managed inside a text. */ parent = Tk_Parent(ewPtr->body.ew.tkwin); for (ancestor = textPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { if (ancestor == parent) { break; } if (Tk_TopWinHierarchy(ancestor)) { badMaster: Tcl_SetObjResult(textPtr->interp, Tcl_ObjPrintf( "can't embed %s in %s", Tk_PathName(ewPtr->body.ew.tkwin), Tk_PathName(textPtr->tkwin))); Tcl_SetErrorCode(textPtr->interp, "TK", "GEOMETRY", "HIERARCHY", NULL); ewPtr->body.ew.tkwin = NULL; if (client != NULL) { client->tkwin = NULL; } return TCL_ERROR; } } if (Tk_TopWinHierarchy(ewPtr->body.ew.tkwin) || (ewPtr->body.ew.tkwin == textPtr->tkwin)) { goto badMaster; } if (client == NULL) { /* * Have to make the new client. */ client = ckalloc(sizeof(TkTextEmbWindowClient)); client->next = ewPtr->body.ew.clients; client->textPtr = textPtr; client->tkwin = NULL; client->chunkCount = 0; client->displayed = 0; client->parent = ewPtr; ewPtr->body.ew.clients = client; } client->tkwin = ewPtr->body.ew.tkwin; /* * Take over geometry management for the window, plus create an * event handler to find out when it is deleted. */ Tk_ManageGeometry(ewPtr->body.ew.tkwin, &textGeomType, client); Tk_CreateEventHandler(ewPtr->body.ew.tkwin, StructureNotifyMask, EmbWinStructureProc, client); /* * Special trick! Must enter into the hash table *after* calling * Tk_ManageGeometry: if the window was already managed elsewhere * in this text, the Tk_ManageGeometry call will cause the entry * to be removed, which could potentially lose the new entry. */ hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->windowTable, Tk_PathName(ewPtr->body.ew.tkwin), &isNew); Tcl_SetHashValue(hPtr, ewPtr); } } return TCL_OK; } /* *-------------------------------------------------------------- * * EmbWinStructureProc -- * * This function is invoked by the Tk event loop whenever StructureNotify * events occur for a window that's embedded in a text widget. This * function's only purpose is to clean up when windows are deleted. * * Results: * None. * * Side effects: * The window is disassociated from the window segment, and the portion * of the text is redisplayed. * *-------------------------------------------------------------- */ static void EmbWinStructureProc( ClientData clientData, /* Pointer to record describing window item. */ XEvent *eventPtr) /* Describes what just happened. */ { TkTextEmbWindowClient *client = clientData; TkTextSegment *ewPtr = client->parent; TkTextIndex index; Tcl_HashEntry *hPtr; if (eventPtr->type != DestroyNotify) { return; } hPtr = Tcl_FindHashEntry(&ewPtr->body.ew.sharedTextPtr->windowTable, Tk_PathName(client->tkwin)); if (hPtr != NULL) { /* * This may not exist if the entire widget is being deleted. */ Tcl_DeleteHashEntry(hPtr); } ewPtr->body.ew.tkwin = NULL; client->tkwin = NULL; index.tree = ewPtr->body.ew.sharedTextPtr->tree; index.linePtr = ewPtr->body.ew.linePtr; index.byteIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); TkTextChanged(ewPtr->body.ew.sharedTextPtr, NULL, &index, &index); TkTextInvalidateLineMetrics(ewPtr->body.ew.sharedTextPtr, NULL, index.linePtr, 0, TK_TEXT_INVALIDATE_ONLY); } /* *-------------------------------------------------------------- * * EmbWinRequestProc -- * * This function is invoked whenever a window that's associated with a * window canvas item changes its requested dimensions. * * Results: * None. * * Side effects: * The size and location on the screen of the window may change, * depending on the options specified for the window item. * *-------------------------------------------------------------- */ /* ARGSUSED */ static void EmbWinRequestProc( ClientData clientData, /* Pointer to record for window item. */ Tk_Window tkwin) /* Window that changed its desired size. */ { TkTextEmbWindowClient *client = clientData; TkTextSegment *ewPtr = client->parent; TkTextIndex index; index.tree = ewPtr->body.ew.sharedTextPtr->tree; index.linePtr = ewPtr->body.ew.linePtr; index.byteIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); TkTextChanged(ewPtr->body.ew.sharedTextPtr, NULL, &index, &index); TkTextInvalidateLineMetrics(ewPtr->body.ew.sharedTextPtr, NULL, index.linePtr, 0, TK_TEXT_INVALIDATE_ONLY); } /* *-------------------------------------------------------------- * * EmbWinLostSlaveProc -- * * This function is invoked by the Tk geometry manager when a slave * window managed by a text widget is claimed away by another geometry * manager. * * Results: * None. * * Side effects: * The window is disassociated from the window segment, and the portion * of the text is redisplayed. * *-------------------------------------------------------------- */ static void EmbWinLostSlaveProc( ClientData clientData, /* Pointer to record describing window item. */ Tk_Window tkwin) /* Window that was claimed away by another * geometry manager. */ { TkTextEmbWindowClient *client = clientData; TkTextSegment *ewPtr = client->parent; TkTextIndex index; Tcl_HashEntry *hPtr; TkTextEmbWindowClient *loop; Tk_DeleteEventHandler(client->tkwin, StructureNotifyMask, EmbWinStructureProc, client); Tcl_CancelIdleCall(EmbWinDelayedUnmap, client); if (client->textPtr->tkwin != Tk_Parent(tkwin)) { Tk_UnmaintainGeometry(tkwin, client->textPtr->tkwin); } else { Tk_UnmapWindow(tkwin); } hPtr = Tcl_FindHashEntry(&ewPtr->body.ew.sharedTextPtr->windowTable, Tk_PathName(client->tkwin)); Tcl_DeleteHashEntry(hPtr); client->tkwin = NULL; ewPtr->body.ew.tkwin = NULL; /* * Free up the memory allocation for this client. */ loop = ewPtr->body.ew.clients; if (loop == client) { ewPtr->body.ew.clients = client->next; } else { while (loop->next != client) { loop = loop->next; } loop->next = client->next; } ckfree(client); index.tree = ewPtr->body.ew.sharedTextPtr->tree; index.linePtr = ewPtr->body.ew.linePtr; index.byteIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); TkTextChanged(ewPtr->body.ew.sharedTextPtr, NULL, &index, &index); TkTextInvalidateLineMetrics(ewPtr->body.ew.sharedTextPtr, NULL, index.linePtr, 0, TK_TEXT_INVALIDATE_ONLY); } /* *-------------------------------------------------------------- * * TkTextWinFreeClient -- * * Free up the hash entry and client information for a given embedded * window. * * It is assumed the caller will manage the linked list of clients * associated with the relevant TkTextSegment. * * Results: * Nothing. * * Side effects: * The embedded window information for a single client is deleted, if it * exists, and any resources associated with it are released. * *-------------------------------------------------------------- */ void TkTextWinFreeClient( Tcl_HashEntry *hPtr, /* Hash entry corresponding to this client, or * NULL */ TkTextEmbWindowClient *client) /* Client data structure, with the 'tkwin' * field to be cleaned up. */ { if (hPtr != NULL) { /* * (It's possible for there to be no hash table entry for this window, * if an error occurred while creating the window segment but before * the window got added to the table) */ Tcl_DeleteHashEntry(hPtr); } /* * Delete the event handler for the window before destroying the window, * so that EmbWinStructureProc doesn't get called (we'll already do * everything that it would have done, and it will just get confused). */ if (client->tkwin != NULL) { Tk_DeleteEventHandler(client->tkwin, StructureNotifyMask, EmbWinStructureProc, client); Tk_DestroyWindow(client->tkwin); } Tcl_CancelIdleCall(EmbWinDelayedUnmap, client); /* * Free up this client. */ ckfree(client); } /* *-------------------------------------------------------------- * * EmbWinDeleteProc -- * * This function is invoked by the text B-tree code whenever an embedded * window lies in a range of characters being deleted. * * Results: * Returns 0 to indicate that the deletion has been accepted. * * Side effects: * The embedded window is deleted, if it exists, and any resources * associated with it are released. * *-------------------------------------------------------------- */ /* ARGSUSED */ static int EmbWinDeleteProc( TkTextSegment *ewPtr, /* Segment being deleted. */ TkTextLine *linePtr, /* Line containing segment. */ int treeGone) /* Non-zero means the entire tree is being * deleted, so everything must get cleaned * up. */ { TkTextEmbWindowClient *client; client = ewPtr->body.ew.clients; while (client != NULL) { TkTextEmbWindowClient *next = client->next; Tcl_HashEntry *hPtr = NULL; if (client->tkwin != NULL) { hPtr = Tcl_FindHashEntry( &ewPtr->body.ew.sharedTextPtr->windowTable, Tk_PathName(client->tkwin)); } TkTextWinFreeClient(hPtr, client); client = next; } ewPtr->body.ew.clients = NULL; Tk_FreeConfigOptions((char *) &ewPtr->body.ew, ewPtr->body.ew.optionTable, NULL); /* * Free up all memory allocated. */ ckfree(ewPtr); return 0; } /* *-------------------------------------------------------------- * * EmbWinCleanupProc -- * * This function is invoked by the B-tree code whenever a segment * containing an embedded window is moved from one line to another. * * Results: * None. * * Side effects: * The linePtr field of the segment gets updated. * *-------------------------------------------------------------- */ static TkTextSegment * EmbWinCleanupProc( TkTextSegment *ewPtr, /* Mark segment that's being moved. */ TkTextLine *linePtr) /* Line that now contains segment. */ { ewPtr->body.ew.linePtr = linePtr; return ewPtr; } /* *-------------------------------------------------------------- * * EmbWinLayoutProc -- * * This function is the "layoutProc" for embedded window segments. * * Results: * 1 is returned to indicate that the segment should be displayed. The * chunkPtr structure is filled in. * * Side effects: * None, except for filling in chunkPtr. * *-------------------------------------------------------------- */ /*ARGSUSED*/ static int EmbWinLayoutProc( TkText *textPtr, /* Text widget being layed out. */ TkTextIndex *indexPtr, /* Identifies first character in chunk. */ TkTextSegment *ewPtr, /* Segment corresponding to indexPtr. */ int offset, /* Offset within segPtr corresponding to * indexPtr (always 0). */ int maxX, /* Chunk must not occupy pixels at this * position or higher. */ int maxChars, /* Chunk must not include more than this many * characters. */ int noCharsYet, /* Non-zero means no characters have been * assigned to this line yet. */ TkWrapMode wrapMode, /* Wrap mode to use for line: * TEXT_WRAPMODE_CHAR, TEXT_WRAPMODE_NONE, or * TEXT_WRAPMODE_WORD. */ register TkTextDispChunk *chunkPtr) /* Structure to fill in with information about * this chunk. The x field has already been * set by the caller. */ { int width, height; TkTextEmbWindowClient *client; if (offset != 0) { Tcl_Panic("Non-zero offset in EmbWinLayoutProc"); } client = EmbWinGetClient(textPtr, ewPtr); if (client == NULL) { ewPtr->body.ew.tkwin = NULL; } else { ewPtr->body.ew.tkwin = client->tkwin; } if ((ewPtr->body.ew.tkwin == NULL) && (ewPtr->body.ew.create != NULL)) { int code, isNew; Tk_Window ancestor; Tcl_HashEntry *hPtr; const char *before, *string; Tcl_DString buf, *dsPtr = NULL; Tcl_Obj *nameObj; before = ewPtr->body.ew.create; /* * Find everything up to the next % character and append it to the * result string. */ string = before; while (*string != 0) { if ((*string == '%') && (string[1] == '%' || string[1] == 'W')) { if (dsPtr == NULL) { Tcl_DStringInit(&buf); dsPtr = &buf; } if (string != before) { Tcl_DStringAppend(dsPtr, before, (int) (string-before)); before = string; } if (string[1] == '%') { Tcl_DStringAppend(dsPtr, "%", 1); } else { /* * Substitute string as proper Tcl list element. */ int spaceNeeded, cvtFlags, length; const char *str = Tk_PathName(textPtr->tkwin); spaceNeeded = Tcl_ScanElement(str, &cvtFlags); length = Tcl_DStringLength(dsPtr); Tcl_DStringSetLength(dsPtr, length + spaceNeeded); spaceNeeded = Tcl_ConvertElement(str, Tcl_DStringValue(dsPtr) + length, cvtFlags | TCL_DONT_USE_BRACES); Tcl_DStringSetLength(dsPtr, length + spaceNeeded); } before += 2; string++; } string++; } /* * The window doesn't currently exist. Create it by evaluating the * creation script. The script must return the window's path name: * look up that name to get back to the window token. Then register * ourselves as the geometry manager for the window. */ if (dsPtr != NULL) { Tcl_DStringAppend(dsPtr, before, (int) (string-before)); code = Tcl_GlobalEval(textPtr->interp, Tcl_DStringValue(dsPtr)); Tcl_DStringFree(dsPtr); } else { code = Tcl_GlobalEval(textPtr->interp, ewPtr->body.ew.create); } if (code != TCL_OK) { Tcl_BackgroundException(textPtr->interp, code); goto gotWindow; } nameObj = Tcl_GetObjResult(textPtr->interp); Tcl_IncrRefCount(nameObj); Tcl_ResetResult(textPtr->interp); ewPtr->body.ew.tkwin = Tk_NameToWindow(textPtr->interp, Tcl_GetString(nameObj), textPtr->tkwin); Tcl_DecrRefCount(nameObj); if (ewPtr->body.ew.tkwin == NULL) { Tcl_BackgroundError(textPtr->interp); goto gotWindow; } for (ancestor = textPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { if (ancestor == Tk_Parent(ewPtr->body.ew.tkwin)) { break; } if (Tk_TopWinHierarchy(ancestor)) { goto badMaster; } } if (Tk_TopWinHierarchy(ewPtr->body.ew.tkwin) || (textPtr->tkwin == ewPtr->body.ew.tkwin)) { badMaster: Tcl_SetObjResult(textPtr->interp, Tcl_ObjPrintf( "can't embed %s relative to %s", Tk_PathName(ewPtr->body.ew.tkwin), Tk_PathName(textPtr->tkwin))); Tcl_SetErrorCode(textPtr->interp, "TK", "GEOMETRY", "HIERARCHY", NULL); Tcl_BackgroundError(textPtr->interp); ewPtr->body.ew.tkwin = NULL; goto gotWindow; } if (client == NULL) { /* * We just used a '-create' script to make a new window, which we * now need to add to our client list. */ client = ckalloc(sizeof(TkTextEmbWindowClient)); client->next = ewPtr->body.ew.clients; client->textPtr = textPtr; client->tkwin = NULL; client->chunkCount = 0; client->displayed = 0; client->parent = ewPtr; ewPtr->body.ew.clients = client; } client->tkwin = ewPtr->body.ew.tkwin; Tk_ManageGeometry(client->tkwin, &textGeomType, client); Tk_CreateEventHandler(client->tkwin, StructureNotifyMask, EmbWinStructureProc, client); /* * Special trick! Must enter into the hash table *after* calling * Tk_ManageGeometry: if the window was already managed elsewhere in * this text, the Tk_ManageGeometry call will cause the entry to be * removed, which could potentially lose the new entry. */ hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->windowTable, Tk_PathName(client->tkwin), &isNew); Tcl_SetHashValue(hPtr, ewPtr); } /* * See if there's room for this window on this line. */ gotWindow: if (ewPtr->body.ew.tkwin == NULL) { width = 0; height = 0; } else { width = Tk_ReqWidth(ewPtr->body.ew.tkwin) + 2*ewPtr->body.ew.padX; height = Tk_ReqHeight(ewPtr->body.ew.tkwin) + 2*ewPtr->body.ew.padY; } if ((width > (maxX - chunkPtr->x)) && !noCharsYet && (textPtr->wrapMode != TEXT_WRAPMODE_NONE)) { return 0; } /* * Fill in the chunk structure. */ chunkPtr->displayProc = TkTextEmbWinDisplayProc; chunkPtr->undisplayProc = EmbWinUndisplayProc; chunkPtr->measureProc = NULL; chunkPtr->bboxProc = EmbWinBboxProc; chunkPtr->numBytes = 1; if (ewPtr->body.ew.align == ALIGN_BASELINE) { chunkPtr->minAscent = height - ewPtr->body.ew.padY; chunkPtr->minDescent = ewPtr->body.ew.padY; chunkPtr->minHeight = 0; } else { chunkPtr->minAscent = 0; chunkPtr->minDescent = 0; chunkPtr->minHeight = height; } chunkPtr->width = width; chunkPtr->breakIndex = -1; chunkPtr->breakIndex = 1; chunkPtr->clientData = ewPtr; if (client != NULL) { client->chunkCount += 1; } return 1; } /* *-------------------------------------------------------------- * * EmbWinCheckProc -- * * This function is invoked by the B-tree code to perform consistency * checks on embedded windows. * * Results: * None. * * Side effects: * The function panics if it detects anything wrong with the embedded * window. * *-------------------------------------------------------------- */ static void EmbWinCheckProc( TkTextSegment *ewPtr, /* Segment to check. */ TkTextLine *linePtr) /* Line containing segment. */ { if (ewPtr->nextPtr == NULL) { Tcl_Panic("EmbWinCheckProc: embedded window is last segment in line"); } if (ewPtr->size != 1) { Tcl_Panic("EmbWinCheckProc: embedded window has size %d", ewPtr->size); } } /* *-------------------------------------------------------------- * * TkTextEmbWinDisplayProc -- * * This function is invoked by the text displaying code when it is time * to actually draw an embedded window chunk on the screen. * * Results: * None. * * Side effects: * The embedded window gets moved to the correct location and mapped onto * the screen. * *-------------------------------------------------------------- */ void TkTextEmbWinDisplayProc( TkText *textPtr, /* Information about text widget. */ TkTextDispChunk *chunkPtr, /* Chunk that is to be drawn. */ int x, /* X-position in dst at which to draw this * chunk (differs from the x-position in the * chunk because of scrolling). */ int y, /* Top of rectangular bounding box for line: * tells where to draw this chunk in dst * (x-position is in the chunk itself). */ int lineHeight, /* Total height of line. */ int baseline, /* Offset of baseline from y. */ Display *display, /* Display to use for drawing (unused). */ Drawable dst, /* Pixmap or window in which to draw * (unused). */ int screenY) /* Y-coordinate in text window that * corresponds to y. */ { int lineX, windowX, windowY, width, height; Tk_Window tkwin; TkTextSegment *ewPtr = chunkPtr->clientData; TkTextEmbWindowClient *client = EmbWinGetClient(textPtr, ewPtr); if (client == NULL) { return; } tkwin = client->tkwin; if (tkwin == NULL) { return; } if ((x + chunkPtr->width) <= 0) { /* * The window is off-screen; just unmap it. */ if (textPtr->tkwin != Tk_Parent(tkwin)) { Tk_UnmaintainGeometry(tkwin, textPtr->tkwin); } else { Tk_UnmapWindow(tkwin); } return; } /* * Compute the window's location and size in the text widget, taking into * account the align and stretch values for the window. */ EmbWinBboxProc(textPtr, chunkPtr, 0, screenY, lineHeight, baseline, &lineX, &windowY, &width, &height); windowX = lineX - chunkPtr->x + x; if (textPtr->tkwin == Tk_Parent(tkwin)) { if ((windowX != Tk_X(tkwin)) || (windowY != Tk_Y(tkwin)) || (Tk_ReqWidth(tkwin) != Tk_Width(tkwin)) || (height != Tk_Height(tkwin))) { Tk_MoveResizeWindow(tkwin, windowX, windowY, width, height); } Tk_MapWindow(tkwin); } else { Tk_MaintainGeometry(tkwin, textPtr->tkwin, windowX, windowY, width, height); } /* * Mark the window as displayed so that it won't get unmapped. */ client->displayed = 1; } /* *-------------------------------------------------------------- * * EmbWinUndisplayProc -- * * This function is called when the chunk for an embedded window is no * longer going to be displayed. It arranges for the window associated * with the chunk to be unmapped. * * Results: * None. * * Side effects: * The window is scheduled for unmapping. * *-------------------------------------------------------------- */ static void EmbWinUndisplayProc( TkText *textPtr, /* Overall information about text widget. */ TkTextDispChunk *chunkPtr) /* Chunk that is about to be freed. */ { TkTextSegment *ewPtr = chunkPtr->clientData; TkTextEmbWindowClient *client = EmbWinGetClient(textPtr, ewPtr); if (client == NULL) { return; } client->chunkCount--; if (client->chunkCount == 0) { /* * Don't unmap the window immediately, since there's a good chance * that it will immediately be redisplayed, perhaps even in the same * place. Instead, schedule the window to be unmapped later; the call * to EmbWinDelayedUnmap will be cancelled in the likely event that * the unmap becomes unnecessary. */ client->displayed = 0; Tcl_DoWhenIdle(EmbWinDelayedUnmap, client); } } /* *-------------------------------------------------------------- * * EmbWinBboxProc -- * * This function is called to compute the bounding box of the area * occupied by an embedded window. * * Results: * There is no return value. *xPtr and *yPtr are filled in with the * coordinates of the upper left corner of the window, and *widthPtr and * *heightPtr are filled in with the dimensions of the window in pixels. * Note: not all of the returned bbox is necessarily visible on the * screen (the rightmost part might be off-screen to the right, and the * bottommost part might be off-screen to the bottom). * * Side effects: * None. * *-------------------------------------------------------------- */ static void EmbWinBboxProc( TkText *textPtr, /* Information about text widget. */ TkTextDispChunk *chunkPtr, /* Chunk containing desired char. */ int index, /* Index of desired character within the * chunk. */ int y, /* Topmost pixel in area allocated for this * line. */ int lineHeight, /* Total height of line. */ int baseline, /* Location of line's baseline, in pixels * measured down from y. */ int *xPtr, int *yPtr, /* Gets filled in with coords of character's * upper-left pixel. */ int *widthPtr, /* Gets filled in with width of window, in * pixels. */ int *heightPtr) /* Gets filled in with height of window, in * pixels. */ { Tk_Window tkwin; TkTextSegment *ewPtr = chunkPtr->clientData; TkTextEmbWindowClient *client = EmbWinGetClient(textPtr, ewPtr); if (client == NULL) { tkwin = NULL; } else { tkwin = client->tkwin; } if (tkwin != NULL) { *widthPtr = Tk_ReqWidth(tkwin); *heightPtr = Tk_ReqHeight(tkwin); } else { *widthPtr = 0; *heightPtr = 0; } *xPtr = chunkPtr->x + ewPtr->body.ew.padX; if (ewPtr->body.ew.stretch) { if (ewPtr->body.ew.align == ALIGN_BASELINE) { *heightPtr = baseline - ewPtr->body.ew.padY; } else { *heightPtr = lineHeight - 2*ewPtr->body.ew.padY; } } switch (ewPtr->body.ew.align) { case ALIGN_BOTTOM: *yPtr = y + (lineHeight - *heightPtr - ewPtr->body.ew.padY); break; case ALIGN_CENTER: *yPtr = y + (lineHeight - *heightPtr)/2; break; case ALIGN_TOP: *yPtr = y + ewPtr->body.ew.padY; break; case ALIGN_BASELINE: *yPtr = y + (baseline - *heightPtr); break; } } /* *-------------------------------------------------------------- * * EmbWinDelayedUnmap -- * * This function is an idle handler that does the actual work of * unmapping an embedded window. See the comment in EmbWinUndisplayProc * for details. * * Results: * None. * * Side effects: * The window gets unmapped, unless its chunk reference count has become * non-zero again. * *-------------------------------------------------------------- */ static void EmbWinDelayedUnmap( ClientData clientData) /* Token for the window to be unmapped. */ { TkTextEmbWindowClient *client = clientData; if (!client->displayed && (client->tkwin != NULL)) { if (client->textPtr->tkwin != Tk_Parent(client->tkwin)) { Tk_UnmaintainGeometry(client->tkwin, client->textPtr->tkwin); } else { Tk_UnmapWindow(client->tkwin); } } } /* *-------------------------------------------------------------- * * TkTextWindowIndex -- * * Given the name of an embedded window within a text widget, returns an * index corresponding to the window's position in the text. * * Results: * The return value is 1 if there is an embedded window by the given name * in the text widget, 0 otherwise. If the window exists, *indexPtr is * filled in with its index. * * Side effects: * None. * *-------------------------------------------------------------- */ int TkTextWindowIndex( TkText *textPtr, /* Text widget containing window. */ const char *name, /* Name of window. */ TkTextIndex *indexPtr) /* Index information gets stored here. */ { Tcl_HashEntry *hPtr; TkTextSegment *ewPtr; if (textPtr == NULL) { return 0; } hPtr = Tcl_FindHashEntry(&textPtr->sharedTextPtr->windowTable, name); if (hPtr == NULL) { return 0; } ewPtr = Tcl_GetHashValue(hPtr); indexPtr->tree = textPtr->sharedTextPtr->tree; indexPtr->linePtr = ewPtr->body.ew.linePtr; indexPtr->byteIndex = TkTextSegToOffset(ewPtr, indexPtr->linePtr); return 1; } /* *-------------------------------------------------------------- * * EmbWinGetClient -- * * Given a text widget and a segment which contains an embedded window, * find the text-widget specific information about the embedded window, * if any. * * This function performs a completely linear lookup for a matching data * structure. If we envisage using this code with dozens of peer widgets, * then performance could become an issue and a more sophisticated lookup * mechanism might be desirable. * * Results: * NULL if no widget-specific info exists, otherwise the structure is * returned. * * Side effects: * None. * *-------------------------------------------------------------- */ static TkTextEmbWindowClient * EmbWinGetClient( const TkText *textPtr, /* Information about text widget. */ TkTextSegment *ewPtr) /* Segment containing embedded window. */ { TkTextEmbWindowClient *client = ewPtr->body.ew.clients; while (client != NULL) { if (client->textPtr == textPtr) { return client; } client = client->next; } return NULL; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */