Example #1
0
int main(int argc, char *argv[])
{
    // Qt initialisation
    QApplication a(argc, argv);

#ifdef Q_OS_LINUX
    setup_unix_signal_handlers();
#endif

    QStringList pathlist = QCoreApplication::libraryPaths();
    qDebug() << pathlist;
#if QT_VERSION >= 0x050000
    // Fixing the qt5 plugin mess
    pathlist << ".";
    QCoreApplication::setLibraryPaths(pathlist);
#endif

    // Creating the QT log file

    QDir homeDir = QDir::home();
    if (!homeDir.cd(Pip3lineConst::USER_DIRECTORY)) {
        if (!homeDir.mkpath(Pip3lineConst::USER_DIRECTORY)) {
            qWarning("Cannot create user directory for log file");
        }
    }

    homeDir = QDir::home();
    if (homeDir.cd(Pip3lineConst::USER_DIRECTORY)) {
        QByteArray logdir = homeDir.absolutePath().append(QDir::separator()).append("pip3line_gui.log").toLocal8Bit();
#ifdef Q_CC_MSVC
#define BUFFERSIZE 200

        char buffer[BUFFERSIZE];
        memset((void *)buffer, 0, BUFFERSIZE);

        errno_t err = fopen_s (&_logFile, logdir.constData(),"w");
        if ( err != 0) {
            strerror_s(buffer, BUFFERSIZE, err);
            qWarning( buffer );
#else
        _logFile = fopen (logdir.constData(),"w");

        if (_logFile == NULL) {
            qWarning("Cannot open log file for writing");
#endif
        } else {
#if QT_VERSION >= 0x050000
            qInstallMessageHandler(myMessageOutput);
#else
            qInstallMsgHandler(myMessageOutput);
#endif
        }
    }


#if QT_VERSION >= 0x050000
    // forcing style for Qt5. can be overwritten at runtime
    // with the option -style [style name]
    // An indicative list of available themes is given in the Help->info dialog
    QStringList stylelist = QStyleFactory::keys();
    if (stylelist.contains("Fusion"))
        QApplication::setStyle("Fusion");
#ifdef Q_OS_WIN
    else if (stylelist.contains("WindowsVista"))
        QApplication::setStyle("WindowsVista");
    else if (stylelist.contains("WindowsXP"))
        QApplication::setStyle("WindowsXP");
#endif

#endif

    a.setStyleSheet("QWidget{ selection-background-color: blue}");
    qDebug() << "App started";
    QStyle *currentStyle = QApplication::style();
    qDebug() << "Style" << currentStyle << currentStyle->objectName();

    // Cleaning the PATH on Windows to avoid library corruption whenever loading plugins
    qputenv("PATH", QByteArray());

#ifdef Q_OS_UNIX
    qputenv("LD_PRELOAD", QByteArray());

#endif

    QStringList list = QApplication::arguments();

    bool debugging =  false;
    if (list.contains(DEBUG_CMD)) {
        debugging = true;
        list.removeAll(DEBUG_CMD);
    }

    QString fileName;
    if (list.contains(FILE_CMD)) {
        int index = list.indexOf(FILE_CMD);
        if (list.size() > index + 1) {
            fileName = list.at(index + 1);
            list.removeAt(index);
            list.removeAt(index);
        } else {
            qCritical() << QObject::tr("Missing file name for --file, ignoring.");
        }
    }

    int ret = 0;
    w = new(std::nothrow) MainWindow(debugging);
    if (w != NULL) {
        if (!fileName.isEmpty())
            w->loadFile(fileName);

        w->show();

        ret = a.exec();
        //qWarning() << "App ending";

        MainWindow * wt = w;
        w = NULL;
        delete wt;
    }

    if (_logFile != NULL) {
        fclose (_logFile);
        _logFile = NULL;
    }

    return ret;
}
SettingsDlg::SettingsDlg(QWidget *parent, CR3View * docView ) :
    QDialog(parent),
    m_ui(new Ui::SettingsDlg),
    m_docview( docView )
{
    initDone = false;

    m_ui->setupUi(this);
    m_props = m_docview->getOptions();

    m_oldHyph = cr2qt(HyphMan::getSelectedDictionary()->getId());

#ifdef _LINUX
    QString homeDir = QDir::toNativeSeparators(QDir::homePath() + "/.cr3/");
#else
    QString homeDir = QDir::toNativeSeparators(QDir::homePath() + "/cr3/");
#endif
#if MAC==1
    QString exeDir = QDir::toNativeSeparators(qApp->applicationDirPath() + "/../Resources/"); //QDir::separator();
#elif _LINUX
    QString exeDir = QString(CR3_DATA_DIR);
#else
    QString exeDir = QDir::toNativeSeparators(qApp->applicationDirPath() + "/"); //QDir::separator();
#endif

    lString16Collection baseDirs;
    baseDirs.add(qt2cr(homeDir));
    baseDirs.add(qt2cr(exeDir));
#ifdef _LINUX
    baseDirs.add(cs16("/usr/local/share/cr3/"));
#endif
    lString16Collection bgFiles;
    QStringList bgFileLabels;
    findBackgrounds( baseDirs, bgFiles );
    int bgIndex = 0;
    m_backgroundFiles.append("[NONE]");
    bgFileLabels.append("[NONE]");
    QString bgFile = m_props->getStringDef(PROP_BACKGROUND_IMAGE, "");
    for ( int i=0; i<bgFiles.length(); i++ ) {
        lString16 fn = bgFiles[i];
        QString f = cr2qt(fn);
        if ( f==bgFile )
            bgIndex = i;
        m_backgroundFiles.append(f);
        fn = LVExtractFilenameWithoutExtension(fn);
        bgFileLabels.append(cr2qt(fn));
    }
    m_ui->cbPageSkin->clear();
    m_ui->cbPageSkin->addItems( bgFileLabels );
    m_ui->cbPageSkin->setCurrentIndex(bgIndex+1);

    optionToUi( PROP_WINDOW_FULLSCREEN, m_ui->cbWindowFullscreen );
    optionToUi( PROP_WINDOW_SHOW_MENU, m_ui->cbWindowShowMenu );
    optionToUi( PROP_WINDOW_SHOW_SCROLLBAR, m_ui->cbWindowShowScrollbar );
    optionToUi( PROP_WINDOW_TOOLBAR_SIZE, m_ui->cbWindowShowToolbar );
    optionToUi( PROP_WINDOW_SHOW_STATUSBAR, m_ui->cbWindowShowStatusBar );

    optionToUi( PROP_FOOTNOTES, m_ui->cbShowFootNotes );
    optionToUi( PROP_SHOW_BATTERY, m_ui->cbShowBattery );
    optionToUi( PROP_SHOW_TIME, m_ui->cbShowClock );
    optionToUi( PROP_SHOW_TITLE, m_ui->cbShowBookName );
    optionToUi( PROP_TXT_OPTION_PREFORMATTED, m_ui->cbTxtPreFormatted );
    optionToUi( PROP_EMBEDDED_STYLES, m_ui->cbEnableDocumentStyles );
    optionToUi( PROP_EMBEDDED_FONTS, m_ui->cbEnableEmbeddedFonts );
    m_ui->cbEnableEmbeddedFonts->setEnabled(m_props->getBoolDef(PROP_EMBEDDED_STYLES, true) ? Qt::Checked : Qt::Unchecked);
    optionToUi( PROP_TXT_OPTION_PREFORMATTED, m_ui->cbTxtPreFormatted );
    optionToUi( PROP_FLOATING_PUNCTUATION, m_ui->cbFloatingPunctuation );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMIN_INLINE_MODE, m_ui->cbImageInlineZoominMode );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMIN_INLINE_SCALE, m_ui->cbImageInlineZoominScale );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMOUT_INLINE_MODE, m_ui->cbImageInlineZoomoutMode );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMOUT_INLINE_SCALE, m_ui->cbImageInlineZoomoutScale );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMIN_BLOCK_MODE, m_ui->cbImageBlockZoominMode );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMIN_BLOCK_SCALE, m_ui->cbImageBlockZoominScale );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMOUT_BLOCK_MODE, m_ui->cbImageBlockZoomoutMode );
    optionToUiIndex( PROP_IMG_SCALING_ZOOMOUT_BLOCK_SCALE, m_ui->cbImageBlockZoomoutScale );

    QString gamma = m_props->getStringDef(PROP_FONT_GAMMA, "");
    if ( gamma=="" )
        m_props->setString(PROP_FONT_GAMMA, "1.0");
    optionToUiString(PROP_FONT_GAMMA, m_ui->cbFontGamma);

    optionToUiInversed( PROP_STATUS_LINE, m_ui->cbShowPageHeader );

    bool b = m_props->getIntDef( PROP_STATUS_LINE, 0 )==0;
    m_ui->cbShowBattery->setEnabled( b );
    m_ui->cbShowClock->setEnabled( b );
    m_ui->cbShowBookName->setEnabled( b );

    m_ui->cbStartupAction->setCurrentIndex( m_props->getIntDef( PROP_APP_START_ACTION, 0 ) );



    int lp = m_props->getIntDef( PROP_LANDSCAPE_PAGES, 2 );
    int vm = m_props->getIntDef( PROP_PAGE_VIEW_MODE, 1 );
    if ( vm==0 )
        m_ui->cbViewMode->setCurrentIndex( 2 );
    else
        m_ui->cbViewMode->setCurrentIndex( lp==1 ? 0 : 1 );
    int hinting = m_props->getIntDef(PROP_FONT_HINTING, 2);
    m_ui->cbFontHinting->setCurrentIndex(hinting);
    int highlight = m_props->getIntDef(PROP_HIGHLIGHT_COMMENT_BOOKMARKS, 1);
    m_ui->cbBookmarkHighlightMode->setCurrentIndex(highlight);


    int n = m_props->getIntDef( PROP_PAGE_MARGIN_LEFT, 8 );
    int mi = 0;
    for (int i=0; i <  (int)MAX_MARGIN_INDEX; i++) {
        if (n <= def_margins[i]) {
            mi = i;
            break;
        }
    }
    CRLog::debug("initial margins index: %d", mi);
    m_ui->cbMargins->setCurrentIndex( mi );

    QStringList styles = QStyleFactory::keys();
    QString style = m_props->getStringDef( PROP_WINDOW_STYLE, "" );
    m_ui->cbLookAndFeel->addItems( styles );
    QStyle * s = QApplication::style();
    QString currStyle = s->objectName();
    CRLog::debug("Current system style is %s", currStyle.toUtf8().data() );
    if ( !styles.contains(style, Qt::CaseInsensitive) )
        style = currStyle;
    int index = styles.indexOf( style, Qt::CaseInsensitive );
    if ( index >=0 )
        m_ui->cbLookAndFeel->setCurrentIndex( index );

    crGetFontFaceList( m_faceList );
    m_ui->cbTextFontFace->addItems( m_faceList );
    m_ui->cbTitleFontFace->addItems( m_faceList );
    m_ui->cbFallbackFontFace->addItems( m_faceList );
    QStringList sizeList;
    LVArray<int> sizes( cr_font_sizes, sizeof(cr_font_sizes)/sizeof(int) );
    for ( int i=0; i<sizes.length(); i++ )
        sizeList.append( QString("%1").arg(sizes[i]) );
    m_ui->cbTextFontSize->addItems( sizeList );
    m_ui->cbTitleFontSize->addItems( sizeList );
    
    const char * defFontFace = "DejaVu Sans";
    static const char * goodFonts[] = {
        "DejaVu Sans",
        "FreeSans",
        "Liberation Sans",
        "Arial",
        NULL
    };
    for ( int i=0; goodFonts[i]; i++ ) {
        if ( m_faceList.indexOf(QString(goodFonts[i]))>=0 ) {
            defFontFace = goodFonts[i];
            break;
        }
    }

    fontToUi( PROP_FONT_FACE, PROP_FONT_SIZE, m_ui->cbTextFontFace, m_ui->cbTextFontSize, defFontFace );
    fontToUi( PROP_STATUS_FONT_FACE, PROP_STATUS_FONT_SIZE, m_ui->cbTitleFontFace, m_ui->cbTitleFontSize, defFontFace );
    fontToUi( PROP_FALLBACK_FONT_FACE, PROP_FALLBACK_FONT_FACE, m_ui->cbFallbackFontFace, NULL, defFontFace );

//		{_("90%"), "90"},
//		{_("100%"), "100"},
//		{_("110%"), "110"},
//		{_("120%"), "120"},
//		{_("140%"), "140"},
    //PROP_INTERLINE_SPACE
    //PROP_HYPHENATION_DICT
    QString v = QString("%1").arg(m_props->getIntDef(PROP_INTERLINE_SPACE, 100)) + "%";
    QStringList isitems;
    for (int i = 0; i < (int)(sizeof(interline_spaces) / sizeof(int)); i++)
        isitems.append(QString("%1").arg(interline_spaces[i]) + "%");
    m_ui->cbInterlineSpace->addItems(isitems);
    int isi = m_ui->cbInterlineSpace->findText(v);
    m_ui->cbInterlineSpace->setCurrentIndex(isi>=0 ? isi : 6);

    int hi = -1;
    v = m_props->getStringDef(PROP_HYPHENATION_DICT,"@algorithm"); //HYPH_DICT_ID_ALGORITHM;
    for ( int i=0; i<HyphMan::getDictList()->length(); i++ ) {
        HyphDictionary * item = HyphMan::getDictList()->get( i );
        if (v == cr2qt(item->getFilename() ) ||  v == cr2qt(item->getId() ))
            hi = i;
        QString s = cr2qt( item->getTitle() );
        if ( item->getType()==HDT_NONE )
            s = tr("[No hyphenation]");
        else if ( item->getType()==HDT_ALGORITHM )
            s = tr("[Algorythmic hyphenation]");
        m_ui->cbHyphenation->addItem( s );
    }
    m_ui->cbHyphenation->setCurrentIndex(hi>=0 ? hi : 1);


    m_ui->crSample->setOptions( m_props );
    m_ui->crSample->getDocView()->setShowCover( false );
    m_ui->crSample->getDocView()->setViewMode( DVM_SCROLL, 1 );
    QString testPhrase = tr("The quick brown fox jumps over the lazy dog. ");
    m_ui->crSample->getDocView()->createDefaultDocument(lString16::empty_str, qt2cr(testPhrase+testPhrase+testPhrase));

    updateStyleSample();

    m_styleNames.clear();
    m_styleNames.append(tr("Default paragraph style"));
    m_styleNames.append(tr("Title"));
    m_styleNames.append(tr("Subtitle"));
    m_styleNames.append(tr("Preformatted text"));
    m_styleNames.append(tr("Link"));
    m_styleNames.append(tr("Cite / quotation"));
    m_styleNames.append(tr("Epigraph"));
    m_styleNames.append(tr("Poem"));
    m_styleNames.append(tr("Text author"));
    m_styleNames.append(tr("Footnote link"));
    m_styleNames.append(tr("Footnote"));
    m_styleNames.append(tr("Footnote title"));
    m_styleNames.append(tr("Annotation"));
    m_ui->cbStyleName->clear();
    m_ui->cbStyleName->addItems(m_styleNames);
    m_ui->cbStyleName->setCurrentIndex(0);
    initStyleControls("def");

    initDone = true;

    //m_ui->cbPageSkin->addItem(QString("[None]"), QVariant());
}
Example #3
0
void SearchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
    QStyleOptionViewItem opt(option);

    QStyle *style = opt.widget->style();

    // Find decoration roles with data present.
    QList<int> roles;
    for (int role : m_decorationRoles) {
        if (!index.data(role).isNull())
            roles.append(role);
    }

    /// TODO: Implemented via initStyleOption() overload
    if (!roles.isEmpty()) {
        opt.features |= QStyleOptionViewItem::HasDecoration;
        opt.icon = index.data(roles.first()).value<QIcon>();

        const QSize actualSize = opt.icon.actualSize(opt.decorationSize);
        opt.decorationSize = {std::min(opt.decorationSize.width(), actualSize.width()),
                              std::min(opt.decorationSize.height(), actualSize.height())};
    }

    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

    const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, opt.widget) + 1;

    if (!roles.isEmpty()) {
        QIcon::Mode mode = QIcon::Normal;
        if (!(opt.state & QStyle::State_Enabled))
            mode = QIcon::Disabled;
        else if (opt.state & QStyle::State_Selected)
            mode = QIcon::Selected;
        const QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;

        // All icons are sized after the first one.
        QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, opt.widget);
        const int dx = iconRect.width() + margin;

        for (int i = 1; i < roles.size(); ++i) {
            opt.decorationSize.rwidth() += dx;
            iconRect.translate(dx, 0);

            const QIcon icon = index.data(roles[i]).value<QIcon>();
            icon.paint(painter, iconRect, opt.decorationAlignment, mode, state);
        }
    }

    // Match QCommonStyle behaviour.
    const QString text = index.data().toString();
    const QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget)
            .adjusted(margin, 0, -margin, 0);

    const QFontMetrics &fm = opt.fontMetrics;
    const QString elidedText = fm.elidedText(text, opt.textElideMode, textRect.width());

    if (!m_highlight.isEmpty()) {
        painter->save();
        painter->setRenderHint(QPainter::Antialiasing);
        painter->setPen(QColor::fromRgb(255, 253, 0));

        const QColor highlightColor = opt.state & (QStyle::State_Selected | QStyle::State_HasFocus)
                ? QColor::fromRgb(255, 255, 100, 20) : QColor::fromRgb(255, 255, 100, 120);

        for (int i = 0;;) {
            const int matchIndex = text.indexOf(m_highlight, i, Qt::CaseInsensitive);
            if (matchIndex == -1 || matchIndex >= elidedText.length() - 1)
                break;

            QRect highlightRect
                    = textRect.adjusted(fm.width(elidedText.left(matchIndex)), 2, 0, -2);
            highlightRect.setWidth(fm.width(elidedText.mid(matchIndex, m_highlight.length())));

            QPainterPath path;
            path.addRoundedRect(highlightRect, 2, 2);

            painter->fillPath(path, highlightColor);
            painter->drawPath(path);

            i = matchIndex + m_highlight.length();
        }

        painter->restore();
    }

    painter->save();

#ifdef Q_OS_WIN32
    // QWindowsVistaStyle overrides highlight colour.
    if (style->objectName() == QStringLiteral("windowsvista")) {
        opt.palette.setColor(QPalette::All, QPalette::HighlightedText,
                             opt.palette.color(QPalette::Active, QPalette::Text));
    }
#endif

    const QPalette::ColorGroup cg = opt.state & QStyle::State_Active
            ? QPalette::Normal : QPalette::Inactive;

    if (opt.state & QStyle::State_Selected)
        painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
    else
        painter->setPen(opt.palette.color(cg, QPalette::Text));

    // Vertically align the text in the middle to match QCommonStyle behaviour.
    const QRect alignedRect = QStyle::alignedRect(opt.direction, opt.displayAlignment,
                                                  QSize(1, fm.height()), textRect);
    painter->drawText(QPoint(alignedRect.x(), alignedRect.y() + fm.ascent()), elidedText);
    painter->restore();
}