File: notifications_manager.cpp

package info (click to toggle)
kicad 9.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 770,320 kB
  • sloc: cpp: 961,692; ansic: 121,001; xml: 66,428; python: 18,387; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (433 lines) | stat: -rw-r--r-- 13,375 bytes parent folder | download | duplicates (3)
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
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2023 Mark Roszko <mark.roszko@gmail.com>
 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program 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; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <wx/filename.h>
#include <wx/frame.h>
#include <wx/hyperlink.h>
#include <wx/panel.h>
#include <wx/scrolwin.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/stattext.h>
#include <wx/string.h>
#include <wx/time.h>

#include <paths.h>

#include <notifications_manager.h>
#include <widgets/kistatusbar.h>
#include <widgets/ui_common.h>
#include <json_common.h>
#include <kiplatform/ui.h>

#include <core/wx_stl_compat.h>
#include <core/json_serializers.h>
#include <core/kicad_algo.h>

#include <algorithm>
#include <fstream>
#include <map>
#include <optional>
#include <tuple>
#include <vector>


static long long g_last_closed_timer = 0;

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE( NOTIFICATION, title, description, href, key, date )

class NOTIFICATION_PANEL : public wxPanel
{
public:
    NOTIFICATION_PANEL( wxWindow* aParent, NOTIFICATIONS_MANAGER* aManager, NOTIFICATION* aNoti ) :
            wxPanel( aParent, wxID_ANY, wxDefaultPosition, wxSize( -1, 75 ), wxBORDER_SIMPLE ),
            m_hlDetails( nullptr ),
            m_notification( aNoti ),
            m_manager( aManager )
    {
        SetSizeHints( wxDefaultSize, wxDefaultSize );

        wxBoxSizer* mainSizer;
        mainSizer = new wxBoxSizer( wxVERTICAL );

        wxColour fg, bg;
        KIPLATFORM::UI::GetInfoBarColours( fg, bg );
        SetBackgroundColour( bg );
        SetForegroundColour( fg );

        m_stTitle = new wxStaticText( this, wxID_ANY, aNoti->title );
        m_stTitle->Wrap( -1 );
        m_stTitle->SetFont( KIUI::GetControlFont( this ).Bold() );
        mainSizer->Add( m_stTitle, 0, wxALL | wxEXPAND, 1 );

        m_stDescription = new wxStaticText( this, wxID_ANY, aNoti->description );
        m_stDescription->Wrap( -1 );
        mainSizer->Add( m_stDescription, 0, wxALL | wxEXPAND, 1 );

        wxBoxSizer* tailSizer;
        tailSizer = new wxBoxSizer( wxHORIZONTAL );

        if( !aNoti->href.IsEmpty() )
        {
            m_hlDetails = new wxHyperlinkCtrl( this, wxID_ANY, _( "View Details" ), aNoti->href );
            tailSizer->Add( m_hlDetails, 0, wxALL, 2 );
        }

        m_hlDismiss = new wxHyperlinkCtrl( this, wxID_ANY, _( "Dismiss" ), aNoti->href );
        tailSizer->Add( m_hlDismiss, 0, wxALL, 2 );

        mainSizer->Add( tailSizer, 1, wxEXPAND, 5 );

        if( m_hlDetails != nullptr )
            m_hlDetails->Bind( wxEVT_HYPERLINK, &NOTIFICATION_PANEL::onDetails, this );

        m_hlDismiss->Bind( wxEVT_HYPERLINK, &NOTIFICATION_PANEL::onDismiss, this );

        SetSizer( mainSizer );
        Layout();
    }

private:
    void onDetails( wxHyperlinkEvent& aEvent )
    {
        wxString url = aEvent.GetURL();

        if( url.StartsWith( wxS( "kicad://" ) ) )
        {
            url.Replace( wxS( "kicad://" ), wxS( "" ) );

            if( url == wxS( "pcm" ) )
            {
                // TODO
            }
        }
        else
        {
            wxLaunchDefaultBrowser( aEvent.GetURL(), wxBROWSER_NEW_WINDOW );
        }
    }

    void onDismiss( wxHyperlinkEvent& aEvent )
    {
        CallAfter(
                [this]()
                {
                    // This will cause this panel to get deleted
                    m_manager->Remove( m_notification->key );
                } );
    }

private:
    wxStaticText*          m_stTitle;
    wxStaticText*          m_stDescription;
    wxHyperlinkCtrl*       m_hlDetails;
    wxHyperlinkCtrl*       m_hlDismiss;
    NOTIFICATION*          m_notification;
    NOTIFICATIONS_MANAGER* m_manager;
};


class NOTIFICATIONS_LIST : public wxFrame
{
public:
    NOTIFICATIONS_LIST( NOTIFICATIONS_MANAGER* aManager, wxWindow* parent, const wxPoint& pos ) :
            wxFrame( parent, wxID_ANY, _( "Notifications" ), pos, wxSize( 300, 150 ),
                     wxFRAME_NO_TASKBAR | wxBORDER_SIMPLE ),
            m_manager( aManager )
    {
        SetSizeHints( wxDefaultSize, wxDefaultSize );

        wxBoxSizer* bSizer1;
        bSizer1 = new wxBoxSizer( wxVERTICAL );

        m_scrolledWindow = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition,
                                                 wxSize( -1, -1 ), wxVSCROLL | wxBORDER_SIMPLE );
        wxColour fg, bg;
        KIPLATFORM::UI::GetInfoBarColours( fg, bg );
        m_scrolledWindow->SetBackgroundColour( bg );
        m_scrolledWindow->SetForegroundColour( fg );

        m_scrolledWindow->SetScrollRate( 5, 5 );
        m_contentSizer = new wxBoxSizer( wxVERTICAL );

        m_scrolledWindow->SetSizer( m_contentSizer );
        m_scrolledWindow->Layout();
        m_contentSizer->Fit( m_scrolledWindow );
        bSizer1->Add( m_scrolledWindow, 1, wxEXPAND | wxALL, 0 );

        m_noNotificationsText = new wxStaticText( m_scrolledWindow, wxID_ANY,
                                                  _( "There are no notifications available" ),
                                                  wxDefaultPosition, wxDefaultSize,
                                                  wxALIGN_CENTER_HORIZONTAL );
        m_noNotificationsText->Wrap( -1 );
        m_contentSizer->Add( m_noNotificationsText, 1, wxALL | wxEXPAND, 5 );

        Bind( wxEVT_KILL_FOCUS, &NOTIFICATIONS_LIST::onFocusLoss, this );
        m_scrolledWindow->Bind( wxEVT_KILL_FOCUS, &NOTIFICATIONS_LIST::onFocusLoss, this );

        SetSizer( bSizer1 );
        Layout();

        SetFocus();
    }


    void onFocusLoss( wxFocusEvent& aEvent )
    {
        if( IsDescendant( aEvent.GetWindow() ) )
        {
            // Child (such as the hyperlink texts) got focus
        }
        else
        {
            Close( true );
            g_last_closed_timer = wxGetLocalTimeMillis().GetValue();
        }

        aEvent.Skip();
    }


    void Add( NOTIFICATION* aNoti )
    {
        m_noNotificationsText->Hide();

        NOTIFICATION_PANEL* panel = new NOTIFICATION_PANEL( m_scrolledWindow, m_manager, aNoti );
        m_contentSizer->Add( panel, 0, wxEXPAND | wxALL, 2 );
        m_scrolledWindow->Layout();
        m_contentSizer->Fit( m_scrolledWindow );

        // call this at this window otherwise the child panels don't resize width properly
        Layout();

        m_panelMap[aNoti] = panel;
    }


    void Remove( NOTIFICATION* aNoti )
    {
        auto it = m_panelMap.find( aNoti );

        if( it != m_panelMap.end() )
        {
            NOTIFICATION_PANEL* panel = m_panelMap[aNoti];
            m_contentSizer->Detach( panel );
            panel->Destroy();

            m_panelMap.erase( it );

            // ensure the window contents get shifted as needed
            m_scrolledWindow->Layout();
            Layout();
        }

        if( m_panelMap.size() == 0 )
        {
            m_noNotificationsText->Show();
        }
    }

private:
    wxScrolledWindow*                                      m_scrolledWindow;

    /// Inner content of the scrolled window, add panels here.
    wxBoxSizer*                                            m_contentSizer;
    std::unordered_map<NOTIFICATION*, NOTIFICATION_PANEL*> m_panelMap;
    NOTIFICATIONS_MANAGER*                                 m_manager;

    /// Text to be displayed when no notifications are present, this gets a Show/Hide call as
    /// needed.
    wxStaticText*                                          m_noNotificationsText;
};


NOTIFICATIONS_MANAGER::NOTIFICATIONS_MANAGER()
{
    m_destFileName = wxFileName( PATHS::GetUserCachePath(), wxT( "notifications.json" ) );
}


void NOTIFICATIONS_MANAGER::Load()
{
    nlohmann::json saved_json;

    std::ifstream saved_json_stream( m_destFileName.GetFullPath().fn_str() );

    try
    {
        saved_json_stream >> saved_json;

        m_notifications = saved_json.get<std::vector<NOTIFICATION>>();
    }
    catch( std::exception& )
    {
        // failed to load the json, which is fine, default to no notifications
    }

    if( wxGetEnv( wxT( "KICAD_TEST_NOTI" ), nullptr ) )
    {
        CreateOrUpdate( wxS( "test" ), wxS( "Test Notification" ), wxS( "Test please ignore" ),
                        wxS( "https://kicad.org" ) );
    }
}


void NOTIFICATIONS_MANAGER::Save()
{
    std::ofstream jsonFileStream( m_destFileName.GetFullPath().fn_str() );

    nlohmann::json saveJson = nlohmann::json( m_notifications );
    jsonFileStream << std::setw( 4 ) << saveJson << std::endl;
    jsonFileStream.flush();
    jsonFileStream.close();
}


void NOTIFICATIONS_MANAGER::CreateOrUpdate( const wxString& aKey,
                                            const wxString& aTitle,
                                            const wxString& aDescription,
                                            const wxString& aHref )
{
    wxCHECK_RET( !aKey.IsEmpty(), wxS( "Notification key must not be empty" ) );

    auto it = std::find_if( m_notifications.begin(), m_notifications.end(),
                            [&]( const NOTIFICATION& noti )
                            {
                                return noti.key == aKey;
                            } );

    if( it != m_notifications.end() )
    {
        NOTIFICATION& noti = *it;

        noti.title = aTitle;
        noti.description = aDescription;
        noti.href = aHref;
    }
    else
    {
        m_notifications.emplace_back( NOTIFICATION{ aTitle, aDescription, aHref,
                                                    aKey, wxEmptyString } );
    }

    if( m_shownDialogs.size() > 0 )
    {
        // update dialogs
        for( NOTIFICATIONS_LIST* list : m_shownDialogs )
            list->Add( &m_notifications.back() );
    }

    for( KISTATUSBAR* statusBar : m_statusBars )
        statusBar->SetNotificationCount( m_notifications.size() );

    Save();
}


void NOTIFICATIONS_MANAGER::Remove( const wxString& aKey )
{
    auto it = std::find_if( m_notifications.begin(), m_notifications.end(),
                            [&]( const NOTIFICATION& noti )
                            {
                                return noti.key == aKey;
                            } );

    if( it == m_notifications.end() )
        return;

    if( m_shownDialogs.size() > 0 )
    {
        // update dialogs

        for( NOTIFICATIONS_LIST* list : m_shownDialogs )
            list->Remove( &(*it) );
    }

    m_notifications.erase( it );

    Save();

    for( KISTATUSBAR* statusBar : m_statusBars )
        statusBar->SetNotificationCount( m_notifications.size() );
}


void NOTIFICATIONS_MANAGER::onListWindowClosed( wxCloseEvent& aEvent )
{
    NOTIFICATIONS_LIST* evtWindow = dynamic_cast<NOTIFICATIONS_LIST*>( aEvent.GetEventObject() );

    alg::delete_if( m_shownDialogs, [&]( NOTIFICATIONS_LIST* dialog )
                                    {
                                        return dialog == evtWindow;
                                    } );

    aEvent.Skip();
}


void NOTIFICATIONS_MANAGER::ShowList( wxWindow* aParent, wxPoint aPos )
{
    // Debounce clicking on the icon with a list already showing.  The button will get focus
    // first, which will cause a focus-loss on the list (thereby closing it), and then we'd open
    // it again without this guard.
    if( wxGetLocalTimeMillis().GetValue() - g_last_closed_timer < 300 )
    {
        g_last_closed_timer = 0;
        return;
    }

    NOTIFICATIONS_LIST* list = new NOTIFICATIONS_LIST( this, aParent, aPos );

    for( NOTIFICATION& job : m_notifications )
        list->Add( &job );

    m_shownDialogs.push_back( list );

    list->Bind( wxEVT_CLOSE_WINDOW, &NOTIFICATIONS_MANAGER::onListWindowClosed, this );

    // correct the position
    wxSize windowSize = list->GetSize();
    list->SetPosition( aPos - windowSize );

    list->Show();
    KIPLATFORM::UI::ForceFocus( list );
}


void NOTIFICATIONS_MANAGER::RegisterStatusBar( KISTATUSBAR* aStatusBar )
{
    m_statusBars.push_back( aStatusBar );

    // notifications should already be loaded so set the initial notification count
    aStatusBar->SetNotificationCount( m_notifications.size() );
}


void NOTIFICATIONS_MANAGER::UnregisterStatusBar( KISTATUSBAR* aStatusBar )
{
    alg::delete_if( m_statusBars, [&]( KISTATUSBAR* statusBar )
                                  {
                                      return statusBar == aStatusBar;
                                  } );
}