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());
}
SettingsDlg::SettingsDlg(QWidget *parent, CR3View * docView ) :
    QDialog(parent),
    m_ui(new Ui::SettingsDlg),
    m_docview( docView )
{
    initDone = false;

    m_ui->setupUi(this);

    addAction(m_ui->actionSaveSettings);
    addAction(m_ui->actionNextTab);
    addAction(m_ui->actionPrevTab);

    m_props = m_docview->getOptions();
    optionToUi(PROP_FOOTNOTES, m_ui->ShowFootNotes);
    optionToUi(PROP_SHOW_BATTERY, m_ui->ShowBattery);
    optionToUi(PROP_SHOW_BATTERY_PERCENT, m_ui->ShowBatteryInPercent);
    optionToUi(PROP_SHOW_TIME, m_ui->ShowClock);
    optionToUi(PROP_SHOW_TITLE, m_ui->ShowBookName);
    optionToUi(PROP_TXT_OPTION_PREFORMATTED, m_ui->TxtPreFormatted);
    optionToUi(PROP_FLOATING_PUNCTUATION, m_ui->FloatingPunctuation);
    optionToUi(PROP_STATUS_CHAPTER_MARKS, m_ui->ChapterMarks);
    optionToUi(PROP_SHOW_POS_PERCENT, m_ui->PositionPercent);
    optionToUi(PROP_FONT_WEIGHT_EMBOLDEN, m_ui->cbEmbolden);
    optionToUi(PROP_FONT_KERNING_ENABLED, m_ui->cbKerning);

    int state1 = m_props->getIntDef(PROP_SHOW_PAGE_NUMBER, 1);
    int state2 = m_props->getIntDef(PROP_SHOW_PAGE_COUNT, 1);
    m_ui->PageNumber->setCheckState(state1==1 || state2==1? Qt::Checked : Qt::Unchecked);

    optionToUiInversed(PROP_STATUS_LINE, m_ui->ShowPageHeader);
    bool checked = !(m_props->getIntDef(PROP_STATUS_LINE, 1)==1);
    SwitchCBs(checked);

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

    int lp = m_props->getIntDef(PROP_LANDSCAPE_PAGES, 2);
    m_ui->cbViewMode->setCurrentIndex(lp==1 ? 0 : 1);

    on_cbMarginSide_currentIndexChanged(0);

    QStringList faceList;
    crGetFontFaceList(faceList);
    m_ui->cbTextFontFace->addItems(faceList);
    m_ui->cbTitleFontFace->addItems(faceList);

    m_ui->sbTextFontSize->setMinimum(MIN_CR_FONT_SIZE);
    m_ui->sbTextFontSize->setMaximum(MAX_CR_FONT_SIZE);
    m_ui->sbTitleFontSize->setMinimum(MIN_CR_HEADER_FONT_SIZE);
    m_ui->sbTitleFontSize->setMaximum(MAX_CR_HEADER_FONT_SIZE);

    const char * defFontFace = "Arial";
    static const char * goodFonts[] = { "Arial", "Verdana", NULL };
    for(int i=0; goodFonts[i]; i++) {
        if(faceList.indexOf(QString(goodFonts[i]))>=0) {
            defFontFace = goodFonts[i];
            break;
        }
    }

    fontToUi(PROP_FONT_FACE, PROP_FONT_SIZE, m_ui->cbTextFontFace, m_ui->sbTextFontSize, defFontFace);
    fontToUi(PROP_STATUS_FONT_FACE, PROP_STATUS_FONT_SIZE, m_ui->cbTitleFontFace, m_ui->sbTitleFontSize, defFontFace);

    m_ui->sbInterlineSpace->setValue(m_props->getIntDef(PROP_INTERLINE_SPACE, 100));

    m_ui->sbSpaceCond->setValue(m_props->getIntDef(PROP_FORMAT_MIN_SPACE_CONDENSING_PERCENT, DEF_MIN_SPACE_CONDENSING_PERCENT));
    m_ui->cbAA->setCurrentIndex(m_props->getIntDef(PROP_FONT_ANTIALIASING, font_aa_all));
    m_ui->cbHinting->setCurrentIndex(m_props->getIntDef(PROP_FONT_HINTING, HINTING_MODE_AUTOHINT));

    int updateEvery = m_props->getIntDef(PROP_DISPLAY_FULL_UPDATE_INTERVAL, 1);
    int upIndex = m_ui->cbFullUpdateEvery->findText(QString::number(updateEvery));
    m_ui->cbFullUpdateEvery->setCurrentIndex(upIndex != -1 ? upIndex : 1);

    // translations
    QString v = m_props->getStringDef(PROP_WINDOW_LANG, "English");
    QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/i18n")));
    QStringList Filter;
    Filter << "*.qm";
    QStringList Files = Dir.entryList(Filter, QDir::Files, QDir::Name);
    m_ui->cbLanguage->addItem("English");
    foreach(const QString &str, Files) {
        QString s = str;
        s.chop(3);
        m_ui->cbLanguage->addItem(s);
    }