~libqtelegram-team/telegram-app/telegram

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
import QtQuick 2.0
import Ubuntu.Components 1.3
import Ubuntu.Components.Popups 1.3
import Ubuntu.Components 1.3 as UC
import Ubuntu.Content 1.3
import AsemanTools.Controls 1.0 as Controls

import AsemanTools 1.0
import TelegramQML 1.0

import "components"
import "js/colors.js" as Colors
import "ui"

Rectangle {
    id: acc_msg_list

    property alias telegramObject: messages_model.telegram
    property alias currentDialog: messages_model.dialog
    property alias refreshing: messages_model.refreshing

    readonly property bool inSelectionMode: mlist.isInSelectionMode
    readonly property int selectedItemCount: mlist.selectedItems.count
    readonly property int totalItemCount: mlist.listModel.count

    property real topMargin
    property real bottomMargin

    property real maximumMediaHeight: maximumMediaWidth
    // This is neat, but I don't like it resizes the photo live: (height-topMargin-bottomMargin)*0.75
    property real maximumMediaWidth: width*0.75

    property bool isActive: View.active && View.visible
    property bool messageDraging: false

    property string selectedText

    property alias maxId: messages_model.maxId

    property bool isChat: currentDialog ? currentDialog.peer.chatId != 0 : false

    property EncryptedChat enchat: telegramObject.encryptedChat(currentDialog.peer.userId)
    property int enChatUid: enchat.adminId==telegramObject.me? enchat.participantId : enchat.adminId

    property int filterId: -1

    signal forwardRequest(variant messageIds)
    signal focusRequest()
    signal dialogRequest(variant dialogObject)
    signal tagSearchRequest(string tag)
    signal replyToRequest(int msgId)
    signal rejectSecretRequest()

    onIsActiveChanged: {
        if( isActive )
            messages_model.setReaded()
    }

    onCurrentDialogChanged: {
        selected_list.clear()
        add_anim_disabler.restart()
    }

    ListObject {
        id: selected_list
    }

    MessagesModel {
        id: messages_model
        onCountChanged: {
            if(count>1 && isActive)
                messages_model.setReaded()
        }
        onRefreshingChanged: {
            if(focus_msg_timer.msgId) {
                if(refreshing)
                    focus_msg_timer.stop()
                else
                    focus_msg_timer.restart()
            }
        }
        onFocusToNewRequest: {
            if(!hasNewMessage) {
                return;
            }

            focus_msg_timer.msgIndex = unreads>0? unreads-1 : 0
            focus_msg_timer.restart()
        }
    }

    Connections {
        id: sticker_installer
        target: telegramObject
        onDocumentStickerRecieved: {
            if(document != doc)
                return

            PopupUtils.open(Qt.resolvedUrl("InstallStickerDialog.qml"), acc_msg_list, {telegram: telegramObject, stickerSet: set.shortName})
        }
        property Document doc
    }

    //Timer refreshes MessagesModel to check if message(s) have been read or not
    Timer {
        id: refresh_timer
        repeat: true
        interval: 1500
        onTriggered: {
            messages_model.refresh()
        }
        Component.onCompleted: {
            if (!isChat) {
                start()
            }
        }
    }

    Image {
        anchors.fill: parent
        fillMode: Cutegram.background.length==0? Image.Tile : Image.PreserveAspectCrop
        horizontalAlignment: Image.AlignLeft
        verticalAlignment: Image.AlignTop
        sourceSize: Cutegram.background.length==0? Cutegram.imageSize("qrc:/qml/files/telegram_background.png") : Qt.size(width,height)
        source: {
            return "qrc:/qml/files/telegram_background.png"
//            if(backgroundManager.background == "")
//                return Cutegram.background.length==0? "qrc:/qml/files/telegram_background.png" : Devices.localFilesPrePath + Cutegram.background
//            else
//                return backgroundManager.background
        }
        opacity: 0.7
    }

    Rectangle {
        anchors.centerIn: parent
        color: "#ffffff"
        width: welcome_txt.width + 20*Devices.density
        height: welcome_txt.height + 10*Devices.density
        radius: 5*Devices.density
        visible: currentDialog == telegramObject.nullDialog

        Text {
            id: welcome_txt
            anchors.centerIn: parent
            font.pixelSize: Math.floor((Cutegram.font.pointSize+1)*Devices.fontDensity)
            font.family: Cutegram.font.family
            // TRANSLATORS: Label for an empty 'chat area' side of the screen (for larger screens).
            text: i18n.tr("Please select chat")
            color: "#111111"
        }
    }

    Timer {
        id: anim_enabler_timer
        interval: 400
    }

    Timer {
        id: file_delete_timer
        interval: 1000
        onTriggered: Cutegram.deleteFile(filePath)

        property string filePath
    }

    Timer {
        id: add_anim_disabler
        interval: 500
    }

    StickersModel {
        id: stickers_model
        telegram: telegramObject
    }

    MultipleSelectionListView {
        id: mlist
        anchors.fill: parent
        cacheBuffer: units.gu(10) * 20
        clip: true
        focus: false
        highlightFollowsCurrentItem: false
        verticalLayoutDirection: ListView.BottomToTop
        visible: !enchat || enchat.classType != encryptedTypes.typeEncryptedChatDiscarded

        maximumFlickVelocity: 5000
        flickDeceleration: 2000

        header: Item{ width: 4; height: units.dp(4) }
        footer: Item{ width: 4; height: units.dp(4) }

        onAtYBeginningChanged: if( atYBeginning && contentHeight>height &&
                                   currentDialog != telegramObject.nullDialog ) messages_model.loadMore()

        displaced: Transition {
            NumberAnimation { easing.type: Easing.OutCubic; properties: "y"; duration: 300 }
        }
        add: Transition {
            NumberAnimation { easing.type: Easing.OutCubic; properties: "y"; duration: add_anim_disabler.running? 0 : 300 }
        }

        section.property: "unreaded"
        section.criteria: ViewSection.FullString
        section.delegate: Item {
            property int padding: units.dp(3)

            width: mlist.width
            height: unread_texts.text.length != 0 && messages_model.hasNewMessage ? unread_texts.height + 2*padding : 0
            clip: true

            Rectangle {
                id: unread_background
                anchors.fill: parent
                color: Qt.rgba(1, 1, 1, 0.5)
            }

            Label {
                id: unread_texts
                anchors.centerIn: parent
                color: Colors.telegram_blue
                text: section=="false" ? i18n.tr("New messages") : ""
                fontSize: "medium"
                font.weight: Font.Normal
            }
        }

        listModel: messages_model
        listDelegate: MessagesListItem {
            id: message_item
            maximumMediaHeight: acc_msg_list.maximumMediaHeight
            maximumMediaWidth: acc_msg_list.maximumMediaWidth
            message: item
            width: mlist.width
            visibleNames: isChat
            opacity: filterId == user.id || filterId == -1 ? 1 : 0.1

            leadingActions: ListItemActions {
                actions: [
                    Action {
                        iconName: "delete"
                        text: i18n.tr("Delete")
                        onTriggered: telegram.deleteMessages([item.id])
                    }
                ]
            }

            trailingActions: ListItemActions {
                // TODO resend action
                actions: [
                    Action {
                        iconName: "edit-copy"
                        text: i18n.tr("Copy")
                        visible: !message_item.hasMedia
                        onTriggered: Clipboard.push(item.message)
                    },
                    Action {
                        iconName: "mail-reply"
                        text: i18n.tr("Reply")
                        onTriggered: {
                            acc_msg_list.replyToRequest(message.id);
                        }
                    },
                    Action {
                        iconName: "info"
                        text: i18n.tr("Sticker Pack info")
                        visible: message_item.isSticker && telegramObject.documentStickerId(message_item.media.document) !== 0
                        onTriggered: {
                            sticker_installer.doc = message_item.media.document
                            telegramObject.getStickerSet(sticker_installer.doc)
                        }
                    },
                    Action {
                        iconName: "next"
                        text: i18n.tr("Forward")
                        visible: enchat == telegramObject.nullEncryptedChat
                        onTriggered: forwardMessages([message.id])
                    }
                ]
            }

            selected: mlist.isSelected(message_item)
            selectMode: mlist.isInSelectionMode

            onDialogRequest: acc_msg_list.dialogRequest(dialog)
            onTagSearchRequest: acc_msg_list.tagSearchRequest(tag)
            onMessageFocusRequest: focusOnMessage(msgId)

            onPressAndHold: {
                if (!message_item.isSystemMessage) {
                    mlist.clearSelection();
                    mlist.startSelection();
                    if (mlist.isInSelectionMode) {
                        mlist.selectItem(message_item);
                    }
                }
            }

            onSelectedChanged:{
                if (mlist.isInSelectionMode) {
                    if (!selected)
                        mlist.deselectItem(message_item);
                    else
                        mlist.selectItem(message_item);
                }
            }

            onClicked: {
                if (!message_item.isSystemMessage) {
                    if (mlist.isInSelectionMode) {
                        if (selected)
                            selected = false;
                        else
                            selected = true;
                    } else {
                        message_item.click();
                    }
                }
                else
                    message_item.click();
            }

//            onClicked: {
//                console.log("on item clicked");
//                if (mlist.isInSelectionMode) {
//                    if (selected) {
//                        mlist.deselectItem(message_item)
//                    } else {
//                        mlist.selectItem(message_item)
//                    }
//                }

//                message_item.click();
//            }

            onPreviewRequest: {
                console.log("onOpenMedia");
                var properties;
                switch (type) {
                case FileHandler.TypeTargetMediaPhoto:
                    properties = {
                        "user": user,
                        "photoPreviewSource": path
                    };
                    break;
                case FileHandler.TypeTargetMediaVideo:
                    properties = {
                        "user": user,
                        "videoPreviewSource": path
                    };
                    break;
                case FileHandler.TypeTargetMediaDocument:
                    // TODO export document
                    pageStack.addPageToCurrentColumn(dialog_page, picker_page_component, {
                            "url": path,
                            "handler": ContentHandler.Destination,
                            "contentType": ContentType.All
                    });
                    return;
                case FileHandler.TypeTargetMediaAudio:
                    return;
                }
                pageStack.addPageToCurrentColumn(dialog_page, preview_page_component, properties);
            }
        }

        Component.onCompleted: {
            // FIXME: workaround for qtubuntu not returning values depending on the grid unit definition
            // for Flickable.maximumFlickVelocity and Flickable.flickDeceleration
            var scaleFactor = units.gridUnit / 8;
            maximumFlickVelocity = maximumFlickVelocity * scaleFactor;
            flickDeceleration = flickDeceleration * scaleFactor;
        }
    }

    MouseArea {
        anchors.fill: parent
        onPressed: {
            acc_msg_list.focusRequest()
            mouse.accepted = false
        }
    }

    NormalWheelScroll {
        flick: mlist
        animated: Cutegram.smoothScroll
        reverse: true
    }

    PhysicalScrollBar {
        scrollArea: mlist; height: mlist.height-bottomMargin-topMargin; width: 6*Devices.density
        anchors.right: mlist.right; anchors.top: mlist.top;
        anchors.topMargin: topMargin; reverse: true
    }

    Rectangle {
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.bottomMargin: bottomMargin + 8*Devices.density
        anchors.rightMargin: 8*Devices.density
        width: units.gu(7)//64*Devices.density
        height: width
        radius: height / 2//5*Devices.density
        color: "#88000000"
//        normalColor: "#88000000"
//        highlightColor: "#aa000000"
//        iconSource: "files/down.png"
//        cursorShape: Qt.PointingHandCursor
//        iconHeight: 18*Devices.density
        visible: opacity != 0
        opacity: mlist.visibleArea.yPosition+mlist.visibleArea.heightRatio < 0.95? 1 : 0

        MouseArea {
            anchors.fill: parent
            onClicked: mlist.positionViewAtBeginning()
        }

//        onClicked: mlist.positionViewAtBeginning()

        Image {
            anchors.centerIn: parent
            height: units.gu(2)
            fillMode: Image.PreserveAspectFit
            source: "qrc:/qml/files/down.png"
        }

        Behavior on opacity {
            NumberAnimation{ easing.type: Easing.OutCubic; duration: 300 }
        }
    }

    Label {
        id: acc_rjc_txt
        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: units.gu(5)
        fontSize: "large"
        text: i18n.tr("Secret chat requested.")
        visible: enchat && enchat.classType == encryptedTypes.typeEncryptedChatRequested
        onVisibleChanged: secret_chat_indicator.stop()
    }

    Label {
        id: rejected_txt
        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: units.gu(5)
        fontSize: "x-small"
        horizontalAlignment: Text.AlignHCenter
        text: i18n.tr("Secret chat rejected or accepted from another device.\nNote that Android accepts secret chats automatically.")
        visible: enchat && enchat.classType == encryptedTypes.typeEncryptedChatDiscarded
        onVisibleChanged: secret_chat_indicator.stop()
    }

    ActivityIndicator {
        id: secret_chat_indicator
        width: units.gu(3)
        height: width
        anchors.top: acc_rjc_txt.bottom
        anchors.topMargin: units.gu(1)
        anchors.horizontalCenter: parent.horizontalCenter

        function start() { running = true; }
        function stop() { running = false; }
    }

    Column {
        anchors.top: acc_rjc_txt.bottom
        anchors.topMargin: 10*Devices.density
        anchors.left: parent.left
        anchors.right: parent.right
        spacing: 10*Devices.density
        visible: acc_rjc_txt.visible

        TelegramButton {
            anchors {
                right: parent.right
                left: parent.left
                margins: units.gu(2)
            }
            // TRANSLATORS: Button label to accept an incoming secret chat request. (Temporarily secret chats are automatically accepted.)
            text: i18n.tr("Accept")
            onClicked: {
                secret_chat_indicator.start()
                telegramObject.messagesAcceptEncryptedChat(currentDialog.peer.userId)
            }
        }

        TelegramButton {
            anchors {
                right: parent.right
                left: parent.left
                margins: units.gu(2)
            }
            // TRANSLATORS: Button label to reject an incoming secret chat request. (Temporarily secret chats are automatically accepted.)
            text: i18n.tr("Reject")
            backgroundColor: Colors.dark_blue
            onClicked: {
                secret_chat_indicator.start()
                telegramObject.messagesDiscardEncryptedChat(currentDialog.peer.userId)
                rejectSecretRequest()
            }
        }
    }

    // Could use wrapping in a Loader { active: currentDialog.encrypted }
    SecretChatEdges {
        visible: currentDialog.encrypted
    }

    Timer {
        id: focus_msg_timer
        interval: 300
        onTriggered: {
            var idx = msgIndex
            if(msgId)
                idx = messages_model.indexOf(msgId)

            mlist.positionViewAtIndex(idx, ListView.Center)
            msgIndex = 0
            msgId = 0
        }
        property int msgId
        property int msgIndex
    }

    function cancelSelection() {
        mlist.cancelSelection();
    }

    function selectAll() {
        mlist.selectAll();
    }

    function getSelectedMessageText() {
        var message = "", item;
        for (var i = mlist.selectedItems.count - 1; i >= 0; i--) {
            item = mlist.selectedItems.get(i);
            var text = item.model.item.message;
            if (text.trim().length > 0) {
                message += text + "\n";
            }
        }
        return message;
    }

    function getSelectedMessageIds() {
        var messageIds = [], item;
        for (var i = 0; i < mlist.selectedItems.count; i++) {
            item = mlist.selectedItems.get(i);
            messageIds.push(item.model.item.id);
        }
        return messageIds;
    }

    function copySelected() {
        var message = getSelectedMessageText();
        mlist.endSelection();
        Clipboard.push(message);
    }

    function deleteSelected() {
        var messageIds = getSelectedMessageIds();
        mlist.endSelection();
        telegram.deleteMessages(messageIds);
    }

    function forwardSelected() {
        var messageIds = getSelectedMessageIds();
        mlist.endSelection();
        forwardMessages(messageIds);
    }

    function forwardMessages(messageIds) {
        forwardRequest(messageIds);
        pageStack.clear();
    }

    function sendMessage( txt, inReplyTo ) {
        messages_model.sendMessage(txt, inReplyTo)
    }

    function focusOn(msgId) {
        focus_msg_timer.msgId = msgId
    }

    function focusOnMessage(msgId) {
        var idx = messages_model.indexOf(msgId)
        mlist.positionViewAtIndex(idx, ListView.Center)
    }

    function copy() {
        if(selectedText.length == 0)
            return

        Devices.clipboard = selectedText
    }
}