summaryrefslogtreecommitdiffstats
path: root/afm-client/bower_components/foundation-icon-fonts/svgs/fi-save.svg
blob: 318ccd2e9e0d6327246451c863df471ecced1586 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 17.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 width="100px" height="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<g>
	<rect x="52.872" y="17.026" width="10.352" height="21.471"/>
	<path d="M86.217,19.195l0.006-0.006l-5.211-5.212c-0.437-0.479-1.06-0.785-1.76-0.785c-0.014,0-0.026,0.004-0.04,0.004h-8.91
		c-0.013,0-0.025,0-0.038,0h-0.139v0.024c-0.286,0.029-0.564,0.128-0.779,0.344c-0.215,0.215-0.315,0.493-0.343,0.779h-0.028v25.306
		h-0.009c-0.047,1.277-1.089,2.3-2.378,2.3h-0.297H32.135v-0.012c-1.234-0.062-2.215-1.05-2.259-2.288h-0.009V14.343h-0.048
		c-0.051-0.266-0.158-0.526-0.367-0.735c-0.311-0.311-0.724-0.427-1.119-0.387v-0.028H15.383v0l-0.001,0
		c-1.318,0-2.387,1.068-2.386,2.388l0,0v26.368v9.585v32.887l0,0.001c-0.001,1.319,1.067,2.386,2.387,2.386h0h7.57v-2.387h0V53.889
		l0-0.001c0,0,0-0.001,0-0.001v-0.053v-0.033h0.009c0.041-1.122,0.851-2.046,1.92-2.255v-0.013h0.132
		c0.108-0.015,0.215-0.032,0.326-0.032h0.001H74.64h0.001h0h0.086v0.009c1.249,0.045,2.247,1.042,2.292,2.291h0.009v33.007h7.581h0
		c1.319,0,2.387-1.068,2.387-2.386l0-0.001h0V21.029c0.001-0.025,0.007-0.048,0.007-0.073
		C87.003,20.255,86.697,19.631,86.217,19.195z"/>
</g>
</svg>
href='#n429'>429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 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 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 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 946
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkProxy>
#include <QTreeWidget>
#include <iostream>
#include <error.h>
#include <json-c/json.h>
#include <stdlib.h>
#include <unistd.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include "MainApp.h"
#include "Business.h"
#include "InfoPanel.h"
#include "ClickableLabel.h"
#include "Keyboard.h"
#include "traces.h"

#define NAVI_CONFIG_FILEPATH    "/etc/naviconfig.ini"

#define DEFAULT_TEXT        "Select your destination with Yelp !"
#define URL_AUTH            "https://api.yelp.com/oauth2/token"
#define URL_AUTOCOMPLETE    "https://api.yelp.com/v3/autocomplete"
#define URL_SEARCH          "https://api.yelp.com/v3/businesses/search"

#define LEFT_OFFSET         28
#define FONT_SIZE_LINEDIT   20
#define FONT_SIZE_LIST      18
#define TEXT_INPUT_WIDTH    800
#define SEARCH_BTN_SIZE     105
#define SPACER              15
#define WIDGET_WIDTH        (SEARCH_BTN_SIZE + SPACER + TEXT_INPUT_WIDTH)
#define DISPLAY_WIDTH       TEXT_INPUT_WIDTH
#define DISPLAY_HEIGHT      480
#define COMPLETE_W_WITH_KB    1080
#define COMPLETE_H_WITH_KB    1488
#define RESULT_ITEM_HEIGHT  80
#define MARGINS             25
#define AGL_REFRESH_DELAY   75 /* milliseconds */

#define SCROLLBAR_STYLE \
"QScrollBar:vertical {" \
"    border: 2px solid grey;" \
"    background: gray;" \
"    width: 45px;" \
"}"

using namespace std;

MainApp::MainApp(Navigation *navigation):QMainWindow(Q_NULLPTR, Qt::FramelessWindowHint),
    networkManager(this),searchBtn(QIcon(tr(":/images/loupe-90.png")), tr(""), this),
    lineEdit(this),keyboard(QRect(0, 688, COMPLETE_W_WITH_KB, 720), this),
    mutex(QMutex::Recursive),token(""),currentSearchingText(""),currentSearchedText(""),
    pSearchReply(NULL),pInfoPanel(NULL),pResultList(NULL),currentLatitude(36.136261),currentLongitude(-115.151254),
    navicoreSession(0),currentIndex(0),fontId(-1),isInfoScreen(false),
    isInputDisplayed(false),isKeyboard(false),isAglNavi(false), naviapi(navigation)
{
    //this->setAttribute(Qt::WA_TranslucentBackground);
    this->setStyleSheet("border: none;");

    searchBtn.setStyleSheet("border: none; color: #FFFFFF;");
    searchBtn.setMinimumSize(QSize(SEARCH_BTN_SIZE, SEARCH_BTN_SIZE));
    searchBtn.setIconSize(searchBtn.size());
    searchBtn.setGeometry(QRect(LEFT_OFFSET, 0, searchBtn.width(), searchBtn.height()));

    lineEdit.setStyleSheet("border: none; color: #FFFFFF;");
    lineEdit.setMinimumSize(QSize(TEXT_INPUT_WIDTH, SEARCH_BTN_SIZE));

    lineEdit.setPlaceholderText(QString(DEFAULT_TEXT));
    font = lineEdit.font();
    font.setPointSize(FONT_SIZE_LINEDIT);
    lineEdit.setFont(font);
    lineEdit.setTextMargins(MARGINS/2, 0, 0, 0);
    lineEdit.installEventFilter(this);
    lineEdit.setGeometry(QRect(LEFT_OFFSET + searchBtn.width() + SPACER, 0, lineEdit.width(), lineEdit.height()));
    lineEdit.setVisible(false);


    QFile file(NAVI_CONFIG_FILEPATH);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray data = file.readAll();
        QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
        QJsonObject jsonObj(jsonDoc.object());

        if (jsonObj.contains("latitude"))
            currentLatitude = jsonObj["latitude"].toDouble();

        if (jsonObj.contains("longitude"))
            currentLongitude = jsonObj["longitude"].toDouble();
    }

    /* We might need a Japanese font: */
    QFile fontFile(":/fonts/DroidSansJapanese.ttf");
    if (!fontFile.open(QIODevice::ReadOnly))
    {
        TRACE_ERROR("failed to open font file");
    }
    else
    {
        QByteArray fontData = fontFile.readAll();
        fontId = QFontDatabase::addApplicationFontFromData(fontData);
        if (fontId < 0)
        {
            TRACE_ERROR("QFontDatabase::addApplicationFontFromData failed");
        }
    }

    /* Check if "AGL_NAVI" env variable is set. If yes, we must notify
     * AGL environment when surface needs to be resized */
    if (getenv("AGL_NAVI"))
        isAglNavi = true;

    connect(this, SIGNAL(positionGotSignal()), this, SLOT(positionGot()));

    this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));
    this->setStyleSheet("background-image: url(:/images/AGL_POI_Background.png);");
    this->show();
}

MainApp::~MainApp()
{
    mutex.lock();
    if (fontId >= 0)
        QFontDatabase::removeApplicationFont(fontId);

    searchBtn.disconnect();
    lineEdit.disconnect();
    networkManager.disconnect();
    keyboard.disconnect();

    delete pSearchReply;
    delete pInfoPanel;
    mutex.unlock();
}

void MainApp::searchBtnClicked()
{
    isInputDisplayed = !isInputDisplayed;
    TRACE_DEBUG("isInputDisplayed = %d", isInputDisplayed);
    DisplayLineEdit(isInputDisplayed);
}

void MainApp::DisplayLineEdit(bool display)
{
    mutex.lock();

    this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));

    if (display)
    {
        lineEdit.setVisible(true);
        lineEdit.setFocus();
    }
    else
    {
        if (pResultList)
        {
            pResultList->removeEventFilter(this);
            delete pResultList;
            pResultList = NULL;
        }
        if (pInfoPanel)
        {
            delete pInfoPanel;
            pInfoPanel = NULL;
        }
        lineEdit.setText(tr(""));
        lineEdit.setVisible(false);
    }
    isInputDisplayed = display;

    mutex.unlock();
}

void MainApp::UpdateAglSurfaces()
{
    char cmd[1024];

    TRACE_DEBUG("handle AGL demo surfaces (new surface is bigger)");
    snprintf(cmd, 1023, "/usr/bin/LayerManagerControl set surface $SURFACE_ID_CLIENT source region 0 0 %d %d",
        this->width(), this->height());
    TRACE_DEBUG("%s", cmd);
    system(cmd);
    snprintf(cmd, 1023, "/usr/bin/LayerManagerControl set surface $SURFACE_ID_CLIENT destination region $CLIENT_X $CLIENT_Y %d %d",
        this->width(), this->height());
    TRACE_DEBUG("%s", cmd);
    system(cmd);
}

void MainApp::DisplayResultList(bool display, bool RefreshDisplay)
{
    mutex.lock();

    if (display)
    {
        if (!pResultList)
        {
            pResultList = new QTreeWidget(this);
            pResultList->setStyleSheet("border: none; color: #FFFFFF;");
            pResultList->setRootIsDecorated(false);
            pResultList->setEditTriggers(QTreeWidget::NoEditTriggers);
            pResultList->setSelectionBehavior(QTreeWidget::SelectRows);
            pResultList->setFrameStyle(QFrame::Box | QFrame::Plain);
            pResultList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
            //pResultList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
            pResultList->setAttribute(Qt::WA_AcceptTouchEvents);
            pResultList->verticalScrollBar()->setStyleSheet(SCROLLBAR_STYLE);
            pResultList->header()->hide();
            //font.setPointSize(FONT_SIZE_LIST);
            //pResultList->setFont(font);
            pResultList->installEventFilter(this);
        }

        pResultList->setGeometry(QRect(   LEFT_OFFSET+searchBtn.width()+SPACER, searchBtn.height()+SPACER,
                                        DISPLAY_WIDTH, DISPLAY_HEIGHT));
        if (RefreshDisplay)
        {
            this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));
        }
        pResultList->setVisible(true);
        pResultList->setFocus();
    }
    else
    {
        if (pResultList)
        {
            pResultList->removeEventFilter(this);
            pResultList->deleteLater();
            pResultList = NULL;
        }

        lineEdit.setFocus();

        if (RefreshDisplay)
        {
            this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));
        }
    }

    mutex.unlock();
}

void MainApp::textChanged(const QString & text)
{
    TRACE_INFO("New text is: %s", qPrintable(text));

    /* do not handle text input if info panel is displayed: */
    if (pInfoPanel) return;

    mutex.lock();

    delete pSearchReply;    /* cancel current search */
    pSearchReply = NULL;

    if (text.length() == 0) /* if empty text -> no search */
    {
        DisplayResultList(false);
        mutex.unlock();
        return;
    }

    /* if text is the same as previous search -> no need to search again */
    if (text == currentSearchedText)
    {
        DisplayResultList(true);
        FillResultList(Businesses, currentIndex);
        mutex.unlock();
        return;
    }
    this->currentSearchingText = text;

    emit positionGotSignal();

    mutex.unlock();
}

void MainApp::textAdded(const QString & text)
{
    mutex.lock();
    lineEdit.setText(lineEdit.text() + text);

    // be sure any text is visible on initial input
    lineEdit.setVisible(true);

    mutex.unlock();
}

void MainApp::keyPressed(int key)
{
    mutex.lock();
    if (key == '\b') /* backspace */
    {
        int len = lineEdit.text().length();
        if (len > 0)
            lineEdit.setText(lineEdit.text().remove(len-1, 1));
    }
    mutex.unlock();
}

void MainApp::itemClicked()
{
    mutex.lock();
    if (isInfoScreen)
    {
        DisplayInformation(true, false);
    }
    else
    {
        SetDestination();
        DisplayLineEdit(false);
    }
    mutex.unlock();
}

void MainApp::ParseJsonBusinessList(const char* buf, std::vector<Business> & Output)
{
    json_object *jobj = json_tokener_parse(buf);
    if (!jobj)
    {
        TRACE_ERROR("json_tokener_parse failed");
        cerr << "json_tokener_parse failed: " << buf << endl;
        return;
    }

    json_object_object_foreach(jobj, key, val)
    {
        (void)key;
        json_object *value;

        if (json_object_get_type(val) == json_type_array)
        {
            TRACE_DEBUG_JSON("an array was found");

            if(json_object_object_get_ex(jobj, "businesses", &value))
            {
                TRACE_DEBUG_JSON("an business was found");

                int arraylen = json_object_array_length(value);

                for (int i = 0; i < arraylen; i++)
                {
                    Business NewBusiness;

                    json_object* medi_array_obj, *medi_array_obj_elem;
                    medi_array_obj = json_object_array_get_idx(value, i);
                    if (medi_array_obj)
                    {
                        if (json_object_object_get_ex(medi_array_obj, "rating", &medi_array_obj_elem))
                        {
                            NewBusiness.Rating = json_object_get_double(medi_array_obj_elem);
                            TRACE_DEBUG_JSON("got Rating : %f", NewBusiness.Rating);
                        }

                        if (json_object_object_get_ex(medi_array_obj, "distance", &medi_array_obj_elem))
                        {
                            NewBusiness.Distance = json_object_get_double(medi_array_obj_elem);
                            TRACE_DEBUG_JSON("got Distance : %f", NewBusiness.Distance);
                        }

                        if (json_object_object_get_ex(medi_array_obj, "review_count", &medi_array_obj_elem))
                        {
                            NewBusiness.ReviewCount = json_object_get_int(medi_array_obj_elem);
                            TRACE_DEBUG_JSON("got ReviewCount : %u", NewBusiness.ReviewCount);
                        }

                        if (json_object_object_get_ex(medi_array_obj, "name", &medi_array_obj_elem))
                        {
                            NewBusiness.Name = QString(json_object_get_string(medi_array_obj_elem));
                            TRACE_DEBUG_JSON("got Name : %s", qPrintable(NewBusiness.Name));
                        }

                        if (json_object_object_get_ex(medi_array_obj, "image_url", &medi_array_obj_elem))
                        {
                            NewBusiness.ImageUrl = QString(json_object_get_string(medi_array_obj_elem));
                            TRACE_DEBUG_JSON("got ImageUrl : %s", qPrintable(NewBusiness.ImageUrl));
                        }

                        if (json_object_object_get_ex(medi_array_obj, "phone", &medi_array_obj_elem))
                        {
                            NewBusiness.Phone = QString(json_object_get_string(medi_array_obj_elem));
                            TRACE_DEBUG_JSON("got Phone : %s", qPrintable(NewBusiness.Phone));
                        }

                        if (json_object_object_get_ex(medi_array_obj, "coordinates", &medi_array_obj_elem))
                        {
                            json_object *value2;

                            TRACE_DEBUG_JSON("coordinates were found");

                            if(json_object_object_get_ex(medi_array_obj_elem, "latitude", &value2))
                            {
                                NewBusiness.Latitude = json_object_get_double(value2);
                                TRACE_DEBUG_JSON("got Latitude : %f", NewBusiness.Latitude);
                            }

                            if(json_object_object_get_ex(medi_array_obj_elem, "longitude", &value2))
                            {
                                NewBusiness.Longitude = json_object_get_double(value2);
                                TRACE_DEBUG_JSON("got Longitude : %f", NewBusiness.Longitude);
                            }
                        }

                        if (json_object_object_get_ex(medi_array_obj, "location", &medi_array_obj_elem))
                        {
                            json_object *value2;

                            TRACE_DEBUG_JSON("a location was found");

                            /* TODO: how do we deal with address2 and address3 ? */
                            if(json_object_object_get_ex(medi_array_obj_elem, "address1", &value2))
                            {
                                NewBusiness.Address = QString(json_object_get_string(value2));
                                TRACE_DEBUG_JSON("got Address : %s", qPrintable(NewBusiness.Address));
                            }

                            if(json_object_object_get_ex(medi_array_obj_elem, "city", &value2))
                            {
                                NewBusiness.City = QString(json_object_get_string(value2));
                                TRACE_DEBUG_JSON("got City : %s", qPrintable(NewBusiness.City));
                            }

                            if(json_object_object_get_ex(medi_array_obj_elem, "state", &value2))
                            {
                                NewBusiness.State = QString(json_object_get_string(value2));
                                TRACE_DEBUG_JSON("got State : %s", qPrintable(NewBusiness.State));
                            }

                            if(json_object_object_get_ex(medi_array_obj_elem, "zip_code", &value2))
                            {
                                NewBusiness.ZipCode = QString(json_object_get_string(value2));
                                TRACE_DEBUG_JSON("got ZipCode : %s", qPrintable(NewBusiness.ZipCode));
                            }

                            if(json_object_object_get_ex(medi_array_obj_elem, "country", &value2))
                            {
                                NewBusiness.Country = QString(json_object_get_string(value2));
                                TRACE_DEBUG_JSON("got Country : %s", qPrintable(NewBusiness.Country));
                            }
                        }

                        /* TODO: parse categories */

                        /* Add business in our list: */
                        Businesses.push_back(NewBusiness);
                    }
                }
            }
        }
    }

    json_object_put(jobj);
}

bool MainApp::eventFilter(QObject *obj, QEvent *ev)
{
    bool ret = false;

    mutex.lock();

    if (obj == pResultList)
    {
        //TRACE_DEBUG("ev->type() = %d", (int)ev->type());

        if (ev->type() == QEvent::KeyPress)
        {
            bool consumed = false;
            int key = static_cast<QKeyEvent*>(ev)->key();
            TRACE_DEBUG("key pressed (%d)", key);
            switch (key) {
                case Qt::Key_Enter:
                case Qt::Key_Return:
                    TRACE_DEBUG("enter or return");
                    if (isInfoScreen)
                    {
                        DisplayInformation(true);
                    }
                    else
                    {
                        SetDestination();
                        DisplayLineEdit(false);
                    }
                    consumed = true;
                    break;

                case Qt::Key_Escape:
                    TRACE_DEBUG("escape");
                    DisplayResultList(false);
                    consumed = true;
                    break;

                case Qt::Key_Up:
                case Qt::Key_Down:
                case Qt::Key_Home:
                case Qt::Key_End:
                case Qt::Key_PageUp:
                case Qt::Key_PageDown:
                    TRACE_DEBUG("arrows");
                    break;

                default:
                    TRACE_DEBUG("default");
                    lineEdit.event(ev);
                    break;
            }

            mutex.unlock();
            return consumed;
        }
    }
    else if (obj == &lineEdit)
    {
        if (pInfoPanel && ev->type() == QEvent::KeyPress)
        {
            switch(static_cast<QKeyEvent*>(ev)->key())
            {
                case Qt::Key_Escape:
                    TRACE_DEBUG("Escape !");
                    DisplayInformation(false, false);
                    DisplayResultList(true);
                    FillResultList(Businesses, currentIndex);
                    break;
                case Qt::Key_Enter:
                case Qt::Key_Return:
                    TRACE_DEBUG("Go !");
                    SetDestination(currentIndex);
                    DisplayLineEdit(false);
                    break;
                default: break;
            }
        }
    }
    else
    {
        ret = QMainWindow::eventFilter(obj, ev);
    }
    mutex.unlock();
    return ret;
}

void MainApp::resizeEvent(QResizeEvent* event)
{
    QMainWindow::resizeEvent(event);
    if (isAglNavi)
    {
        QTimer::singleShot(AGL_REFRESH_DELAY, Qt::CoarseTimer, this, SLOT(UpdateAglSurfaces()));
    }
}

void MainApp::SetDestination(int index)
{
    mutex.lock();

    /* if pResultList exists, take the selected index
     * otherwise, take the index given as parameter */
    if (pResultList)
    {
        QList<QTreeWidgetItem *> SelectedItems = pResultList->selectedItems();
        if (SelectedItems.size() > 0)
        {
            /* select the first selected item : */
            index = pResultList->indexOfTopLevelItem(*SelectedItems.begin());
        }
    }

    TRACE_DEBUG("index is: %d", index);

    /* retrieve the coordinates of this item : */
    this->destinationLatitude = Businesses[index].Latitude;
    this->destinationLongitude = Businesses[index].Longitude;

    SetWayPoints(0);

    mutex.unlock();
}

void MainApp::DisplayInformation(bool display, bool RefreshDisplay)
{
    mutex.lock();
    if (display)
    {
        /* pResultList must exist, so that we can retrieve the selected index: */
        if (!pResultList)
        {
            TRACE_ERROR("pResultList is null");
            mutex.unlock();
            return;
        }

        QList<QTreeWidgetItem *> SelectedItems = pResultList->selectedItems();
        if (SelectedItems.size() <= 0)
        {
            TRACE_ERROR("no item is selected");
            mutex.unlock();
            return;
        }

        /* select the first selected item : */
        currentIndex = pResultList->indexOfTopLevelItem(*SelectedItems.begin());

        /* Resize window: */
        DisplayResultList(false, false);

        /* Display info for the selected item: */
        QRect rect( LEFT_OFFSET+searchBtn.width()+SPACER, searchBtn.height()+SPACER,
                    DISPLAY_WIDTH, DISPLAY_HEIGHT);
        pInfoPanel = new InfoPanel(this, Businesses[currentIndex], rect);

        if (RefreshDisplay)
        {
            this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));
        }

        connect(pInfoPanel->getGoButton(),      SIGNAL(clicked(bool)), this, SLOT(goClicked()));
        connect(pInfoPanel->getCancelButton(),  SIGNAL(clicked(bool)), this, SLOT(cancelClicked()));
    }
    else
    {
        if (pInfoPanel)
        {
            pInfoPanel->getGoButton()->disconnect();
            pInfoPanel->getCancelButton()->disconnect();
            delete pInfoPanel;
            pInfoPanel = NULL;
        }
        lineEdit.setFocus();

        if (RefreshDisplay)
        {
            this->setGeometry(QRect(this->pos().x(), this->pos().y(), COMPLETE_W_WITH_KB, COMPLETE_H_WITH_KB));
        }
    }

    mutex.unlock();
}

void MainApp::networkReplySearch(QNetworkReply* reply)
{
    QByteArray buf;

    mutex.lock();

    /* memorize the text which gave this result: */
    currentSearchedText = lineEdit.text();

    if (reply->error() == QNetworkReply::NoError)
    {
        // we only handle this callback if it matches the last search request:
        if (reply != pSearchReply)
        {
            TRACE_INFO("this reply is already too late (or about a different network request)");
            mutex.unlock();
            return;
        }

        buf = reply->readAll();

        if (buf.isEmpty())
        {
            mutex.unlock();
            return;
        }



        currentIndex = 0;
        Businesses.clear();
        ParseJsonBusinessList(buf.data(), Businesses);
        DisplayResultList(true);
        FillResultList(Businesses);
    }
    else
    {
        fprintf(stderr,"POI: reply error network please check to poikey and system time (adjusted?)\n");
    }

    mutex.unlock();
}

/* pResultList must be allocated at this point ! */
int MainApp::FillResultList(vector<Business> & list, int focusIndex)
{
    int nbElem = 0;

    mutex.lock();

    pResultList->setUpdatesEnabled(false);
    pResultList->clear();

    /* filling the dropdown menu: */
    for (vector<Business>::iterator it = list.begin(); it != list.end(); it++)
    {
        /*  workaround to avoid entries with wrong coordinates returned by Yelp: */
        if (IsCoordinatesConsistent(*it) == false)
        {
            list.erase(it--);
            continue;
        }

        QTreeWidgetItem * item = new QTreeWidgetItem(pResultList);

        ClickableLabel *label = new ClickableLabel("<b>"+(*it).Name+
            "</b><br>"+(*it).Address+", "+(*it).City+", "+(*it).State+
            " "+(*it).ZipCode+", "+(*it).Country, pResultList);
        label->setTextFormat(Qt::RichText);
        font.setPointSize(FONT_SIZE_LIST);
        label->setFont(font);
        label->setIndent(MARGINS);
        label->setAttribute(Qt::WA_AcceptTouchEvents);
        item->setSizeHint(0, QSize(TEXT_INPUT_WIDTH, RESULT_ITEM_HEIGHT));
        pResultList->setItemWidget(item, 0, label);
        connect(label, SIGNAL(clicked()), this, SLOT(itemClicked()));

        //item->setText(0, (*it).Name);

        if (nbElem == focusIndex)
        {
            pResultList->setCurrentItem(item);
        }
        nbElem++;
    }

    pResultList->setUpdatesEnabled(true);

    mutex.unlock();
    return nbElem;
}

/* Well... some of the POI returned by Yelp have coordinates which are
 * completely inconsistent with the distance at which the POI is
 * supposed to be.
 * https://github.com/Yelp/yelp-fusion/issues/104
 * Let's skip them for the moment: */
#define PI 3.14159265
#define EARTH_RADIUS 6371000
static inline double toRadians(double a) { return a * PI / 180.0; }
bool MainApp::IsCoordinatesConsistent(Business & business)
{
    double lat1 = toRadians(currentLatitude);
    double lon1 = toRadians(currentLongitude);
    double lat2 = toRadians(business.Latitude);
    double lon2 = toRadians(business.Longitude);
    double x = (lon2 - lon1) * cos((lat1 + lat2)/2);
    double y = lat2 - lat1;
    double DistanceFromCoords = EARTH_RADIUS * sqrt(pow(x, 2) + pow(y, 2));

    /* if calculated distance is not between +/- 10% of the announced
     * distance -> skip this POI: */
    if (DistanceFromCoords < business.Distance * 0.9 ||
        DistanceFromCoords > business.Distance * 1.1)
    {
        TRACE_ERROR("Announced distance: %f, calculated distance: %f", business.Distance, DistanceFromCoords);
        return false;
    }

    return true;
}
/* end of workaround */

int MainApp::AuthenticatePOI(const QString & CredentialsFile)
{
    char buf[512];
    QString AppId;
    QString AppSecret;
    QString ProxyHostName;
    QString PortStr;
    QString User;
    QString Password;
    int portnum;

    /* First, read AppId and AppSecret from credentials file: */
    FILE* filep = fopen(qPrintable(CredentialsFile), "r");
    if (!filep)
    {
        fprintf(stderr,"Failed to open credentials file \"%s\": %m", qPrintable(CredentialsFile));
        return -1;
    }

    if (!fgets(buf, 512, filep))
    {
        fprintf(stderr,"Failed to read AppId from credentials file \"%s\"", qPrintable(CredentialsFile));
        fclose(filep);
        return -1;
    }
    if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
        buf[strlen(buf)-1] = '\0';
    AppId = QString(buf);

    if (!fgets(buf, 512, filep))
    {
        fprintf(stderr,"Failed to read AppSecret from credentials file \"%s\"", qPrintable(CredentialsFile));
        fclose(filep);
        return -1;
    }
    if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
        buf[strlen(buf)-1] = '\0';
    AppSecret = QString(buf);

    QNetworkProxy proxy;

    //ProxyHostName
    if (!fgets(buf, 512, filep))
    {
        TRACE_INFO("Failed to read ProxyHostName from credentials file \"%s\"", qPrintable(CredentialsFile));
    }
    else
    {
        if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
            buf[strlen(buf)-1] = '\0';
        ProxyHostName = QString(buf);
        ProxyHostName.replace(0, 14, tr(""));

        //Port
        if (!fgets(buf, 512, filep))
        {
            TRACE_ERROR("Failed to read Port from credentials file \"%s\"", qPrintable(CredentialsFile));
            fclose(filep);
            return -1;
        }
        if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
            buf[strlen(buf)-1] = '\0';
        PortStr = QString(buf);
        PortStr.replace(0, 5, tr(""));
        portnum = PortStr.toInt();

        //User
        if (!fgets(buf, 512, filep))
        {
            TRACE_ERROR("Failed to read User from credentials file \"%s\"", qPrintable(CredentialsFile));
            fclose(filep);
            return -1;
        }
        if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
            buf[strlen(buf)-1] = '\0';
        User = QString(buf);
        User.replace(0, 5, tr(""));

        //Password
        if (!fgets(buf, 512, filep))
        {
            TRACE_ERROR("Failed to read Password from credentials file \"%s\"", qPrintable(CredentialsFile));
            fclose(filep);
            return -1;
        }
        if (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
            buf[strlen(buf)-1] = '\0';
        Password = QString(buf);
        Password.replace(0, 9, tr(""));

        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(qPrintable(ProxyHostName));
        proxy.setPort(portnum);
        proxy.setUser(qPrintable(User));
        proxy.setPassword(qPrintable(Password));
        QNetworkProxy::setApplicationProxy(proxy);
    }

    fclose(filep);

    TRACE_INFO("Found credentials");

    /* Then, send a HTTP request to get the token and wait for answer (synchronously): */

    token = AppSecret;
    return 0;
}

int MainApp::StartMonitoringUserInput()
{
    connect(&searchBtn, SIGNAL(clicked(bool)), this, SLOT(searchBtnClicked()));
    connect(&lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));
    connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(networkReplySearch(QNetworkReply*)));
    connect(&keyboard, SIGNAL(keyClicked(const QString &)), this, SLOT(textAdded(const QString &)));
    connect(&keyboard, SIGNAL(specialKeyClicked(int)), this, SLOT(keyPressed(int)));
    return 1;
}

void MainApp::SetWayPoints(uint32_t myRoute)
{
    /* set the destination : */
    naviapi->sendWaypoint(this->destinationLatitude, this->destinationLongitude);

    /* reset search: */
    currentSearchingText = tr("");
    currentSearchedText = tr("");
    currentIndex = 0;
    Businesses.clear();
}

void MainApp::goClicked()
{
    TRACE_DEBUG("Go clicked !");
    SetDestination(currentIndex);
    DisplayLineEdit(false);
}

void MainApp::cancelClicked()
{
    TRACE_DEBUG("Cancel clicked !");
    DisplayInformation(false, false);
    DisplayResultList(true, false);
    FillResultList(Businesses, currentIndex);
}

void MainApp::getAllSessions_reply(const std::map< uint32_t, std::string >& allSessions)
{
    mutex.lock();

    if (allSessions.empty())
    {
        TRACE_ERROR("Error: could not find an instance of Navicore");
        mutex.unlock();
        return;
    }

    this->navicoreSession = allSessions.begin()->first;

    TRACE_INFO("Current session: %d", this->navicoreSession);

    mutex.unlock();
}

void MainApp::positionGot()
{
    mutex.lock();

    /* let's generate a search request : */
    QString myUrlStr = URL_SEARCH + tr("?") + tr("term=") + currentSearchingText +
        tr("&latitude=") + QString::number(currentLatitude) +
        tr("&longitude=") + QString::number(currentLongitude);

    TRACE_DEBUG("URL: %s", qPrintable(myUrlStr));

    QUrl myUrl = QUrl(myUrlStr);
    QNetworkRequest req(myUrl);
    req.setRawHeader(QByteArray("Authorization"), (tr("bearer ") + token).toLocal8Bit());

    /* Then, send a HTTP request to get the token and wait for answer (synchronously): */

    pSearchReply = networkManager.get(req);

    mutex.unlock();
}