~mzanetti/reminders-app/improve-edit-tags

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
/*
 * Copyright: 2013 - 2014 Canonical, Ltd
 *
 * This file is part of reminders
 *
 * reminders is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * reminders is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import QtQuick 2.3
import QtQuick.Layouts 1.1
import Ubuntu.Components 1.1
import Ubuntu.Components.Popups 1.0
import Ubuntu.Components.ListItems 1.0
import Ubuntu.Connectivity 1.0
import Evernote 0.1
import Ubuntu.OnlineAccounts 0.1
import Ubuntu.OnlineAccounts.Client 0.1
import Ubuntu.PushNotifications 0.1
import "components"
import "ui"

MainView {
    id: root

    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "com.ubuntu.reminders"

    useDeprecatedToolbar: false

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    automaticOrientation: true

    property bool narrowMode: root.width < units.gu(80)
    property var uri: undefined

    onNarrowModeChanged: {
        if (narrowMode) {
            // Clean the toolbar
            notesPage.selectedNote = null;
        }
    }

    Connections {
        target: UriHandler
        onOpened: {
            root.uri = uris[0];
            processUri();
        }
    }

    Connections {
        target: NetworkingStatus
        onStatusChanged: {
            switch (NetworkingStatus.status) {
            case NetworkingStatus.Offline:
                EvernoteConnection.disconnectFromEvernote();
                break;
            case NetworkingStatus.Online:
                // Seems DNS still fails most of the time when we get this signal.
                connectDelayTimer.start();
                break;
            }
        }
    }

    Timer {
        id: connectDelayTimer
        interval: 2000
        onTriggered: EvernoteConnection.connectToEvernote();
    }

    Connections {
        target: EvernoteConnection
        onIsConnectedChanged: {
            if (EvernoteConnection.isConnected && root.uri) {
                processUri();
            }
        }
    }

    backgroundColor: "#dddddd"

    function openAccountPage() {
        var unauthorizedAccounts = allAccounts.count - accounts.count > 0 ? true : false
        var accountPage = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/AccountSelectorPage.qml")), { accounts: accounts, unauthorizedAccounts: unauthorizedAccounts, oaSetup: setup });
        accountPage.accountSelected.connect(function(username, handle) { accountService.startAuthentication(username, handle); pagestack.pop(); root.accountPage = null });
    }

    function displayNote(note, conflictMode) {
        if (conflictMode == undefined) {
            conflictMode = false;
        }

        print("displayNote:", note.guid)
        note.load(true);
        if (root.narrowMode) {
            print("creating noteview");
            if (!conflictMode && note.conflicting) {
                // User wants to open the note even though it is conflicting! Show the Conflict page instead.
                var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/NoteConflictPage.qml")), {note: note});
                page.displayNote.connect(function(note) { root.displayNote(note, true); } );
                page.resolveConflict.connect(function(keepLocal) {
                    var confirmation = PopupUtils.open(Qt.resolvedUrl("components/ResolveConflictConfirmationDialog.qml"), page, {keepLocal: keepLocal, remoteDeleted: note.conflictingNote.deleted, localDeleted: note.deleted});
                    confirmation.accepted.connect(function() {
                        NotesStore.resolveConflict(note.guid, keepLocal ? NotesStore.KeepLocal : NotesStore.KeepRemote);
                        pagestack.pop();
                    });
                })
            } else {
                var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/NotePage.qml")), {readOnly: conflictMode, note: note })
                page.editNote.connect(function(note) {root.switchToEditMode(note)})
                page.openTaggedNotes.connect(function(title, tagGuid) {pagestack.pop();root.openTaggedNotes(title, tagGuid, true)})
            }
        } else {
            var view;
            if (!conflictMode && note.conflicting) {
                // User wants to open the note even though it is conflicting! Show the Conflict page instead.
                notesPage.conflictMode = true;
                view = sideViewLoader.embed(Qt.resolvedUrl("ui/NoteConflictView.qml"))
                view.displayNote.connect(function(note) {root.displayNote(note,true)})
                view.resolveConflict.connect(function(keepLocal) {
                    var confirmation = PopupUtils.open(Qt.resolvedUrl("components/ResolveConflictConfirmationDialog.qml"), page, {keepLocal: keepLocal, remoteDeleted: note.conflictingNote.deleted, localDeleted: note.deleted});
                    confirmation.accepted.connect(function() {
                        NotesStore.resolveConflict(note.guid, keepLocal ? NotesStore.KeepLocal : NotesStore.KeepRemote);
                    });
                })
            } else {
                notesPage.conflictMode = conflictMode;
                view = sideViewLoader.embed(Qt.resolvedUrl("ui/NoteView.qml"))
                view.openTaggedNotes.connect(function(title, tagGuid) {root.openTaggedNotes(title, tagGuid, false)})
            }
            view.note = note;
        }
    }

    function switchToEditMode(note) {
        note.load(true)
        if (root.narrowMode) {
            if (pagestack.depth > 1) {
                pagestack.pop();
            }
            var page = pagestack.push(Qt.resolvedUrl("ui/EditNotePage.qml"), {note: note});
            page.exitEditMode.connect(function() {Qt.inputMethod.hide(); pagestack.pop()});
        } else {
            sideViewLoader.clear();
            var view = sideViewLoader.embed(Qt.resolvedUrl("ui/EditNoteView.qml"))
            print("--- setting note:", note)
            view.note = note;
            view.exitEditMode.connect(function(note) {root.displayNote(note)});
        }
    }

    function openSearch() {
        var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/SearchNotesPage.qml")))
        page.noteSelected.connect(function(note) {root.displayNote(note)})
        page.editNote.connect(function(note) {root.switchToEditMode(note)})
    }

    function doLogin() {
        var accountName = preferences.accountName;
        if (accountName == "@local") {
            accountService.startAuthentication("@local", null);
            return;
        }

        if (accountName) {
            print("Last used account:", accountName);
            var i;
            for (i = 0; i < accounts.count; i++) {
                if (accounts.get(i, "displayName") == accountName) {
                    print("Account", accountName, "still valid in Online Accounts.");
                    accountService.startAuthentication(accounts.get(i, "displayName"), accounts.get(i, "accountServiceHandle"));
                    return;
                }
            }
        }

        switch (accounts.count) {
        case 0:
            PopupUtils.open(noAccountDialog, root);
            print("No account available! Please setup an account in the system settings");
            break;
        case 1:
            print("Connecting to account", accounts.get(0, "displayName"), "as there is only one account available");
            accountService.startAuthentication(accounts.get(0, "displayName"), accounts.get(0, "accountServiceHandle"));
            break;
        default:
            print("There are multiple accounts. Allowing user to select one.");
            openAccountPage();
        }
    }

    function processUri() {
        var commands = root.uri.split("://")[1].split("/");
        if (EvernoteConnection.isConnected && commands && NotesStore) {
            switch(commands[0].toLowerCase()) {
                case "notes": // evernote://notes
                    rootTabs.selectedTabIndex = 0;
                    break;

                case "note": // evernote://note/<noteguid>
                    if (commands[1]) {
                        var note = NotesStore.note(commands[1])
                        if (note) {
                            displayNote(note);
                        } else {
                            console.warn("No such note:", commands[1])
                        }
                    }
                    break;

                case "newnote": // evernote://newnote  or  evernote://newnote/<notebookguid>
                    if (commands[1]) {
                        if (NotesStore.notebook(commands[1])) {
                            NotesStore.createNote(i18n.tr("Untitled"), commands[1]);
                        } else {
                            console.warn("No such notebook.");
                        }
                    } else {
                        NotesStore.createNote(i18n.tr("Untitled"));
                    }
                    break;

                case "editnote": // evernote://editnote/<noteguid>
                    if (commands[1]) {
                        var note = NotesStore.note(commands[1]);
                        displayNote(note);
                        switchToEditMode(note);
                    }
                    break;

                case "notebooks": // evernote://notebooks
                    rootTabs.selectedTabIndex = 1;
                    break;

                case "notebook": // evernote://notebook/<notebookguid>
                    if (commands[1]) {
                        if (NotesStore.notebook(commands[1])) {
                            notebooksPage.openNotebook(commands[1]);
                        } else {
                            console.warn("No such notebook:", commands[1]);
                        }
                    }
                    break;

                case "reminders": // evernote://reminders
                    rootTabs.selectedTabIndex = 2;
                    break;

                case "tags": // evernote://tags
                    rootTabs.selectedTabIndex = 3;
                    break;

                case "tag": // evernote://tag/<tagguid>
                    if (commands[1]) {
                        tagsPage.openTaggedNotes(commands[1]);
                    }
                    break;

                default: console.warn('WARNING: Unmanaged URI: ' + commands);
            }
            commands = undefined;
        }
    }

    function registerPushClient() {
        console.log("Registering push client");
        var req = new XMLHttpRequest();
        req.open("post", "http://162.213.35.108/register", true);
        req.setRequestHeader("content-type", "application/json");
        req.onreadystatechange = function() {//Call a function when the state changes.
            print("push client register response")
            if(req.readyState == 4) {
                if (req.status == 200) {
                    print("PushClient registered")
                } else {
                    print("Error registering PushClient:", req.status, req.responseText, req.statusText);
                }
            }
        }
        req.send(JSON.stringify({
            "userId" : UserStore.username,
            "appId": root.applicationName + "_reminders",
            "token": pushClient.token
        }))
    }

    function openTaggedNotes(title, tagGuid, narrowMode) {
        print("opening note page for tag", tagGuid)
        var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/NotesPage.qml")), {title: title, filterTagGuid: tagGuid, narrowMode: narrowMode});
        page.selectedNoteChanged.connect(function() {
            if (page.selectedNote) {
                root.displayNote(page.selectedNote);
                if (root.narrowMode) {
                    page.selectedNote = null;
                }
            }
        })
        page.editNote.connect(function(note) {
            root.switchToEditMode(note)
        })
    }

    PushClient {
        id: pushClient
        appId: root.applicationName + "_reminders"

        onNotificationsChanged: {
            print("PushClient notification:", notifications)
            var notification = JSON.parse(notifications)["payload"];
            print("user", notification["userId"])
            if (notification["userId"] !== UserStore.username) {
                console.warn("user mismatch:", notification["userId"], "!=", UserStore.username)
                return;
            }

            if (notification["notebookGUID"] !== undefined) {
                NotesStore.refreshNotebooks();
                NotesStore.refreshNotes(notification["notebookGUID"]);
            }
            if (notification["noteGUID"] !== undefined) {
                NotesStore.refreshNoteContent(notification["noteGUID"]);
            }
        }

        onError: {
            console.warn("PushClient Error:", error)
        }
    }

    AccountServiceModel {
        id: accounts
        applicationId: "com.ubuntu.reminders_reminders"
    }

    AccountServiceModel {
        id: allAccounts
        applicationId: "com.ubuntu.reminders_reminders"
        service: useSandbox ? "evernote-sandbox" : "evernote"
        includeDisabled: true
    }

    AccountService {
        id: accountService
        function startAuthentication(username, objectHandle) {
            //Load the cache
            EvernoteConnection.disconnectFromEvernote();
            EvernoteConnection.token = "";
            NotesStore.username = username;
            preferences.accountName = username;
            if (username === "@local" && !preferences.haveLocalUser) {
                NotesStore.createNotebook(i18n.tr("Default notebook"));
                preferences.haveLocalUser = true;
            }

            if (objectHandle === null) {
                return;
            }

            accountService.objectHandle = objectHandle;
            // FIXME: workaround for lp:1351041. We'd normally set the hostname
            // under onAuthenticated, but it seems that now returns empty parameters
            EvernoteConnection.hostname = accountService.authData.parameters["HostName"];
            authenticate(null);
        }

        onAuthenticated: {
            EvernoteConnection.token = reply.AccessToken;
            print("token is:", EvernoteConnection.token)
            print("NetworkingStatus.online:", NetworkingStatus.Online)
            if (NetworkingStatus.Online) {
                EvernoteConnection.connectToEvernote();
            }
        }
        onAuthenticationError: {
            console.log("Authentication failed, code " + error.code)
        }
    }

    Component.onCompleted: {
        if (tablet) {
            width = units.gu(100);
            height = units.gu(75);
        } else if (phone) {
            width = units.gu(40);
            height = units.gu(75);
        }

        pagestack.push(rootTabs);
        doLogin();

        if (uriArgs) {
            root.uri = uriArgs[0];
        }
    }

    Connections {
        target: UserStore
        onUsernameChanged: {
            print("Logged in as user:", UserStore.username);
            // Disabling push notifications as we haven't had a chance to properly test that yet
            //registerPushClient();
        }
    }

    Connections {
        target: NotesStore
        onNoteCreated: {
            var note = NotesStore.note(guid);
            print("note created:", note.guid);
            if (root.narrowMode) {
                var page = pagestack.push(Qt.resolvedUrl("ui/EditNotePage.qml"), {note: note});
                page.exitEditMode.connect(function() {Qt.inputMethod.hide(); pagestack.pop();});
            } else {
                notesPage.selectedNote = note;
                var view = sideViewLoader.embed(Qt.resolvedUrl("ui/EditNoteView.qml"));
                view.note = note;
                view.exitEditMode.connect(function(note) {root.displayNote(note)});
            }
        }
    }

    StatusBar {
        id: statusBar
        anchors { left: parent.left; right: parent.right; top: parent.top; topMargin: units.gu(9) }
        color: root.backgroundColor
        shown: text
        text: EvernoteConnection.error || NotesStore.error
        iconName: "sync-error"

        Timer {
            interval: 5000
            repeat: true
            running: NotesStore.error
            onTriggered: NotesStore.clearError();
        }

        MouseArea {
            anchors.fill: parent
            onClicked: NotesStore.clearError();
        }

    }

    PageStack {
        id: pagestack
        anchors.rightMargin: root.narrowMode ? 0 : root.width - units.gu(40)
        anchors.topMargin: statusBar.height


        Tabs {
            id: rootTabs

            anchors.fill: parent

            Tab {
                title: i18n.tr("Notes")
                objectName: "NotesTab"
                page: NotesPage {
                    id: notesPage
                    readOnly: conflictMode
                    property bool conflictMode: false

                    narrowMode: root.narrowMode

                    onEditNote: {
                        root.switchToEditMode(note)
                    }

                    onSelectedNoteChanged: {
                        if (selectedNote !== null) {
                            root.displayNote(selectedNote);
                            if (root.narrowMode) {
                                selectedNote = null;
                            }
                        } else {
                            sideViewLoader.clear();
                        }
                    }
                    onOpenSearch: root.openSearch();
                }
            }

            Tab {
                title: i18n.tr("Notebooks")
                objectName: "NotebookTab"
                page: NotebooksPage {
                    id: notebooksPage

                    narrowMode: root.narrowMode

                    onOpenNotebook: {
                        var notebook = NotesStore.notebook(notebookGuid)
                        print("have notebook:", notebook, notebook.name)
                        print("opening note page for notebook", notebookGuid)
                        var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/NotesPage.qml")), {title: notebook.name, filterNotebookGuid: notebookGuid, narrowMode: root.narrowMode});
                        page.selectedNoteChanged.connect(function() {
                            if (page.selectedNote) {
                                root.displayNote(page.selectedNote);
                                if (root.narrowMode) {
                                    page.selectedNote = null;
                                }
                            }
                        })
                        page.editNote.connect(function(note) {
                            root.switchToEditMode(note)
                        })
                        page.openSearch.connect(function() {
                            root.openSearch();
                        })
                        NotesStore.refreshNotes();
                    }

                    onOpenSearch: root.openSearch();
                }
            }

            Tab {
                title: i18n.tr("Reminders")
                page: RemindersPage {
                    id: remindersPage

                    onSelectedNoteChanged: {
                        if (selectedNote !== null) {
                            root.displayNote(selectedNote);
                        } else {
                            sideViewLoader.clear();
                        }
                    }

                    onOpenSearch: root.openSearch();
                }
            }

            Tab {
                title: i18n.tr("Tags")
                page: TagsPage {
                    id: tagsPage

                    onOpenTaggedNotes: {
                        var tag = NotesStore.tag(tagGuid);
                        print("opening note page for tag", tagGuid)
                        var page = pagestack.push(Qt.createComponent(Qt.resolvedUrl("ui/NotesPage.qml")), {title: tag.name, filterTagGuid: tagGuid, narrowMode: root.narrowMode});
                        page.selectedNoteChanged.connect(function() {
                            if (page.selectedNote) {
                                root.displayNote(page.selectedNote);
                                if (root.narrowMode) {
                                    page.selectedNote = null;
                                }
                            }
                        })
                        page.editNote.connect(function(note) {
                            root.switchToEditMode(note)
                        })
                        NotesStore.refreshNotes();
                    }

                    onOpenSearch: root.openSearch();
                }
            }
            Tab {
                title: i18n.tr("Accounts")

                page: AccountSelectorPage {
                    accounts: accounts
                    unauthorizedAccounts: true
                    oaSetup: setup
                    onAccountSelected: {
                        accountService.startAuthentication(username, handle)
                        rootTabs.selectedTabIndex = 0;
                    }
                }
            }
        }
    }

    Label {
        anchors.centerIn: parent
        anchors.horizontalCenterOffset: pagestack.width / 2
        visible: !root.narrowMode
        text: i18n.tr("No note selected.\nSelect a note to see it in detail.")
        wrapMode: Text.WordWrap
        horizontalAlignment: Text.AlignHCenter
        fontSize: "large"
        width: parent.width - pagestack.width
    }

    Loader {
        id: sideViewLoader
        anchors { top: parent.top; right: parent.right; bottom: parent.bottom; topMargin: units.gu(10) }
        width: root.width - pagestack.width

        ThinDivider {
            width: sideViewLoader.height
            anchors { right: null; left: parent.left; }
            z: 5

            transform: Rotation {
                angle: 90
            }
        }

        function embed(view, args) {
            source = view;
            return item;
        }

        function clear() {
            source = "";
        }
    }

    Setup {
        id: setup
        applicationId: "com.ubuntu.reminders_reminders"
        providerId: useSandbox ? "com.ubuntu.reminders_evernote-account-plugin-sandbox" : "com.ubuntu.reminders_evernote-account-plugin"
    }

    Component {
        id: noAccountDialog
        Dialog {
            id: noAccount
            objectName: "noAccountDialog"
            title: i18n.tr("Setup Evernote connection?")
            text: i18n.tr("Notes can be stored on this device, or optionally synced with Evernote.") + " "
                          + i18n.tr("In order to synchronize notes with Evernote, an account at Evernote is required.") + " "
                          + i18n.tr("Do you want to setup an account now?")

            Connections {
                target: accounts
                onCountChanged: {
                    if (accounts.count == 1) {
                        PopupUtils.close(noAccount)
                        doLogin();
                    }
                }
            }

            RowLayout {
                Button {
                    objectName: "openAccountButton"
                    text: i18n.tr("No")
                    color: UbuntuColors.red
                    onClicked: {
                        PopupUtils.close(noAccount)
                        accountService.startAuthentication("@local", null);
                    }
                    Layout.fillWidth: true
                }
                Button {
                    objectName: "openAccountButton"
                    text: i18n.tr("Yes")
                    color: UbuntuColors.green
                    onClicked: setup.exec()
                    Layout.fillWidth: true
                }
            }
        }
    }
}