AppFrame.cpp 93.7 KB
Newer Older
1 2 3
// Copyright (c) Charles J. Cliffe
// SPDX-License-Identifier: GPL-2.0+

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include "AppFrame.h"

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "wx/numdlg.h"
#include "wx/filedlg.h"

#if !wxUSE_GLCANVAS
#error "OpenGL required: set wxUSE_GLCANVAS to 1 and rebuild the library"
#endif

#include <vector>
#include <algorithm>
#include "AudioThread.h"
#include "CubicSDR.h"
#include "DataTree.h"
#include "ColorTheme.h"
#include "DemodulatorMgr.h"
26
#include "ImagePanel.h"
27 28 29 30

#include <thread>

#include <wx/panel.h>
31
#include <wx/numformatter.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#ifdef __linux__
#include "CubicSDR.xpm"
#endif

wxBEGIN_EVENT_TABLE(AppFrame, wxFrame)
//EVT_MENU(wxID_NEW, AppFrame::OnNewWindow)
EVT_CLOSE(AppFrame::OnClose)
EVT_MENU(wxID_ANY, AppFrame::OnMenu)
EVT_IDLE(AppFrame::OnIdle)
EVT_SPLITTER_DCLICK(wxID_ANY, AppFrame::OnDoubleClickSash)
EVT_SPLITTER_UNSPLIT(wxID_ANY, AppFrame::OnUnSplit)
wxEND_EVENT_TABLE()

#ifdef USE_HAMLIB
#include "RigThread.h"
48 49
#include "PortSelectorDialog.h"
#include "rs232.h"
50 51
#endif

52 53 54 55

/* split a string by 'seperator' into a vector of string */
std::vector<std::string> str_explode(const std::string &seperator, const std::string &in_str);

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#define APPFRAME_MODEMPROPS_MINSIZE 20
#define APPFRAME_MODEMPROPS_MAXSIZE 240

AppFrame::AppFrame() :
        wxFrame(NULL, wxID_ANY, CUBICSDR_TITLE), activeDemodulator(NULL) {

#ifdef __linux__
    SetIcon(wxICON(cubicsdr));
#endif

    wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL);
    demodTray = new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer *demodScopeTray = new wxBoxSizer(wxVERTICAL);
    wxBoxSizer *demodTunerTray = new wxBoxSizer(wxHORIZONTAL);

71
    std::vector<int> attribList = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, 0 };
72 73 74 75 76
    //wxGLAttributes attribList;
    //attribList.PlatformDefaults().RGBA().DoubleBuffer().EndList();
    //attribList.PlatformDefaults().MinRGBA(8, 8, 8, 8).DoubleBuffer().Depth(16).EndList();

    mainSplitter = new wxSplitterWindow( this, wxID_MAIN_SPLITTER, wxDefaultPosition, wxDefaultSize, wxSP_3DSASH | wxSP_LIVE_UPDATE );
77
    mainSplitter->SetSashGravity(10.0f / 37.0f);
78
    mainSplitter->SetMinimumPaneSize(1);
79
    
80 81

    wxPanel *demodPanel = new wxPanel(mainSplitter, wxID_ANY);
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

#ifdef CUBICSDR_HEADER_IMAGE
    wxFileName exePath = wxFileName(wxStandardPaths::Get().GetExecutablePath());
    std::string headerPath = exePath.GetPath().ToStdString();
    headerPath += filePathSeparator + std::string("" CUBICSDR_HEADER_IMAGE);
    wxInitAllImageHandlers();

    ImagePanel *imgPanel = new ImagePanel(demodPanel, headerPath, wxBITMAP_TYPE_ANY);

    std::string headerBgColor = "" CUBICSDR_HEADER_BG;
    if (headerBgColor != "") {
        imgPanel->SetBackgroundColour(wxColour(headerBgColor));
    }

    imgPanel->SetBestFittingSize(wxSize(200, 0));

    demodTray->Add(imgPanel, 0, wxEXPAND | wxALL, 0);
    demodTray->AddSpacer(1);
#endif
101 102
            
    gainCanvas = new GainCanvas(demodPanel, attribList);
103
    gainCanvas->setHelpTip("Tuner gains in dB. Click / use Mousewheel to change.");
104 105 106 107 108
    gainSizerItem = demodTray->Add(gainCanvas, 0, wxEXPAND | wxALL, 0);
    gainSizerItem->Show(false);
    gainSpacerItem = demodTray->AddSpacer(1);
    gainSpacerItem->Show(false);
            
109 110 111 112 113 114 115 116 117 118 119 120 121
    std::vector<std::string> modemList = { "FM", "FMS", "NBFM", "AM", "LSB", "USB", "DSB", "I/Q" };
  
#ifdef CUBICSDR_MODEM_EXCLUDE
    std::string excludeListStr = "" CUBICSDR_MODEM_EXCLUDE;
    std::vector<std::string> excludeList = str_explode(",",excludeListStr);
    for (auto ex_i : excludeList) {
        std::vector<std::string>::iterator found_i = std::find(modemList.begin(),modemList.end(),ex_i);
        if (found_i != modemList.end()) {
            modemList.erase(found_i);
        }
    }
#endif
            
122
    demodModeSelector = new ModeSelectorCanvas(demodPanel, attribList);
123 124 125
    for (auto mt_i : modemList) {
        demodModeSelector->addChoice(mt_i);
    }
126 127 128 129
            
#ifdef CUBICSDR_MODEM_EXCLUDE
    demodModeSelector->setHelpTip("Use buttons to choose modulation type.");
#else
130
    demodModeSelector->setHelpTip("Choose modulation type: Frequency Modulation (Hotkey F), Amplitude Modulation (A) and Lower (L), Upper (U), Double Side-Band and more.");
131 132
#endif
            
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
    demodModeSelector->SetMinSize(wxSize(50,-1));
    demodModeSelector->SetMaxSize(wxSize(50,-1));
    demodTray->Add(demodModeSelector, 2, wxEXPAND | wxALL, 0);
    
#ifdef ENABLE_DIGITAL_LAB
    demodModeSelectorAdv = new ModeSelectorCanvas(demodPanel, attribList);
    demodModeSelectorAdv->addChoice("ASK");
    demodModeSelectorAdv->addChoice("APSK");
    demodModeSelectorAdv->addChoice("BPSK");
    demodModeSelectorAdv->addChoice("DPSK");
    demodModeSelectorAdv->addChoice("PSK");
    demodModeSelectorAdv->addChoice("FSK");
    demodModeSelectorAdv->addChoice("GMSK");
    demodModeSelectorAdv->addChoice("OOK");
    demodModeSelectorAdv->addChoice("ST");
    demodModeSelectorAdv->addChoice("SQAM");
    demodModeSelectorAdv->addChoice("QAM");
    demodModeSelectorAdv->addChoice("QPSK");
    demodModeSelectorAdv->setHelpTip("Choose advanced modulation types.");
    demodModeSelectorAdv->SetMinSize(wxSize(50,-1));
    demodModeSelectorAdv->SetMaxSize(wxSize(50,-1));
    demodTray->Add(demodModeSelectorAdv, 3, wxEXPAND | wxALL, 0);
#endif
            
    modemPropertiesUpdated.store(false);
    modemProps = new ModemProperties(demodPanel, wxID_ANY);
    modemProps->SetMinSize(wxSize(APPFRAME_MODEMPROPS_MAXSIZE,-1));
    modemProps->SetMaxSize(wxSize(APPFRAME_MODEMPROPS_MAXSIZE,-1));

162 163 164 165
    ModemArgInfoList dummyInfo;
    modemProps->initProperties(dummyInfo, nullptr);
    modemProps->updateTheme();

166 167 168 169 170
    demodTray->Add(modemProps, 15, wxEXPAND | wxALL, 0);

#ifndef __APPLE__
    demodTray->AddSpacer(1);
#endif
171 172 173 174 175
      
#if CUBICSDR_ENABLE_VIEW_DEMOD
    wxBoxSizer *demodVisuals = new wxBoxSizer(wxVERTICAL);

    wxGetApp().getDemodSpectrumProcessor()->setup(DEFAULT_DMOD_FFT_SIZE);
176 177 178 179 180 181 182 183
    demodSpectrumCanvas = new SpectrumCanvas(demodPanel, attribList);
    demodSpectrumCanvas->setView(wxGetApp().getConfig()->getCenterFreq(), 300000);
    demodVisuals->Add(demodSpectrumCanvas, 3, wxEXPAND | wxALL, 0);
    wxGetApp().getDemodSpectrumProcessor()->attachOutput(demodSpectrumCanvas->getVisualDataQueue());

    demodVisuals->AddSpacer(1);

    demodWaterfallCanvas = new WaterfallCanvas(demodPanel, attribList);
184
    demodWaterfallCanvas->setup(DEFAULT_DMOD_FFT_SIZE, DEFAULT_DEMOD_WATERFALL_LINES_NB);
185 186 187 188 189 190 191
    demodWaterfallCanvas->setView(wxGetApp().getConfig()->getCenterFreq(), 300000);
    demodWaterfallCanvas->attachSpectrumCanvas(demodSpectrumCanvas);
    demodWaterfallCanvas->setMinBandwidth(8000);
    demodSpectrumCanvas->attachWaterfallCanvas(demodWaterfallCanvas);
    demodVisuals->Add(demodWaterfallCanvas, 6, wxEXPAND | wxALL, 0);
    wxGetApp().getDemodSpectrumProcessor()->attachOutput(demodWaterfallCanvas->getVisualDataQueue());
    demodWaterfallCanvas->getVisualDataQueue()->set_max_num_items(3);
192 193
    demodWaterfallCanvas->setLinesPerSecond((int)(DEFAULT_DEMOD_WATERFALL_LINES_NB / DEMOD_WATERFALL_DURATION_IN_SECONDS));
    
194 195 196 197 198
    demodVisuals->SetMinSize(wxSize(128,-1));

    demodTray->Add(demodVisuals, 30, wxEXPAND | wxALL, 0);

    demodTray->AddSpacer(1);
199 200 201 202 203
#else
    demodSpectrumCanvas = nullptr;
    demodWaterfallCanvas = nullptr;
#endif
            
204 205 206 207 208 209 210 211 212 213 214 215
    demodSignalMeter = new MeterCanvas(demodPanel, attribList);
    demodSignalMeter->setMax(DEMOD_SIGNAL_MAX);
    demodSignalMeter->setMin(DEMOD_SIGNAL_MIN);
    demodSignalMeter->setLevel(DEMOD_SIGNAL_MIN);
    demodSignalMeter->setInputValue(DEMOD_SIGNAL_MIN);
    demodSignalMeter->setHelpTip("Current Signal Level.  Click / Drag to set Squelch level.  Right-Click to Auto-Zero Squelch");
    demodSignalMeter->SetMinSize(wxSize(12,24));
    demodTray->Add(demodSignalMeter, 1, wxEXPAND | wxALL, 0);


    demodTray->AddSpacer(1);

216
#if CUBICSDR_ENABLE_VIEW_SCOPE
217
    scopeCanvas = new ScopeCanvas(demodPanel, attribList);
218
    scopeCanvas->setHelpTip("Audio Visuals, drag left/right to toggle Scope or Spectrum, 'B' to toggle decibels display.");
219 220
    scopeCanvas->SetMinSize(wxSize(128,-1));
    demodScopeTray->Add(scopeCanvas, 8, wxEXPAND | wxALL, 0);
221
    wxGetApp().getScopeProcessor()->setup(DEFAULT_SCOPE_FFT_SIZE);
222 223 224
    wxGetApp().getScopeProcessor()->attachOutput(scopeCanvas->getInputQueue());

    demodScopeTray->AddSpacer(1);
225 226 227 228
#else
    scopeCanvas = nullptr;
#endif
            
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
    deltaLockButton = new ModeSelectorCanvas(demodPanel, attribList);
    deltaLockButton->addChoice(1, "V");
    deltaLockButton->setPadding(-1,-1);
    deltaLockButton->setHighlightColor(RGBA4f(0.8f,0.8f,0.2f));
    deltaLockButton->setHelpTip("Delta Lock Toggle (V) - Enable to lock modem relative to center frequency.");
    deltaLockButton->setToggleMode(true);
    deltaLockButton->setSelection(-1);
    deltaLockButton->SetMinSize(wxSize(20,28));
    
    demodTunerTray->Add(deltaLockButton, 0, wxEXPAND | wxALL, 0);
    demodTunerTray->AddSpacer(1);
            
    demodTuner = new TuningCanvas(demodPanel, attribList);
    demodTuner->SetMinClientSize(wxSize(200,28));
    demodTunerTray->Add(demodTuner, 1, wxEXPAND | wxALL, 0);
            
    demodScopeTray->Add(demodTunerTray, 1, wxEXPAND | wxALL, 0);

    demodTray->Add(demodScopeTray, 30, wxEXPAND | wxALL, 0);

    demodTray->AddSpacer(1);

    wxBoxSizer *demodGainTray = new wxBoxSizer(wxVERTICAL);
            
    demodGainMeter = new MeterCanvas(demodPanel, attribList);
    demodGainMeter->setMax(2.0);
    demodGainMeter->setHelpTip("Current Demodulator Gain Level.  Click / Drag to set Gain level.");
    demodGainMeter->setShowUserInput(false);
    demodGainMeter->SetMinSize(wxSize(13,24));
    demodGainTray->Add(demodGainMeter, 8, wxEXPAND | wxALL, 0);

    demodGainTray->AddSpacer(1);
    
    soloModeButton = new ModeSelectorCanvas(demodPanel, attribList);
    soloModeButton->addChoice(1, "S");
    soloModeButton->setPadding(-1,-1);
    soloModeButton->setHighlightColor(RGBA4f(0.8f,0.8f,0.2f));
    soloModeButton->setHelpTip("Solo Mode Toggle");
    soloModeButton->setToggleMode(true);
    soloModeButton->setSelection(-1);
    soloModeButton->SetMinSize(wxSize(12,28));
    
    demodGainTray->Add(soloModeButton, 1, wxEXPAND | wxALL, 0);

    demodGainTray->AddSpacer(1);

    demodMuteButton = new ModeSelectorCanvas(demodPanel, attribList);
    demodMuteButton->addChoice(1, "M");
    demodMuteButton->setPadding(-1,-1);
    demodMuteButton->setHighlightColor(RGBA4f(0.8f,0.2f,0.2f));
    demodMuteButton->setHelpTip("Demodulator Mute Toggle");
    demodMuteButton->setToggleMode(true);
	demodMuteButton->setSelection(-1);
    demodMuteButton->SetMinSize(wxSize(12,28));
            
    demodGainTray->Add(demodMuteButton, 1, wxEXPAND | wxALL, 0);

    demodTray->Add(demodGainTray, 1, wxEXPAND | wxALL, 0);
    
    demodPanel->SetSizer(demodTray);

//    vbox->Add(demodTray, 12, wxEXPAND | wxALL, 0);
//    vbox->AddSpacer(1);
292 293 294 295 296
    bookmarkSplitter = new wxSplitterWindow(mainSplitter, wxID_BM_SPLITTER, wxDefaultPosition, wxDefaultSize, wxSP_3DSASH | wxSP_LIVE_UPDATE );
    bookmarkSplitter->SetMinimumPaneSize(1);
    bookmarkSplitter->SetSashGravity(1.0f / 20.0f);
        
    mainVisSplitter = new wxSplitterWindow( bookmarkSplitter, wxID_VIS_SPLITTER, wxDefaultPosition, wxDefaultSize, wxSP_3DSASH | wxSP_LIVE_UPDATE );
297
    mainVisSplitter->SetMinimumPaneSize(1);
298
    mainVisSplitter->SetSashGravity(6.0f / 25.0f);
299 300 301 302 303 304
        
//    mainVisSplitter->Connect( wxEVT_IDLE, wxIdleEventHandler( AppFrame::mainVisSplitterIdle ), NULL, this );

    wxPanel *spectrumPanel = new wxPanel(mainVisSplitter, wxID_ANY);
    wxBoxSizer *spectrumSizer = new wxBoxSizer(wxHORIZONTAL);

305
    wxGetApp().getSpectrumProcessor()->setup(DEFAULT_FFT_SIZE);
306 307
    spectrumCanvas = new SpectrumCanvas(spectrumPanel, attribList);
    spectrumCanvas->setShowDb(true);
308
    spectrumCanvas->setUseDBOfs(true);
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
    spectrumCanvas->setScaleFactorEnabled(true);
    wxGetApp().getSpectrumProcessor()->attachOutput(spectrumCanvas->getVisualDataQueue());
           
    wxBoxSizer *spectrumCtlTray = new wxBoxSizer(wxVERTICAL);
            
    peakHoldButton = new ModeSelectorCanvas(spectrumPanel, attribList);
    peakHoldButton->addChoice(1, "P");
    peakHoldButton->setPadding(-1,-1);
    peakHoldButton->setHighlightColor(RGBA4f(0.2f,0.8f,0.2f));
    peakHoldButton->setHelpTip("Peak Hold Toggle");
    peakHoldButton->setToggleMode(true);
    peakHoldButton->setSelection(-1);
    peakHoldButton->SetMinSize(wxSize(12,24));

    spectrumCtlTray->Add(peakHoldButton, 1, wxEXPAND | wxALL, 0);
    spectrumCtlTray->AddSpacer(1);

    spectrumAvgMeter = new MeterCanvas(spectrumPanel, attribList);
    spectrumAvgMeter->setHelpTip("Spectrum averaging speed, click or drag to adjust.");
    spectrumAvgMeter->setMax(1.0);
    spectrumAvgMeter->setLevel(0.65f);
    spectrumAvgMeter->setShowUserInput(false);
    spectrumAvgMeter->SetMinSize(wxSize(12,24));
            
    spectrumCtlTray->Add(spectrumAvgMeter, 8, wxEXPAND | wxALL, 0);

    spectrumSizer->Add(spectrumCanvas, 63, wxEXPAND | wxALL, 0);
    spectrumSizer->AddSpacer(1);
    spectrumSizer->Add(spectrumCtlTray, 1, wxEXPAND | wxALL, 0);
    spectrumPanel->SetSizer(spectrumSizer);
            
//    vbox->Add(spectrumSizer, 5, wxEXPAND | wxALL, 0);

//    vbox->AddSpacer(1);
            
    wxPanel *waterfallPanel = new wxPanel(mainVisSplitter, wxID_ANY);
    wxBoxSizer *wfSizer = new wxBoxSizer(wxHORIZONTAL);
           
    waterfallCanvas = new WaterfallCanvas(waterfallPanel, attribList);
348
    waterfallCanvas->setup(DEFAULT_FFT_SIZE, DEFAULT_MAIN_WATERFALL_LINES_NB);
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

    waterfallDataThread = new FFTVisualDataThread();

    waterfallDataThread->setInputQueue("IQDataInput", wxGetApp().getWaterfallVisualQueue());
    waterfallDataThread->setOutputQueue("FFTDataOutput", waterfallCanvas->getVisualDataQueue());
    waterfallDataThread->getProcessor()->setHideDC(true);

    t_FFTData = new std::thread(&FFTVisualDataThread::threadMain, waterfallDataThread);

    waterfallSpeedMeter = new MeterCanvas(waterfallPanel, attribList);
    waterfallSpeedMeter->setHelpTip("Waterfall speed, click or drag to adjust (max 1024 lines per second)");
    waterfallSpeedMeter->setMax(sqrt(1024));
    waterfallSpeedMeter->setLevel(sqrt(DEFAULT_WATERFALL_LPS));
    waterfallSpeedMeter->setShowUserInput(false);
    waterfallSpeedMeter->SetMinSize(wxSize(12,24));

    wfSizer->Add(waterfallCanvas, 63, wxEXPAND | wxALL, 0);
    wfSizer->AddSpacer(1);
    wfSizer->Add(waterfallSpeedMeter, 1, wxEXPAND | wxALL, 0);
    waterfallPanel->SetSizer(wfSizer);
            
//    vbox->Add(wfSizer, 20, wxEXPAND | wxALL, 0);

    mainVisSplitter->SplitHorizontally( spectrumPanel, waterfallPanel, 0 );
373 374
    
    bookmarkView = new BookmarkView(bookmarkSplitter, wxID_ANY, wxDefaultPosition, wxSize(120,-1));
375
            
376 377 378 379 380 381 382
    bookmarkSplitter->SplitVertically( bookmarkView, mainVisSplitter );
    mainSplitter->SplitHorizontally( demodPanel, bookmarkSplitter );
    
    if (!wxGetApp().getConfig()->getBookmarksVisible()) {
        bookmarkSplitter->Unsplit(bookmarkView);
        bookmarkSplitter->Layout();
    }
383
            
384 385
    vbox->Add(mainSplitter, 1, wxEXPAND | wxALL, 0);

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    // TODO: refactor these..
    waterfallCanvas->attachSpectrumCanvas(spectrumCanvas);
    spectrumCanvas->attachWaterfallCanvas(waterfallCanvas);

/* * /
    vbox->AddSpacer(1);
    testCanvas = new UITestCanvas(this, attribList);
    vbox->Add(testCanvas, 20, wxEXPAND | wxALL, 0);
// */
            
    this->SetSizer(vbox);

    //    SetIcon(wxICON(sample));

    // Make a menubar
    menuBar = new wxMenuBar;
    wxMenu *menu = new wxMenu;
403 404
#ifndef __APPLE__ 
#ifdef CUBICSDR_ENABLE_ABOUT_DIALOG
405
    menu->Append(wxID_ABOUT_CUBICSDR, "About " CUBICSDR_INSTALL_NAME);
406
#endif
407
#endif
408 409 410 411 412 413 414 415 416 417 418
    menu->Append(wxID_SDR_DEVICES, "SDR Devices");
    menu->AppendSeparator();
    menu->Append(wxID_SDR_START_STOP, "Stop / Start Device");
    menu->AppendSeparator();
    menu->Append(wxID_OPEN, "&Open Session");
    menu->Append(wxID_SAVE, "&Save Session");
    menu->Append(wxID_SAVEAS, "Save Session &As..");
    menu->AppendSeparator();
    menu->Append(wxID_RESET, "&Reset Session");
            
#ifndef __APPLE__
419 420
    menu->AppendSeparator();
    menu->Append(wxID_CLOSE);
421
#else
422 423 424 425 426 427 428
#ifdef CUBICSDR_ENABLE_ABOUT_DIALOG
    if ( wxApp::s_macAboutMenuItemId != wxID_NONE ) {
        wxString aboutLabel;
        aboutLabel.Printf(_("About %s"), CUBICSDR_INSTALL_NAME);
        menu->Append( wxApp::s_macAboutMenuItemId, aboutLabel);
    }
#endif
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
#endif

    menuBar->Append(menu, wxT("&File"));
            
    settingsMenu = new wxMenu;
          
    menuBar->Append(settingsMenu, wxT("&Settings"));
            
    menu = new wxMenu;

    std::vector<RtAudio::DeviceInfo>::iterator devices_i;
    std::map<int, RtAudio::DeviceInfo>::iterator mdevices_i;
    AudioThread::enumerateDevices(devices);

    int i = 0;

    for (devices_i = devices.begin(); devices_i != devices.end(); devices_i++) {
        if (devices_i->inputChannels) {
            inputDevices[i] = *devices_i;
        }
        if (devices_i->outputChannels) {
            outputDevices[i] = *devices_i;
        }
        i++;
    }
454 455
            
    wxGetApp().getDemodMgr().setOutputDevices(outputDevices);
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
//
//    for (mdevices_i = outputDevices.begin(); mdevices_i != outputDevices.end(); mdevices_i++) {
//        wxMenuItem *itm = menu->AppendRadioItem(wxID_RT_AUDIO_DEVICE + mdevices_i->first, mdevices_i->second.name, wxT("Description?"));
//        itm->SetId(wxID_RT_AUDIO_DEVICE + mdevices_i->first);
//        if (mdevices_i->second.isDefaultOutput) {
//            itm->Check(true);
//        }
//        outputDeviceMenuItems[mdevices_i->first] = itm;
//    }
//
//    menuBar->Append(menu, wxT("Audio &Output"));
            
    sampleRateMenu = new wxMenu;
    menuBar->Append(sampleRateMenu, wxT("Sample &Rate"));

    // Audio Sample Rates
    menu = new wxMenu;

#define NUM_RATES_DEFAULT 4
    unsigned int desired_rates[NUM_RATES_DEFAULT] = { 48000, 44100, 96000, 192000 };

    for (mdevices_i = outputDevices.begin(); mdevices_i != outputDevices.end(); mdevices_i++) {
        unsigned int desired_rate = 0;
        unsigned int desired_rank = NUM_RATES_DEFAULT + 1;

        for (std::vector<unsigned int>::iterator srate = mdevices_i->second.sampleRates.begin(); srate != mdevices_i->second.sampleRates.end();
                srate++) {
            for (unsigned int i = 0; i < NUM_RATES_DEFAULT; i++) {
                if (desired_rates[i] == (*srate)) {
                    if (desired_rank > i) {
                        desired_rank = i;
                        desired_rate = (*srate);
                    }
                }
            }
        }

        if (desired_rank > NUM_RATES_DEFAULT) {
            desired_rate = mdevices_i->second.sampleRates.back();
        }
        AudioThread::deviceSampleRate[mdevices_i->first] = desired_rate;
    }

    for (mdevices_i = outputDevices.begin(); mdevices_i != outputDevices.end(); mdevices_i++) {
        int menu_id = wxID_AUDIO_BANDWIDTH_BASE + wxID_AUDIO_DEVICE_MULTIPLIER * mdevices_i->first;
        wxMenu *subMenu = new wxMenu;
        menu->AppendSubMenu(subMenu, mdevices_i->second.name, wxT("Description?"));

        int j = 0;
        for (std::vector<unsigned int>::iterator srate = mdevices_i->second.sampleRates.begin(); srate != mdevices_i->second.sampleRates.end();
                srate++) {
            std::stringstream srateName;
            srateName << ((float) (*srate) / 1000.0f) << "kHz";
            wxMenuItem *itm = subMenu->AppendRadioItem(menu_id + j, srateName.str(), wxT("Description?"));

            if ((int)(*srate) == AudioThread::deviceSampleRate[mdevices_i->first]) {
                itm->Check(true);
            }
            audioSampleRateMenuItems[menu_id + j] = itm;

            j++;
        }
    }

    menuBar->Append(menu, wxT("Audio &Sample Rate"));

    //Add Display menu
    displayMenu = new wxMenu;
        
    wxMenu *fontMenu = new wxMenu;

    int fontScale = wxGetApp().getConfig()->getFontScale();

    fontMenu->AppendRadioItem(wxID_DISPLAY_BASE, "Normal")->Check(GLFont::GLFONT_SCALE_NORMAL == fontScale);
    fontMenu->AppendRadioItem(wxID_DISPLAY_BASE + 1, "1.5x")->Check(GLFont::GLFONT_SCALE_MEDIUM == fontScale);
    fontMenu->AppendRadioItem(wxID_DISPLAY_BASE + 2, "2.0x")->Check(GLFont::GLFONT_SCALE_LARGE == fontScale);

    displayMenu->AppendSubMenu(fontMenu, "&Text Size");
            
    wxMenu *themeMenu = new wxMenu;
    
    int themeId = wxGetApp().getConfig()->getTheme();
    
    themeMenu->AppendRadioItem(wxID_THEME_DEFAULT, "Default")->Check(themeId==COLOR_THEME_DEFAULT);
    themeMenu->AppendRadioItem(wxID_THEME_RADAR, "RADAR")->Check(themeId==COLOR_THEME_RADAR);
    themeMenu->AppendRadioItem(wxID_THEME_BW, "Black & White")->Check(themeId==COLOR_THEME_BW);
    themeMenu->AppendRadioItem(wxID_THEME_SHARP, "Sharp")->Check(themeId==COLOR_THEME_SHARP);
    themeMenu->AppendRadioItem(wxID_THEME_RAD, "Rad")->Check(themeId==COLOR_THEME_RAD);
    themeMenu->AppendRadioItem(wxID_THEME_TOUCH, "Touch")->Check(themeId==COLOR_THEME_TOUCH);
    themeMenu->AppendRadioItem(wxID_THEME_HD, "HD")->Check(themeId==COLOR_THEME_HD);

    displayMenu->AppendSubMenu(themeMenu, wxT("&Color Scheme"));
548 549 550

    hideBookmarksItem = displayMenu->AppendCheckItem(wxID_DISPLAY_BOOKMARKS, wxT("Hide Bookmarks"));
    hideBookmarksItem->Check(!wxGetApp().getConfig()->getBookmarksVisible());
551 552 553 554 555 556 557 558
            
    GLFont::setScale((GLFont::GLFontScale)fontScale);

#ifdef USE_HAMLIB
            
    rigModel = wxGetApp().getConfig()->getRigModel();
    rigSerialRate = wxGetApp().getConfig()->getRigRate();
    rigPort = wxGetApp().getConfig()->getRigPort();
559
    rigPortDialog = nullptr;
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
    rigMenu = new wxMenu;

    rigEnableMenuItem = rigMenu->AppendCheckItem(wxID_RIG_TOGGLE, wxT("Enable Rig"));

    rigMenu->Append(wxID_RIG_SDR_IF, wxT("SDR-IF"));

    rigControlMenuItem = rigMenu->AppendCheckItem(wxID_RIG_CONTROL, wxT("Control Rig"));
    rigControlMenuItem->Check(wxGetApp().getConfig()->getRigControlMode());
            
    rigFollowMenuItem = rigMenu->AppendCheckItem(wxID_RIG_FOLLOW, wxT("Follow Rig"));
    rigFollowMenuItem->Check(wxGetApp().getConfig()->getRigFollowMode());

    rigCenterLockMenuItem = rigMenu->AppendCheckItem(wxID_RIG_CENTERLOCK, wxT("Floating Center"));
    rigCenterLockMenuItem->Check(wxGetApp().getConfig()->getRigCenterLock());

    rigFollowModemMenuItem = rigMenu->AppendCheckItem(wxID_RIG_FOLLOW_MODEM, wxT("Track Modem"));
    rigFollowModemMenuItem->Check(wxGetApp().getConfig()->getRigFollowModem());

    wxMenu *rigModelMenu = new wxMenu;
    RigList &rl = RigThread::enumerate();
    numRigs = rl.size();
            
    int modelMenuId = wxID_RIG_MODEL_BASE;
    for (RigList::const_iterator ri = rl.begin(); ri != rl.end(); ri++) {
        std::string modelString((*ri)->mfg_name);
        modelString.append(" ");
        modelString.append((*ri)->model_name);
        
        rigModelMenuItems[(*ri)->rig_model] = rigModelMenu->AppendRadioItem(modelMenuId, modelString, wxT("Description?"));
        
        if (rigModel == (*ri)->rig_model) {
            rigModelMenuItems[(*ri)->rig_model]->Check(true);
        }
        
        modelMenuId++;
    }

    rigMenu->AppendSubMenu(rigModelMenu, wxT("Model"));

    wxMenu *rigSerialMenu = new wxMenu;
            
    rigSerialRates.push_back(1200);
    rigSerialRates.push_back(2400);
    rigSerialRates.push_back(4800);
    rigSerialRates.push_back(9600);
    rigSerialRates.push_back(19200);
    rigSerialRates.push_back(38400);
    rigSerialRates.push_back(57600);
    rigSerialRates.push_back(115200);
    rigSerialRates.push_back(128000);
    rigSerialRates.push_back(256000);

    int rateMenuId = wxID_RIG_SERIAL_BASE;
    for (std::vector<int>::const_iterator rate_i = rigSerialRates.begin(); rate_i != rigSerialRates.end(); rate_i++) {
        std::string rateString;
        rateString.append(std::to_string((*rate_i)));
        rateString.append(" baud");
        
        rigSerialMenuItems[(*rate_i)] = rigSerialMenu->AppendRadioItem(rateMenuId, rateString, wxT("Description?"));
        
        if (rigSerialRate == (*rate_i)) {
            rigSerialMenuItems[(*rate_i)]->Check(true);
        }
        
        rateMenuId++;
    }
    
    rigMenu->AppendSubMenu(rigSerialMenu, wxT("Serial Rate"));

    rigPortMenuItem = rigMenu->Append(wxID_RIG_PORT, wxT("Control Port"));

    menuBar->Append(rigMenu, wxT("&Rig Control"));
#endif

    menuBar->Append(displayMenu, wxT("&Display"));

    SetMenuBar(menuBar);

    CreateStatusBar();

    wxRect *win = wxGetApp().getConfig()->getWindow();
    if (win) {
        this->SetPosition(win->GetPosition());
        this->SetClientSize(win->GetSize());
    } else {
        SetClientSize(1280, 600);
        Centre();
    }
    bool max = wxGetApp().getConfig()->getWindowMaximized();

    if (max) {
        this->Maximize();
    }

    long long freqSnap = wxGetApp().getConfig()->getSnap();
    wxGetApp().setFrequencySnap(freqSnap);

    float spectrumAvg = wxGetApp().getConfig()->getSpectrumAvgSpeed();
            
    spectrumAvgMeter->setLevel(spectrumAvg);
    wxGetApp().getSpectrumProcessor()->setFFTAverageRate(spectrumAvg);
            
    int wflps =wxGetApp().getConfig()->getWaterfallLinesPerSec();
            
    waterfallSpeedMeter->setLevel(sqrt(wflps));
    waterfallDataThread->setLinesPerSecond(wflps);
    waterfallCanvas->setLinesPerSecond(wflps);
            
    ThemeMgr::mgr.setTheme(wxGetApp().getConfig()->getTheme());
669
    bookmarkView->updateTheme();
670 671 672 673 674 675

    int mpc =wxGetApp().getConfig()->getModemPropsCollapsed();

    if (mpc) {
        modemProps->setCollapsed(true);
    }
676 677 678 679 680 681 682 683 684 685 686 687 688 689

    int msPos = wxGetApp().getConfig()->getMainSplit();
    if (msPos != -1) {
        mainSplitter->SetSashPosition(msPos);
    }
    int bsPos = wxGetApp().getConfig()->getBookmarkSplit();
    if (bsPos != -1) {
        bookmarkSplitter->SetSashPosition(bsPos);
    }
    int vsPos = wxGetApp().getConfig()->getVisSplit();
    if (vsPos != -1) {
        mainVisSplitter->SetSashPosition(vsPos);
    }
    
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    Show();

#ifdef _WIN32
    SetIcon(wxICON(frame_icon));
#endif

    wxAcceleratorEntry entries[3];
    entries[0].Set(wxACCEL_CTRL, (int) 'O', wxID_OPEN);
    entries[1].Set(wxACCEL_CTRL, (int) 'S', wxID_SAVE);
    entries[2].Set(wxACCEL_CTRL, (int) 'A', wxID_SAVEAS);

    wxAcceleratorTable accel(3, entries);
    SetAcceleratorTable(accel);
    deviceChanged.store(false);
    devInfo = NULL;
    wxGetApp().deviceSelector();
706 707
    saveDisabled = false;
    aboutDlg = nullptr;
708 709 710 711 712 713 714 715 716 717
            
//    static const int attribs[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, 0 };
//    wxLogStatus("Double-buffered display %s supported", wxGLCanvas::IsDisplaySupported(attribs) ? "is" : "not");
//    ShowFullScreen(true);

    //Force refresh of all
    Refresh();
}

AppFrame::~AppFrame() {
718

719 720 721 722 723 724 725 726 727
    waterfallDataThread->terminate();
    t_FFTData->join();
}

void AppFrame::initDeviceParams(SDRDeviceInfo *devInfo) {
    this->devInfo = devInfo;
    deviceChanged.store(true);
}

728 729 730 731
void AppFrame::notifyDeviceChanged() {
    deviceChanged.store(true);
}

732 733
void AppFrame::updateDeviceParams() {
    
734
    if (!deviceChanged.load() || devInfo == nullptr) {
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        return;
    }
    
    int i = 0;
    SoapySDR::Device *soapyDev = devInfo->getSoapyDevice();
    
    // Build settings menu
    wxMenu *newSettingsMenu = new wxMenu;
    showTipMenuItem = newSettingsMenu->AppendCheckItem(wxID_SET_TIPS, "Show Hover Tips");
    showTipMenuItem->Check(wxGetApp().getConfig()->getShowTips());

    lowPerfMode = wxGetApp().getConfig()->getLowPerfMode();
    lowPerfMenuItem = newSettingsMenu->AppendCheckItem(wxID_LOW_PERF, "Reduce CPU Usage");
    if (lowPerfMode) {
        lowPerfMenuItem->Check(true);
    }

    newSettingsMenu->AppendSeparator();

754
    newSettingsMenu->Append(wxID_SET_DB_OFFSET, "Power Level Offset");
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    newSettingsMenu->Append(wxID_SET_FREQ_OFFSET, "Frequency Offset");

    if (devInfo->hasCORR(SOAPY_SDR_RX, 0)) {
        newSettingsMenu->Append(wxID_SET_PPM, "Device PPM");
    }

    if (devInfo->getDriver() != "rtlsdr") {
        iqSwapMenuItem = newSettingsMenu->AppendCheckItem(wxID_SET_IQSWAP, "I/Q Swap");
        iqSwapMenuItem->Check(wxGetApp().getSDRThread()->getIQSwap());
    }

    agcMenuItem = nullptr;
    if (soapyDev->listGains(SOAPY_SDR_RX, 0).size()) {
        agcMenuItem = newSettingsMenu->AppendCheckItem(wxID_AGC_CONTROL, "Automatic Gain");
        agcMenuItem->Check(wxGetApp().getAGCMode());
    } else if (!wxGetApp().getAGCMode()) {
        wxGetApp().setAGCMode(true);
    }
    
    SoapySDR::ArgInfoList::const_iterator args_i;
    settingArgs = soapyDev->getSettingInfo();

    if (settingArgs.size()) {
        newSettingsMenu->AppendSeparator();
    }
    
    for (args_i = settingArgs.begin(); args_i != settingArgs.end(); args_i++) {
        SoapySDR::ArgInfo arg = (*args_i);
        std::string currentVal = soapyDev->readSetting(arg.key);
        if (arg.type == SoapySDR::ArgInfo::BOOL) {
            wxMenuItem *item = newSettingsMenu->AppendCheckItem(wxID_SETTINGS_BASE+i, arg.name, arg.description);
            item->Check(currentVal=="true");
            i++;
        } else if (arg.type == SoapySDR::ArgInfo::INT) {
            newSettingsMenu->Append(wxID_SETTINGS_BASE+i, arg.name, arg.description);
            i++;
        } else if (arg.type == SoapySDR::ArgInfo::FLOAT) {
            newSettingsMenu->Append(wxID_SETTINGS_BASE+i, arg.name, arg.description);
            i++;
        } else if (arg.type == SoapySDR::ArgInfo::STRING) {
            if (arg.options.size()) {
                wxMenu *subMenu = new wxMenu;
                int j = 0;
                for (std::vector<std::string>::iterator str_i = arg.options.begin(); str_i != arg.options.end(); str_i++) {
                    std::string optName = (*str_i);
                    std::string displayName = optName;
                    if (arg.optionNames.size()) {
                        displayName = arg.optionNames[j];
                    }
                    wxMenuItem *item = subMenu->AppendRadioItem(wxID_SETTINGS_BASE+i, displayName);
                    if (currentVal == (*str_i)) {
                        item->Check(true);
                    }
                    j++;
                    i++;
                }
                newSettingsMenu->AppendSubMenu(subMenu, arg.name, arg.description);
            } else {
                newSettingsMenu->Append(wxID_SETTINGS_BASE+i, arg.name, arg.description);
                i++;
            }
        }
    }
    settingsIdMax = wxID_SETTINGS_BASE+i;
    
    menuBar->Replace(1, newSettingsMenu, wxT("&Settings"));
    settingsMenu = newSettingsMenu;
    
823
    // Build/Rebuild the sample rate menu :
824
    sampleRates = devInfo->getSampleRates(SOAPY_SDR_RX, 0);
825
    sampleRateMenuItems.clear();
826 827 828
    
    wxMenu *newSampleRateMenu = new wxMenu;
    int ofs = 0;
829 830
    
    //Current sample rate, try to keep it as is.
831
    long sampleRate = wxGetApp().getSampleRate();
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
   
    long minRate = sampleRates.front();
    long maxRate = sampleRates.back();

    //If it is beyond limits, make device choose a reasonable value
    if (sampleRate < minRate || sampleRate > maxRate) {
        sampleRate = devInfo->getSampleRateNear(SOAPY_SDR_RX, 0, sampleRate);
    }

    //Check if a manual entry was previously set: if so, check its value is still within the limits of the device. If not so, reset it.
    if (manualSampleRate > 0 && 
        (manualSampleRate < minRate || manualSampleRate > maxRate)) {
        manualSampleRate = -1;
    }

847 848
    bool checked = false;
    for (vector<long>::iterator i = sampleRates.begin(); i != sampleRates.end(); i++) {
849

850
        sampleRateMenuItems[wxID_BANDWIDTH_BASE+ofs] = newSampleRateMenu->AppendRadioItem(wxID_BANDWIDTH_BASE+ofs, frequencyToStr(*i));
851
        
852 853 854 855 856 857 858
        if (sampleRate == (*i)) {
            sampleRateMenuItems[wxID_BANDWIDTH_BASE+ofs]->Check(true);
            checked = true;
        }
        ofs++;
    }
    
859 860 861 862 863 864 865 866 867 868 869 870
    //Add a manual sample value radio button, but disabled by default in case the user 
    //never ever uses manual entry.
    if (manualSampleRate <= 0) {
        sampleRateMenuItems[wxID_BANDWIDTH_MANUAL] = newSampleRateMenu->AppendRadioItem(wxID_BANDWIDTH_MANUAL, wxT("Manual :  N/A"));
        sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->Enable(false);
    }
    else {
        sampleRateMenuItems[wxID_BANDWIDTH_MANUAL] = newSampleRateMenu->AppendRadioItem(wxID_BANDWIDTH_MANUAL, wxT("Manual :  ") + frequencyToStr(manualSampleRate));
        sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->Enable(true);
    }

    //We apply the current sample rate after all 
871 872 873
    if (!checked) {
        sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->Check(true);
    }
874 875 876 877 878

    //Append a normal button (NOT a radio-button) for manual entry dialog at the end
    newSampleRateMenu->AppendSeparator();
    sampleRateMenuItems[wxID_BANDWIDTH_MANUAL_DIALOG] = newSampleRateMenu->Append(wxID_BANDWIDTH_MANUAL_DIALOG, wxT("Manual Entry..."));

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
   
    menuBar->Replace(2, newSampleRateMenu, wxT("Sample &Rate"));
    sampleRateMenu = newSampleRateMenu;

    if (!wxGetApp().getAGCMode()) {
        gainSpacerItem->Show(true);
        gainSizerItem->Show(true);
        gainSizerItem->SetMinSize(devInfo->getSoapyDevice()->listGains(SOAPY_SDR_RX,0).size()*50,0);
        demodTray->Layout();
        gainCanvas->updateGainUI();
        gainCanvas->Refresh();
        gainCanvas->Refresh();
    } else {
        gainSpacerItem->Show(false);
        gainSizerItem->Show(false);
        demodTray->Layout();
    }


#if USE_HAMLIB
    if (wxGetApp().getConfig()->getRigEnabled() && !wxGetApp().rigIsActive()) {
        enableRig();
        rigEnableMenuItem->Check(true);
    }
    
    std::string deviceId = devInfo->getDeviceId();
    DeviceConfig *devConfig = wxGetApp().getConfig()->getDevice(deviceId);

    if (wxGetApp().rigIsActive()) {
        rigSDRIF = devConfig->getRigIF(rigModel);
        if (rigSDRIF) {
            wxGetApp().lockFrequency(rigSDRIF);
        } else {
            wxGetApp().unlockFrequency();
        }
    }
#endif
    
    deviceChanged.store(false);
}

#ifdef USE_HAMLIB
void AppFrame::enableRig() {
    wxGetApp().stopRig();
    wxGetApp().initRig(rigModel, rigPort, rigSerialRate);

    if (devInfo != nullptr) {
        std::string deviceId = devInfo->getDeviceId();
        DeviceConfig *devConfig = wxGetApp().getConfig()->getDevice(deviceId);
        rigSDRIF = devConfig->getRigIF(rigModel);
        if (rigSDRIF) {
            wxGetApp().lockFrequency(rigSDRIF);
        } else {
            wxGetApp().unlockFrequency();
        }
    } else {
        wxGetApp().unlockFrequency();
    }
    
    wxGetApp().getConfig()->setRigEnabled(true);
}

void AppFrame::disableRig() {
    wxGetApp().stopRig();
    wxGetApp().unlockFrequency();
    wxGetApp().getConfig()->setRigEnabled(false);
}
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

void AppFrame::setRigControlPort(std::string portName) {
    if (rigPortDialog == nullptr) {
        return;
    }
    if (portName != "") {
        rigPort = portName;

        wxGetApp().stopRig();
        wxGetApp().initRig(rigModel, rigPort, rigSerialRate);
        
        Refresh();
    }
    rigPortDialog->EndModal(0);
    delete rigPortDialog;
    rigPortDialog = nullptr;
}


void AppFrame::dismissRigControlPortDialog() {
    rigPortDialog->EndModal(0);
    delete rigPortDialog;
    rigPortDialog = nullptr;
}

971 972
#endif

973
bool AppFrame::actionOnMenuDisplay(wxCommandEvent& event) {
974

975 976
    //by default, is managed.
    bool bManaged = true;
977

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    if (event.GetId() == wxID_THEME_DEFAULT) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_DEFAULT);
    }
    else if (event.GetId() == wxID_THEME_SHARP) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_SHARP);
    }
    else if (event.GetId() == wxID_THEME_BW) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_BW);
    }
    else if (event.GetId() == wxID_THEME_RAD) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_RAD);
    }
    else if (event.GetId() == wxID_THEME_TOUCH) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_TOUCH);
    }
    else if (event.GetId() == wxID_THEME_HD) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_HD);
    }
    else if (event.GetId() == wxID_THEME_RADAR) {
        ThemeMgr::mgr.setTheme(COLOR_THEME_RADAR);
    }
    //Display : font sizes
    else if (event.GetId() == wxID_DISPLAY_BASE) {
        GLFont::setScale(GLFont::GLFONT_SCALE_NORMAL);
    }
    else if (event.GetId() == wxID_DISPLAY_BASE + 1) {
        GLFont::setScale(GLFont::GLFONT_SCALE_MEDIUM);
    }
    else if (event.GetId() == wxID_DISPLAY_BASE + 2) {
        GLFont::setScale(GLFont::GLFONT_SCALE_LARGE);
    }
    else if (event.GetId() == wxID_DISPLAY_BOOKMARKS) {
        if (hideBookmarksItem->IsChecked()) {
            bookmarkSplitter->Unsplit(bookmarkView);
            bookmarkSplitter->Layout();
        }
        else {
            bookmarkSplitter->SplitVertically(bookmarkView, mainVisSplitter, wxGetApp().getConfig()->getBookmarkSplit());
            bookmarkSplitter->Layout();
        }
    }
    else {
        bManaged = false;
    }
1022

1023 1024 1025 1026 1027 1028
    //update theme choice in children elements:  
    if (event.GetId() >= wxID_THEME_DEFAULT && event.GetId() <= wxID_THEME_RADAR) {
       
        gainCanvas->setThemeColors();
        modemProps->updateTheme();
        bookmarkView->updateTheme();
1029 1030
    }

1031 1032 1033 1034
    //force all windows refresh
    if (bManaged) {
        Refresh();
    }
1035

1036 1037 1038 1039 1040 1041
    return bManaged;
}

bool AppFrame::actionOnMenuReset(wxCommandEvent& event) {

    if (event.GetId() == wxID_RESET) {
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

        wxGetApp().getDemodMgr().terminateAll();
        wxGetApp().setFrequency(100000000);
        wxGetApp().getDemodMgr().setLastDemodulatorType("FM");
        demodModeSelector->setSelection(1);
        wxGetApp().getDemodMgr().setLastMuted(false);
        wxGetApp().getDemodMgr().setLastBandwidth(DEFAULT_DEMOD_BW);
        wxGetApp().getDemodMgr().setLastGain(1.0);
        wxGetApp().getDemodMgr().setLastSquelchLevel(-100);
        waterfallCanvas->setBandwidth(wxGetApp().getSampleRate());
        waterfallCanvas->setCenterFrequency(wxGetApp().getFrequency());
        spectrumCanvas->setBandwidth(wxGetApp().getSampleRate());
        spectrumCanvas->setCenterFrequency(wxGetApp().getFrequency());
        waterfallDataThread->setLinesPerSecond(DEFAULT_WATERFALL_LPS);
        waterfallCanvas->setLinesPerSecond(DEFAULT_WATERFALL_LPS);
        waterfallSpeedMeter->setLevel(sqrt(DEFAULT_WATERFALL_LPS));
        wxGetApp().getSpectrumProcessor()->setFFTAverageRate(0.65f);
        spectrumAvgMeter->setLevel(0.65f);
1060

1061 1062
        SetTitle(CUBICSDR_TITLE);
        currentSessionFile = "";
1063 1064 1065
        bookmarkSplitter->Unsplit(bookmarkView);
        bookmarkSplitter->SplitVertically(bookmarkView, mainVisSplitter, wxGetApp().getConfig()->getBookmarkSplit());
        hideBookmarksItem->Check(false);
1066 1067
        //force all windows refresh
        Refresh();
1068 1069

        return true;
1070
    }
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

    return false;
}

bool AppFrame::actionOnMenuAbout(wxCommandEvent& event) {

#ifdef __APPLE__
    if (event.GetId() == wxApp::s_macAboutMenuItemId) {
#else 
    if (event.GetId() == wxID_ABOUT_CUBICSDR) {
#endif
        if (aboutDlg != nullptr) {
            aboutDlg->Raise();
            aboutDlg->SetFocus();
        }
        else {
            aboutDlg = new AboutDialog(NULL);
            aboutDlg->Connect(wxEVT_CLOSE_WINDOW, wxCommandEventHandler(AppFrame::OnAboutDialogClose), NULL, this);

            aboutDlg->Show();
        }

        return true;
1094 1095
    }

1096 1097 1098 1099 1100
    return false;
}

bool AppFrame::actionOnMenuSettings(wxCommandEvent& event) {

1101
    if (event.GetId() >= wxID_SETTINGS_BASE && event.GetId() < settingsIdMax) {
1102 1103

        int setIdx = event.GetId() - wxID_SETTINGS_BASE;
1104
        int menuIdx = 0;
1105

1106 1107 1108
        for (std::vector<SoapySDR::ArgInfo>::iterator arg_i = settingArgs.begin(); arg_i != settingArgs.end(); arg_i++) {
            SoapySDR::ArgInfo &arg = (*arg_i);

1109 1110
            if (arg.type == SoapySDR::ArgInfo::STRING && arg.options.size() && setIdx >= menuIdx && setIdx < menuIdx + (int)arg.options.size()) {
                int optIdx = setIdx - menuIdx;
1111 1112
                wxGetApp().getSDRThread()->writeSetting(arg.key, arg.options[optIdx]);
                break;
1113 1114
            }
            else if (arg.type == SoapySDR::ArgInfo::STRING && arg.options.size()) {
1115
                menuIdx += arg.options.size();
1116 1117
            }
            else if (menuIdx == setIdx) {
1118
                if (arg.type == SoapySDR::ArgInfo::BOOL) {
1119
                    wxGetApp().getSDRThread()->writeSetting(arg.key, (wxGetApp().getSDRThread()->readSetting(arg.key) == "true") ? "false" : "true");
1120
                    break;
1121 1122
                }
                else if (arg.type == SoapySDR::ArgInfo::STRING) {
1123 1124 1125 1126 1127
                    wxString stringVal = wxGetTextFromUser(arg.description, arg.name, wxGetApp().getSDRThread()->readSetting(arg.key));
                    if (stringVal.ToStdString() != "") {
                        wxGetApp().getSDRThread()->writeSetting(arg.key, stringVal.ToStdString());
                    }
                    break;
1128 1129
                }
                else if (arg.type == SoapySDR::ArgInfo::INT) {
1130 1131 1132
                    int currentVal;
                    try {
                        currentVal = std::stoi(wxGetApp().getSDRThread()->readSetting(arg.key));
1133 1134
                    }
                    catch (std::invalid_argument e) {
1135 1136 1137 1138 1139 1140 1141
                        currentVal = 0;
                    }
                    int intVal = wxGetNumberFromUser(arg.description, arg.units, arg.name, currentVal, arg.range.minimum(), arg.range.maximum(), this);
                    if (intVal != -1) {
                        wxGetApp().getSDRThread()->writeSetting(arg.key, std::to_string(intVal));
                    }
                    break;
1142 1143
                }
                else if (arg.type == SoapySDR::ArgInfo::FLOAT) {
1144 1145 1146
                    wxString floatVal = wxGetTextFromUser(arg.description, arg.name, wxGetApp().getSDRThread()->readSetting(arg.key));
                    try {
                        wxGetApp().getSDRThread()->writeSetting(arg.key, floatVal.ToStdString());
1147 1148
                    }
                    catch (std::invalid_argument e) {
1149 1150 1151
                        // ...
                    }
                    break;
1152 1153
                }
                else {
1154 1155
                    menuIdx++;
                }
1156 1157
            }
            else {
1158 1159
                menuIdx++;
            }
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        } //end for

        return true;
    }

    return false;
}

bool AppFrame::actionOnMenuAGC(wxCommandEvent& event) {

    if (event.GetId() == wxID_AGC_CONTROL) {

        if (wxGetApp().getDevice() == NULL) {
            agcMenuItem->Check(true);
            return true;
        }
        if (!wxGetApp().getAGCMode()) {
            wxGetApp().setAGCMode(true);
            gainSpacerItem->Show(false);
            gainSizerItem->Show(false);
            demodTray->Layout();
        }
        else {
            wxGetApp().setAGCMode(false);
            gainSpacerItem->Show(true);
            gainSizerItem->Show(true);
            gainSizerItem->SetMinSize(wxGetApp().getDevice()->getSoapyDevice()->listGains(SOAPY_SDR_RX, 0).size() * 40, 0);
            demodTray->Layout();
            gainCanvas->updateGainUI();
1189
        }
1190 1191 1192 1193 1194

        //full Refresh, some graphical elements has changed
        Refresh();

        return true;
1195
    }
1196 1197 1198 1199 1200 1201 1202 1203 1204

    return false;
}

bool AppFrame::actionOnMenuSampleRate(wxCommandEvent& event) {

    if (event.GetId() == wxID_BANDWIDTH_MANUAL) {
        wxGetApp().setSampleRate(manualSampleRate);
        return true;
1205
    }
1206 1207 1208 1209 1210 1211
    else if (event.GetId() == wxID_BANDWIDTH_MANUAL_DIALOG) {

        int rateHigh = 0, rateLow = 0;

        SDRDeviceInfo *dev = wxGetApp().getDevice();
        if (dev != nullptr) {
1212 1213

            std::vector<long> sampleRates = dev->getSampleRates(SOAPY_SDR_RX, 0);
1214 1215 1216 1217 1218

            //default
            rateLow = MANUAL_SAMPLE_RATE_MIN;
            rateHigh = MANUAL_SAMPLE_RATE_MAX;

1219
            if (sampleRates.size()) {
1220 1221
                rateLow = sampleRates.front();
                rateHigh = sampleRates.back();
1222 1223 1224
            }

            long bw = wxGetNumberFromUser("\n" + dev->getName() + "\n\n  "
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
                + "min: " + std::to_string(rateLow) + " Hz"
                + ", max: " + std::to_string(rateHigh) + " Hz\n",
                "Sample Rate in Hz",
                "Manual Sample Rate Entry",
                //If a manual sample rate has already been input, recall this one.
                manualSampleRate > 0 ? manualSampleRate : wxGetApp().getSampleRate(),
                rateLow,
                rateHigh,
                this);

1235
            if (bw != -1) {
1236 1237 1238 1239 1240 1241 1242

                manualSampleRate = bw;
                sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->Enable(true);

                sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->SetItemLabel(wxT("Manual :  ") + frequencyToStr(manualSampleRate));
                sampleRateMenuItems[wxID_BANDWIDTH_MANUAL]->Check(true);
                wxGetApp().setSampleRate(manualSampleRate);
1243
            }
1244 1245 1246
        }

        return true;
1247
    }
1248 1249 1250 1251
    else if (event.GetId() >= wxID_BANDWIDTH_BASE && event.GetId() < wxID_BANDWIDTH_BASE + (int)sampleRates.size()) {

        wxGetApp().setSampleRate(sampleRates[event.GetId() - wxID_BANDWIDTH_BASE]);
        return true;
1252
    }
1253 1254 1255 1256 1257 1258

    return false;
}

bool AppFrame::actionOnMenuAudioSampleRate(wxCommandEvent& event) {

1259
    if (event.GetId() >= wxID_AUDIO_BANDWIDTH_BASE) {
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
        int evId = event.GetId();
        std::vector<RtAudio::DeviceInfo>::iterator devices_i;
        std::map<int, RtAudio::DeviceInfo>::iterator mdevices_i;

        int i = 0;
        for (mdevices_i = outputDevices.begin(); mdevices_i != outputDevices.end(); mdevices_i++) {
            int menu_id = wxID_AUDIO_BANDWIDTH_BASE + wxID_AUDIO_DEVICE_MULTIPLIER * mdevices_i->first;

            int j = 0;
            for (std::vector<unsigned int>::iterator srate = mdevices_i->second.sampleRates.begin(); srate != mdevices_i->second.sampleRates.end();
1271
                srate++) {
1272 1273 1274 1275 1276

                if (evId == menu_id + j) {
                    //audioSampleRateMenuItems[menu_id+j];
                    //std::cout << "Would set audio sample rate on device " << mdevices_i->second.name << " (" << mdevices_i->first << ") to " << (*srate) << "Hz" << std::endl;
                    AudioThread::setDeviceSampleRate(mdevices_i->first, *srate);
1277 1278

                    return true;
1279 1280 1281 1282 1283 1284
                }

                j++;
            }
            i++;
        }
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

    }

    return false;
}

bool AppFrame::actionOnMenuLoadSave(wxCommandEvent& event) {

    if (event.GetId() == wxID_SAVE) {

        if (!currentSessionFile.empty()) {
            saveSession(currentSessionFile);
        }
        else {
            wxFileDialog saveFileDialog(this, _("Save XML Session file"), "", "", "XML files (*.xml)|*.xml", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
            if (saveFileDialog.ShowModal() == wxID_CANCEL) {
                return true;
            }
            saveSession(saveFileDialog.GetPath().ToStdString());
        }

        return true;
    }
    else if (event.GetId() == wxID_OPEN) {
        wxFileDialog openFileDialog(this, _("Open XML Session file"), "", "", "XML files (*.xml)|*.xml", wxFD_OPEN | wxFD_FILE_MUST_EXIST);
        if (openFileDialog.ShowModal() == wxID_CANCEL) {
            return true;
        }
        loadSession(openFileDialog.GetPath().ToStdString());

        return true;
    }
    else if (event.GetId() == wxID_SAVEAS) {
        wxFileDialog saveFileDialog(this, _("Save XML Session file"), "", "", "XML files (*.xml)|*.xml", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
        if (saveFileDialog.ShowModal() == wxID_CANCEL) {
            return true;
        }
        saveSession(saveFileDialog.GetPath().ToStdString());

        return true;
1325
    }
1326 1327 1328 1329 1330

    return false;
}

bool AppFrame::actionOnMenuRig(wxCommandEvent& event) {
1331
    
1332 1333
    bool bManaged = false;

1334 1335 1336
#ifdef USE_HAMLIB

    bool resetRig = false;
1337 1338
    if (event.GetId() >= wxID_RIG_MODEL_BASE && event.GetId() < wxID_RIG_MODEL_BASE + numRigs) {
        int rigIdx = event.GetId() - wxID_RIG_MODEL_BASE;
1339 1340 1341 1342 1343 1344 1345 1346
        RigList &rl = RigThread::enumerate();
        rigModel = rl[rigIdx]->rig_model;
        if (devInfo != nullptr) {
            std::string deviceId = devInfo->getDeviceId();
            DeviceConfig *devConfig = wxGetApp().getConfig()->getDevice(deviceId);
            rigSDRIF = devConfig->getRigIF(rigModel);
            if (rigSDRIF) {
                wxGetApp().lockFrequency(rigSDRIF);
1347 1348
            }
            else {
1349 1350
                wxGetApp().unlockFrequency();
            }
1351 1352
        }
        else {
1353 1354 1355
            wxGetApp().unlockFrequency();
        }
        resetRig = true;
1356 1357

        bManaged = true;
1358 1359
    }

1360 1361
    if (event.GetId() >= wxID_RIG_SERIAL_BASE && event.GetId() < wxID_RIG_SERIAL_BASE + rigSerialRates.size()) {
        int serialIdx = event.GetId() - wxID_RIG_SERIAL_BASE;
1362 1363
        rigSerialRate = rigSerialRates[serialIdx];
        resetRig = true;
1364
        bManaged = true;
1365 1366 1367
    }

    if (event.GetId() == wxID_RIG_PORT) {
1368 1369 1370
        if (rigPortDialog == nullptr) {
            rigPortDialog = new PortSelectorDialog(this, wxID_ANY, rigPort);
            rigPortDialog->ShowModal();
1371 1372 1373 1374 1375 1376 1377
        }
    }

    if (event.GetId() == wxID_RIG_TOGGLE) {
        resetRig = false;
        if (!wxGetApp().rigIsActive()) {
            enableRig();
1378 1379
        }
        else {
1380 1381
            disableRig();
        }
1382 1383

        bManaged = true;
1384
    }
1385

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    if (event.GetId() == wxID_RIG_SDR_IF) {
        if (devInfo != nullptr) {
            std::string deviceId = devInfo->getDeviceId();
            DeviceConfig *devConfig = wxGetApp().getConfig()->getDevice(deviceId);
            long long freqRigIF = wxGetNumberFromUser("Rig SDR-IF Frequency", "Frequency (Hz)", "Frequency", devConfig->getRigIF(rigModel), 0, 2000000000);
            if (freqRigIF != -1) {
                rigSDRIF = freqRigIF;
                devConfig->setRigIF(rigModel, rigSDRIF);
            }
            if (rigSDRIF && wxGetApp().rigIsActive()) {
                wxGetApp().lockFrequency(rigSDRIF);
1397 1398
            }
            else {
1399 1400 1401
                wxGetApp().unlockFrequency();
            }
        }
1402
        bManaged = true;
1403
    }
1404

1405 1406 1407 1408 1409 1410
    if (event.GetId() == wxID_RIG_CONTROL) {
        if (wxGetApp().rigIsActive()) {
            RigThread *rt = wxGetApp().getRigThread();
            rt->setControlMode(!rt->getControlMode());
            rigControlMenuItem->Check(rt->getControlMode());
            wxGetApp().getConfig()->setRigControlMode(rt->getControlMode());
1411 1412
        }
        else {
1413 1414
            wxGetApp().getConfig()->setRigControlMode(rigControlMenuItem->IsChecked());
        }
1415
        bManaged = true;
1416 1417 1418 1419 1420 1421 1422 1423
    }

    if (event.GetId() == wxID_RIG_FOLLOW) {
        if (wxGetApp().rigIsActive()) {
            RigThread *rt = wxGetApp().getRigThread();
            rt->setFollowMode(!rt->getFollowMode());
            rigFollowMenuItem->Check(rt->getFollowMode());
            wxGetApp().getConfig()->setRigFollowMode(rt->getFollowMode());
1424 1425
        }
        else {
1426 1427
            wxGetApp().getConfig()->setRigFollowMode(rigFollowMenuItem->IsChecked());
        }
1428 1429

        bManaged = true;
1430
    }
1431

1432 1433 1434 1435 1436 1437
    if (event.GetId() == wxID_RIG_CENTERLOCK) {
        if (wxGetApp().rigIsActive()) {
            RigThread *rt = wxGetApp().getRigThread();
            rt->setCenterLock(!rt->getCenterLock());
            rigCenterLockMenuItem->Check(rt->getCenterLock());
            wxGetApp().getConfig()->setRigCenterLock(rt->getCenterLock());
1438 1439
        }
        else {
1440 1441
            wxGetApp().getConfig()->setRigCenterLock(rigCenterLockMenuItem->IsChecked());
        }
1442 1443

        bManaged = true;
1444 1445 1446 1447 1448 1449 1450 1451
    }

    if (event.GetId() == wxID_RIG_FOLLOW_MODEM) {
        if (wxGetApp().rigIsActive()) {
            RigThread *rt = wxGetApp().getRigThread();
            rt->setFollowModem(!rt->getFollowModem());
            rigFollowModemMenuItem->Check(rt->getFollowModem());
            wxGetApp().getConfig()->setRigFollowModem(rt->getFollowModem());
1452 1453
        }
        else {
1454 1455
            wxGetApp().getConfig()->setRigFollowModem(rigFollowModemMenuItem->IsChecked());
        }
1456 1457

        bManaged = true;
1458 1459 1460 1461 1462 1463 1464 1465
    }

    if (wxGetApp().rigIsActive() && resetRig) {
        wxGetApp().stopRig();
        wxGetApp().initRig(rigModel, rigPort, rigSerialRate);
    }
#endif

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
    return bManaged;
}


void AppFrame::OnMenu(wxCommandEvent& event) {

    if (actionOnMenuAbout(event)) {
        return;
    }
    else if (event.GetId() == wxID_SDR_START_STOP) {
        if (!wxGetApp().getSDRThread()->isTerminated()) {
            wxGetApp().stopDevice(true, 2000);
        } else {
            SDRDeviceInfo *dev = wxGetApp().getDevice();
            if (dev != nullptr) {
                wxGetApp().setDevice(dev, 0);
            }
        }
    } 
    else if (event.GetId() == wxID_LOW_PERF) {
        lowPerfMode = lowPerfMenuItem->IsChecked();
        wxGetApp().getConfig()->setLowPerfMode(lowPerfMode);

    } 
    else if (event.GetId() == wxID_SET_TIPS ) {
        if (wxGetApp().getConfig()->getShowTips()) {
            wxGetApp().getConfig()->setShowTips(false);
        } else {
            wxGetApp().getConfig()->setShowTips(true);
        }
    } 
    else if (event.GetId() == wxID_SET_IQSWAP) {
        wxGetApp().getSDRThread()->setIQSwap(!wxGetApp().getSDRThread()->getIQSwap());
    } 
    else if (event.GetId() == wxID_SET_FREQ_OFFSET) {
        long ofs = wxGetNumberFromUser("Shift the displayed frequency by this amount.\ni.e. -125000000 for -125 MHz", "Frequency (Hz)",
                "Frequency Offset", wxGetApp().getOffset(), -2000000000, 2000000000, this);
        if (ofs != -1) {
            wxGetApp().setOffset(ofs);
        }
    } 
    else if (event.GetId() == wxID_SET_DB_OFFSET) {
        long ofs = wxGetNumberFromUser("Shift the displayed RF power level by this amount.\ni.e. -30 for -30 dB", "Decibels (dB)",
                                       "Power Level Offset", wxGetApp().getConfig()->getDBOffset(), -1000, 1000, this);
        if (ofs != -1) {
            wxGetApp().getConfig()->setDBOffset(ofs);
        }
    } 
    else if (actionOnMenuAGC(event)) {
        return;
    }
    else if (event.GetId() == wxID_SDR_DEVICES) {
        wxGetApp().deviceSelector();
    }
    else if (event.GetId() == wxID_SET_PPM) {
        long ofs = wxGetNumberFromUser("Frequency correction for device in PPM.\ni.e. -51 for -51 PPM\n\nNote: you can adjust PPM interactively\nby holding ALT over the frequency tuning bar.\n", "Parts per million (PPM)",
                "Frequency Correction", wxGetApp().getPPM(), -1000, 1000, this);
            wxGetApp().setPPM(ofs);
    } 
    else if (actionOnMenuLoadSave(event)) {
        return;
    } 
    else if (actionOnMenuReset(event)) {
        return;
    }
    else if (event.GetId() == wxID_CLOSE || event.GetId() == wxID_EXIT) {
        Close(false);
    }
    else if (actionOnMenuSettings(event)) {
        return;
    }
    else if (actionOnMenuSampleRate(event)) {
        return;
    }
    else if (actionOnMenuAudioSampleRate(event)) {
        return;
    }
    else if (actionOnMenuDisplay(event)) {
        return;
    }
    //Optional : Rig 
    else if (actionOnMenuRig(event)) {
        return;
    }
1550 1551 1552 1553
}

void AppFrame::OnClose(wxCloseEvent& event) {
    wxGetApp().closeDeviceSelector();
1554 1555 1556
    if (aboutDlg) {
        aboutDlg->Destroy();
    }
1557

1558 1559 1560 1561
    if (wxGetApp().getDemodSpectrumProcessor()) {
        wxGetApp().getDemodSpectrumProcessor()->removeOutput(demodSpectrumCanvas->getVisualDataQueue());
        wxGetApp().getDemodSpectrumProcessor()->removeOutput(demodWaterfallCanvas->getVisualDataQueue());
    }
1562 1563
    wxGetApp().getSpectrumProcessor()->removeOutput(spectrumCanvas->getVisualDataQueue());

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
    if (saveDisabled) {
        event.Skip();
        return;
    }
    
#ifdef __APPLE__
    if (this->GetPosition().y > 0) {
        wxGetApp().getConfig()->setWindow(this->GetPosition(), this->GetClientSize());
        wxGetApp().getConfig()->setWindowMaximized(this->IsMaximized());
    }
#else
1575 1576
    wxGetApp().getConfig()->setWindow(this->GetPosition(), this->GetClientSize());
    wxGetApp().getConfig()->setWindowMaximized(this->IsMaximized());
1577
#endif
1578 1579 1580 1581 1582 1583 1584 1585
    wxGetApp().getConfig()->setTheme(ThemeMgr::mgr.getTheme());
    wxGetApp().getConfig()->setFontScale(GLFont::getScale());
    wxGetApp().getConfig()->setSnap(wxGetApp().getFrequencySnap());
    wxGetApp().getConfig()->setCenterFreq(wxGetApp().getFrequency());
    wxGetApp().getConfig()->setSpectrumAvgSpeed(wxGetApp().getSpectrumProcessor()->getFFTAverageRate());
    wxGetApp().getConfig()->setWaterfallLinesPerSec(waterfallDataThread->getLinesPerSecond());
    wxGetApp().getConfig()->setManualDevices(SDREnumerator::getManuals());
    wxGetApp().getConfig()->setModemPropsCollapsed(modemProps->isCollapsed());
1586 1587 1588 1589
    wxGetApp().getConfig()->setMainSplit(mainSplitter->GetSashPosition());
    wxGetApp().getConfig()->setVisSplit(mainVisSplitter->GetSashPosition());
    if (!hideBookmarksItem->IsChecked()) wxGetApp().getConfig()->setBookmarkSplit(bookmarkSplitter->GetSashPosition());
    wxGetApp().getConfig()->setBookmarksVisible(!hideBookmarksItem->IsChecked());
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
#ifdef USE_HAMLIB
    wxGetApp().getConfig()->setRigEnabled(rigEnableMenuItem->IsChecked());
    wxGetApp().getConfig()->setRigModel(rigModel);
    wxGetApp().getConfig()->setRigRate(rigSerialRate);
    wxGetApp().getConfig()->setRigPort(rigPort);
    wxGetApp().getConfig()->setRigFollowMode(rigFollowMenuItem->IsChecked());
    wxGetApp().getConfig()->setRigControlMode(rigControlMenuItem->IsChecked());
    wxGetApp().getConfig()->setRigCenterLock(rigCenterLockMenuItem->IsChecked());
    wxGetApp().getConfig()->setRigFollowModem(rigFollowModemMenuItem->IsChecked());
#endif
    wxGetApp().getConfig()->save();
1601
    wxGetApp().getBookmarkMgr().saveToFile("bookmarks.xml");
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    event.Skip();
}

void AppFrame::OnNewWindow(wxCommandEvent& WXUNUSED(event)) {
    new AppFrame();
}

void AppFrame::OnIdle(wxIdleEvent& event) {

    if (deviceChanged.load()) {
        updateDeviceParams();
    }
    
    DemodulatorInstance *demod = wxGetApp().getDemodMgr().getLastActiveDemodulator();

    if (demod && demod->isModemInitialized()) {
        if (demod->isTracking()) {
            if (spectrumCanvas->getViewState()) {
                long long diff = abs(demod->getFrequency() - spectrumCanvas->getCenterFrequency()) + (demod->getBandwidth()/2) + (demod->getBandwidth()/4);

                if (diff > spectrumCanvas->getBandwidth()/2) {
                    if (demod->getBandwidth() > (int)spectrumCanvas->getBandwidth()) {
                        diff = abs(demod->getFrequency() - spectrumCanvas->getCenterFrequency());
                    } else {
                        diff = diff - spectrumCanvas->getBandwidth()/2;
                    }
                    spectrumCanvas->moveCenterFrequency((demod->getFrequency() < spectrumCanvas->getCenterFrequency())?diff:-diff);
                    demod->setTracking(false);
                }
            } else {
                demod->setTracking(false);
            }
        }
        
        if (demod->getBandwidth() != wxGetApp().getDemodMgr().getLastBandwidth()) {
            wxGetApp().getDemodMgr().setLastBandwidth(demod->getBandwidth());
        }

        if (demod != activeDemodulator) {
            demodSignalMeter->setInputValue(demod->getSquelchLevel());
            demodGainMeter->setInputValue(demod->getGain());
            wxGetApp().getDemodMgr().setLastGain(demod->getGain());
            int outputDevice = demod->getOutputDevice();
1645 1646 1647
            if (scopeCanvas) {
                scopeCanvas->setDeviceName(outputDevices[outputDevice].name);
            }
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
//            outputDeviceMenuItems[outputDevice]->Check(true);
            std::string dType = demod->getDemodulatorType();
            demodModeSelector->setSelection(dType);
#ifdef ENABLE_DIGITAL_LAB
            demodModeSelectorAdv->setSelection(dType);
#endif
            deltaLockButton->setSelection(demod->isDeltaLock()?1:-1);
            demodMuteButton->setSelection(demod->isMuted()?1:-1);
            modemPropertiesUpdated.store(true);
            demodTuner->setHalfBand(dType=="USB" || dType=="LSB");
        }
1659
        if (!demodWaterfallCanvas || demodWaterfallCanvas->getDragState() == WaterfallCanvas::WF_DRAG_NONE) {
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
            long long centerFreq = demod->getFrequency();
            unsigned int demodBw = (unsigned int) ceil((float) demod->getBandwidth() * 2.25);

            if (demod->getDemodulatorType() == "USB") {
                demodBw /= 2;
                centerFreq += demod->getBandwidth() / 4;
            }

            if (demod->getDemodulatorType() == "LSB") {
                demodBw /= 2;
                centerFreq -= demod->getBandwidth() / 4;
            }

            if (demodBw > wxGetApp().getSampleRate() / 2) {
                demodBw = wxGetApp().getSampleRate() / 2;
            }
            if (demodBw < 20000) {
                demodBw = 20000;
            }

1680
            if (demodWaterfallCanvas && centerFreq != demodWaterfallCanvas->getCenterFrequency()) {
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
                demodWaterfallCanvas->setCenterFrequency(centerFreq);
                demodSpectrumCanvas->setCenterFrequency(centerFreq);
            }
            std::string dSelection = demodModeSelector->getSelectionLabel();
#ifdef ENABLE_DIGITAL_LAB
            std::string dSelectionadv = demodModeSelectorAdv->getSelectionLabel();

            // basic demodulators
            if (dSelection != "" && dSelection != demod->getDemodulatorType()) {
                demod->setDemodulatorType(dSelection);
                demodTuner->setHalfBand(dSelection=="USB" || dSelection=="LSB");
                demodModeSelectorAdv->setSelection(-1);
            }
            // advanced demodulators
			else if (dSelectionadv != "" && dSelectionadv != demod->getDemodulatorType()) {
				demod->setDemodulatorType(dSelectionadv);
                demodTuner->setHalfBand(false);
				demodModeSelector->setSelection(-1);
            }
#else
            // basic demodulators
            if (dSelection != "" && dSelection != demod->getDemodulatorType()) {
                demod->setDemodulatorType(dSelection);
                demodTuner->setHalfBand(dSelection=="USB" || dSelection=="LSB");
            }
#endif

            int muteMode = demodMuteButton->getSelection();
            if (demodMuteButton->modeChanged()) {
                if (demod->isMuted() && muteMode == -1) {
                    demod->setMuted(false);
                } else if (!demod->isMuted() && muteMode == 1) {
                    demod->setMuted(true);
                }
                wxGetApp().getDemodMgr().setLastMuted(demod->isMuted());
                demodMuteButton->clearModeChanged();
            } else {
                if (demod->isMuted() && muteMode == -1) {
                    demodMuteButton->setSelection(1);
                    wxGetApp().getDemodMgr().setLastMuted(demod->isMuted());
                    demodMuteButton->Refresh();
                } else if (!demod->isMuted() && muteMode == 1) {
                    demodMuteButton->setSelection(-1);
                    wxGetApp().getDemodMgr().setLastMuted(demod->isMuted());
                    demodMuteButton->Refresh();
                }
            }

            int deltaMode = deltaLockButton->getSelection();
            if (deltaLockButton->modeChanged()) {
                if (demod->isDeltaLock() && deltaMode == -1) {
                    demod->setDeltaLock(false);
                } else if (!demod->isDeltaLock() && deltaMode == 1) {
                    demod->setDeltaLockOfs(demod->getFrequency()-wxGetApp().getFrequency());
                    demod->setDeltaLock(true);
                }
                wxGetApp().getDemodMgr().setLastDeltaLock(demod->isDeltaLock());
                deltaLockButton->clearModeChanged();
            } else {
                if (demod->isDeltaLock() && deltaMode == -1) {
                    deltaLockButton->setSelection(1);
                    wxGetApp().getDemodMgr().setLastDeltaLock(true);
                    deltaLockButton->Refresh();
                } else if (!demod->isDeltaLock() && deltaMode == 1) {
                    deltaLockButton->setSelection(-1);
                    wxGetApp().getDemodMgr().setLastDeltaLock(false);
                    deltaLockButton->Refresh();
                }
            }

            int soloMode = soloModeButton->getSelection();
            if (soloModeButton->modeChanged()) {
                if (soloMode == 1) {
                    wxGetApp().setSoloMode(true);
                } else {
                    wxGetApp().setSoloMode(false);
                }
                soloModeButton->clearModeChanged();
            } else {
                if (wxGetApp().getSoloMode() != (soloMode==1)) {
                    soloModeButton->setSelection(wxGetApp().getSoloMode()?1:-1);
                    soloModeButton->Refresh();
                }
            }
            
1766 1767 1768 1769
            if (demodWaterfallCanvas) {
                demodWaterfallCanvas->setBandwidth(demodBw);
                demodSpectrumCanvas->setBandwidth(demodBw);
            }
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
        }

        demodSignalMeter->setLevel(demod->getSignalLevel());
        demodSignalMeter->setMin(demod->getSignalFloor());
        demodSignalMeter->setMax(demod->getSignalCeil());
        
        demodGainMeter->setLevel(demod->getGain());
        if (demodSignalMeter->inputChanged()) {
            demod->setSquelchLevel(demodSignalMeter->getInputValue());
        }
        if (demodGainMeter->inputChanged()) {
            demod->setGain(demodGainMeter->getInputValue());
            demodGainMeter->setLevel(demodGainMeter->getInputValue());
        }
        activeDemodulator = demod;
    } else if (demod) {
        // Wait state for current demodulator modem to activate..
    } else {
        DemodulatorMgr *mgr = &wxGetApp().getDemodMgr();

        std::string dSelection = demodModeSelector->getSelectionLabel();
#ifdef ENABLE_DIGITAL_LAB
        std::string dSelectionadv = demodModeSelectorAdv->getSelectionLabel();

        // basic demodulators
        if (dSelection != "" && dSelection != mgr->getLastDemodulatorType()) {
            mgr->setLastDemodulatorType(dSelection);
            mgr->setLastBandwidth(Modem::getModemDefaultSampleRate(dSelection));
            demodTuner->setHalfBand(dSelection=="USB" || dSelection=="LSB");
            demodModeSelectorAdv->setSelection(-1);
        }
        // advanced demodulators
        else if(dSelectionadv != "" && dSelectionadv != mgr->getLastDemodulatorType()) {
            mgr->setLastDemodulatorType(dSelectionadv);
            mgr->setLastBandwidth(Modem::getModemDefaultSampleRate(dSelectionadv));
            demodTuner->setHalfBand(false);
            demodModeSelector->setSelection(-1);
        }
#else
        // basic demodulators
        if (dSelection != "" && dSelection != mgr->getLastDemodulatorType()) {
            mgr->setLastDemodulatorType(dSelection);
			mgr->setLastBandwidth(Modem::getModemDefaultSampleRate(dSelection));
            demodTuner->setHalfBand(dSelection=="USB" || dSelection=="LSB");
        }
#endif
        demodGainMeter->setLevel(mgr->getLastGain());
        if (demodSignalMeter->inputChanged()) {
            mgr->setLastSquelchLevel(demodSignalMeter->getInputValue());
        }
        if (demodGainMeter->inputChanged()) {
            mgr->setLastGain(demodGainMeter->getInputValue());
            demodGainMeter->setLevel(demodGainMeter->getInputValue());
        }

1825
        if (demodWaterfallCanvas && wxGetApp().getFrequency() != demodWaterfallCanvas->getCenterFrequency()) {
1826
            demodWaterfallCanvas->setCenterFrequency(wxGetApp().getFrequency());
1827 1828 1829
            if (demodSpectrumCanvas) {
                demodSpectrumCanvas->setCenterFrequency(wxGetApp().getFrequency());
            }
1830
        }
1831

1832 1833 1834 1835
        if (spectrumCanvas->getViewState() && abs(wxGetApp().getFrequency()-spectrumCanvas->getCenterFrequency()) > (wxGetApp().getSampleRate()/2)) {
            spectrumCanvas->setCenterFrequency(wxGetApp().getFrequency());
            waterfallCanvas->setCenterFrequency(wxGetApp().getFrequency());
        }
1836

1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
        if (demodMuteButton->modeChanged()) {
            int muteMode = demodMuteButton->getSelection();
            if (muteMode == -1) {
                wxGetApp().getDemodMgr().setLastMuted(false);
            } else if (muteMode == 1) {
                wxGetApp().getDemodMgr().setLastMuted(true);
            }
            demodMuteButton->clearModeChanged();
        }
    }

1848 1849 1850 1851 1852 1853 1854 1855 1856
    if (scopeCanvas) {
        scopeCanvas->setPPMMode(demodTuner->isAltDown());
        
        wxGetApp().getScopeProcessor()->setScopeEnabled(scopeCanvas->scopeVisible());
        wxGetApp().getScopeProcessor()->setSpectrumEnabled(scopeCanvas->spectrumVisible());
        wxGetApp().getAudioVisualQueue()->set_max_num_items((scopeCanvas->scopeVisible()?1:0) + (scopeCanvas->spectrumVisible()?1:0));
        
        wxGetApp().getScopeProcessor()->run();
    }
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    
    SpectrumVisualProcessor *proc = wxGetApp().getSpectrumProcessor();

    if (spectrumAvgMeter->inputChanged()) {
        float val = spectrumAvgMeter->getInputValue();
        if (val < 0.01) {
            val = 0.01f;
        }
        if (val > 0.99) {
            val = 0.99f;
        }
        spectrumAvgMeter->setLevel(val);
        proc->setFFTAverageRate(val);

        GetStatusBar()->SetStatusText(wxString::Format(wxT("Spectrum averaging speed changed to %0.2f%%."),val*100.0));
    }
    
    SpectrumVisualProcessor *dproc = wxGetApp().getDemodSpectrumProcessor();

1876 1877 1878 1879
    if (dproc) {
        dproc->setView(demodWaterfallCanvas->getViewState(), demodWaterfallCanvas->getCenterFrequency(),demodWaterfallCanvas->getBandwidth());
    }
    
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    SpectrumVisualProcessor *wproc = waterfallDataThread->getProcessor();
    
    if (waterfallSpeedMeter->inputChanged()) {
        float val = waterfallSpeedMeter->getInputValue();
        waterfallSpeedMeter->setLevel(val);
        waterfallDataThread->setLinesPerSecond((int)ceil(val*val));
        waterfallCanvas->setLinesPerSecond((int)ceil(val*val));
        GetStatusBar()->SetStatusText(wxString::Format(wxT("Waterfall max speed changed to %d lines per second."),(int)ceil(val*val)));
    }

    wproc->setView(waterfallCanvas->getViewState(), waterfallCanvas->getCenterFrequency(), waterfallCanvas->getBandwidth());
    wxGetApp().getSDRPostThread()->setIQVisualRange(waterfallCanvas->getCenterFrequency(), waterfallCanvas->getBandwidth());
    
    proc->setView(wproc->isView(), wproc->getCenterFrequency(), wproc->getBandwidth());
    
    demod = wxGetApp().getDemodMgr().getLastActiveDemodulator();
    
    if (modemPropertiesUpdated.load() && demod && demod->isModemInitialized()) {
        
        //reset notification flag
        modemPropertiesUpdated.store(false);

        modemProps->initProperties(demod->getModemArgs(), demod);
        modemProps->updateTheme(); 
        demodTray->Layout();
        modemProps->fitColumns();
#if ENABLE_DIGITAL_LAB
        if (demod->getModemType() == "digital") {
            ModemDigitalOutputConsole *outp = (ModemDigitalOutputConsole *)demod->getOutput();
            if (!outp->getDialog()) {
                outp->setTitle(demod->getDemodulatorType() + ": " + frequencyToStr(demod->getFrequency()));
1911
                outp->setDialog(new DigitalConsole(this, outp)) ;
1912 1913 1914 1915
            }
            demod->showOutput();
        }
#endif
1916 1917 1918 1919
    } else if (!demod && modemPropertiesUpdated.load()) {
        ModemArgInfoList dummyInfo;
        modemProps->initProperties(dummyInfo, nullptr);
        modemProps->updateTheme();
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
        demodTray->Layout();
    }
    
    if (modemProps->IsShown() && modemProps->isCollapsed() && modemProps->GetMinWidth() > 22) {
        modemProps->SetMinSize(wxSize(APPFRAME_MODEMPROPS_MINSIZE,-1));
        modemProps->SetMaxSize(wxSize(APPFRAME_MODEMPROPS_MINSIZE,-1));
        demodTray->Layout();
        modemProps->fitColumns();
    } else if (modemProps->IsShown() && !modemProps->isCollapsed() && modemProps->GetMinWidth() < 200) {
        modemProps->SetMinSize(wxSize(APPFRAME_MODEMPROPS_MAXSIZE,-1));
        modemProps->SetMaxSize(wxSize(APPFRAME_MODEMPROPS_MAXSIZE,-1));
        demodTray->Layout();
        modemProps->fitColumns();
    }
    
    int peakHoldMode = peakHoldButton->getSelection();
    if (peakHoldButton->modeChanged()) {
        wxGetApp().getSpectrumProcessor()->setPeakHold(peakHoldMode == 1);

        //make the peak hold act on the current dmod also, like a zoomed-in version.
1940 1941 1942
        if (wxGetApp().getDemodSpectrumProcessor()) {
            wxGetApp().getDemodSpectrumProcessor()->setPeakHold(peakHoldMode == 1);
        }
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954